AMDILCFGStructurizer.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  1. //===-- AMDILCFGStructurizer.cpp - CFG Structurizer -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. /// \file
  9. //==-----------------------------------------------------------------------===//
  10. #define DEBUG_TYPE "structcfg"
  11. #include "AMDGPU.h"
  12. #include "AMDGPUInstrInfo.h"
  13. #include "R600InstrInfo.h"
  14. #include "llvm/ADT/DepthFirstIterator.h"
  15. #include "llvm/ADT/SCCIterator.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/CodeGen/MachineDominators.h"
  19. #include "llvm/CodeGen/MachineFunction.h"
  20. #include "llvm/CodeGen/MachineFunctionAnalysis.h"
  21. #include "llvm/CodeGen/MachineFunctionPass.h"
  22. #include "llvm/CodeGen/MachineInstrBuilder.h"
  23. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  24. #include "llvm/CodeGen/MachineLoopInfo.h"
  25. #include "llvm/CodeGen/MachinePostDominators.h"
  26. #include "llvm/CodeGen/MachineRegisterInfo.h"
  27. #include "llvm/IR/Dominators.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/Target/TargetInstrInfo.h"
  31. #include "llvm/Target/TargetMachine.h"
  32. using namespace llvm;
  33. #define DEFAULT_VEC_SLOTS 8
  34. // TODO: move-begin.
  35. //===----------------------------------------------------------------------===//
  36. //
  37. // Statistics for CFGStructurizer.
  38. //
  39. //===----------------------------------------------------------------------===//
  40. STATISTIC(numSerialPatternMatch, "CFGStructurizer number of serial pattern "
  41. "matched");
  42. STATISTIC(numIfPatternMatch, "CFGStructurizer number of if pattern "
  43. "matched");
  44. STATISTIC(numLoopcontPatternMatch, "CFGStructurizer number of loop-continue "
  45. "pattern matched");
  46. STATISTIC(numClonedBlock, "CFGStructurizer cloned blocks");
  47. STATISTIC(numClonedInstr, "CFGStructurizer cloned instructions");
  48. namespace llvm {
  49. void initializeAMDGPUCFGStructurizerPass(PassRegistry&);
  50. }
  51. //===----------------------------------------------------------------------===//
  52. //
  53. // Miscellaneous utility for CFGStructurizer.
  54. //
  55. //===----------------------------------------------------------------------===//
  56. namespace {
  57. #define SHOWNEWINSTR(i) \
  58. DEBUG(dbgs() << "New instr: " << *i << "\n");
  59. #define SHOWNEWBLK(b, msg) \
  60. DEBUG( \
  61. dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
  62. dbgs() << "\n"; \
  63. );
  64. #define SHOWBLK_DETAIL(b, msg) \
  65. DEBUG( \
  66. if (b) { \
  67. dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
  68. b->print(dbgs()); \
  69. dbgs() << "\n"; \
  70. } \
  71. );
  72. #define INVALIDSCCNUM -1
  73. template<class NodeT>
  74. void ReverseVector(SmallVectorImpl<NodeT *> &Src) {
  75. size_t sz = Src.size();
  76. for (size_t i = 0; i < sz/2; ++i) {
  77. NodeT *t = Src[i];
  78. Src[i] = Src[sz - i - 1];
  79. Src[sz - i - 1] = t;
  80. }
  81. }
  82. } // end anonymous namespace
  83. //===----------------------------------------------------------------------===//
  84. //
  85. // supporting data structure for CFGStructurizer
  86. //
  87. //===----------------------------------------------------------------------===//
  88. namespace {
  89. class BlockInformation {
  90. public:
  91. bool IsRetired;
  92. int SccNum;
  93. BlockInformation() : IsRetired(false), SccNum(INVALIDSCCNUM) {}
  94. };
  95. } // end anonymous namespace
  96. //===----------------------------------------------------------------------===//
  97. //
  98. // CFGStructurizer
  99. //
  100. //===----------------------------------------------------------------------===//
  101. namespace {
  102. class AMDGPUCFGStructurizer : public MachineFunctionPass {
  103. public:
  104. typedef SmallVector<MachineBasicBlock *, 32> MBBVector;
  105. typedef std::map<MachineBasicBlock *, BlockInformation *> MBBInfoMap;
  106. typedef std::map<MachineLoop *, MachineBasicBlock *> LoopLandInfoMap;
  107. enum PathToKind {
  108. Not_SinglePath = 0,
  109. SinglePath_InPath = 1,
  110. SinglePath_NotInPath = 2
  111. };
  112. static char ID;
  113. AMDGPUCFGStructurizer() :
  114. MachineFunctionPass(ID), TII(NULL), TRI(NULL) {
  115. initializeAMDGPUCFGStructurizerPass(*PassRegistry::getPassRegistry());
  116. }
  117. const char *getPassName() const {
  118. return "AMDGPU Control Flow Graph structurizer Pass";
  119. }
  120. void getAnalysisUsage(AnalysisUsage &AU) const {
  121. AU.addPreserved<MachineFunctionAnalysis>();
  122. AU.addRequired<MachineFunctionAnalysis>();
  123. AU.addRequired<MachineDominatorTree>();
  124. AU.addRequired<MachinePostDominatorTree>();
  125. AU.addRequired<MachineLoopInfo>();
  126. }
  127. /// Perform the CFG structurization
  128. bool run();
  129. /// Perform the CFG preparation
  130. /// This step will remove every unconditionnal/dead jump instructions and make
  131. /// sure all loops have an exit block
  132. bool prepare();
  133. bool runOnMachineFunction(MachineFunction &MF) {
  134. TII = static_cast<const R600InstrInfo *>(MF.getTarget().getInstrInfo());
  135. TRI = &TII->getRegisterInfo();
  136. DEBUG(MF.dump(););
  137. OrderedBlks.clear();
  138. FuncRep = &MF;
  139. MLI = &getAnalysis<MachineLoopInfo>();
  140. DEBUG(dbgs() << "LoopInfo:\n"; PrintLoopinfo(*MLI););
  141. MDT = &getAnalysis<MachineDominatorTree>();
  142. DEBUG(MDT->print(dbgs(), (const llvm::Module*)0););
  143. PDT = &getAnalysis<MachinePostDominatorTree>();
  144. DEBUG(PDT->print(dbgs()););
  145. prepare();
  146. run();
  147. DEBUG(MF.dump(););
  148. return true;
  149. }
  150. protected:
  151. MachineDominatorTree *MDT;
  152. MachinePostDominatorTree *PDT;
  153. MachineLoopInfo *MLI;
  154. const R600InstrInfo *TII;
  155. const AMDGPURegisterInfo *TRI;
  156. // PRINT FUNCTIONS
  157. /// Print the ordered Blocks.
  158. void printOrderedBlocks() const {
  159. size_t i = 0;
  160. for (MBBVector::const_iterator iterBlk = OrderedBlks.begin(),
  161. iterBlkEnd = OrderedBlks.end(); iterBlk != iterBlkEnd; ++iterBlk, ++i) {
  162. dbgs() << "BB" << (*iterBlk)->getNumber();
  163. dbgs() << "(" << getSCCNum(*iterBlk) << "," << (*iterBlk)->size() << ")";
  164. if (i != 0 && i % 10 == 0) {
  165. dbgs() << "\n";
  166. } else {
  167. dbgs() << " ";
  168. }
  169. }
  170. }
  171. static void PrintLoopinfo(const MachineLoopInfo &LoopInfo) {
  172. for (MachineLoop::iterator iter = LoopInfo.begin(),
  173. iterEnd = LoopInfo.end(); iter != iterEnd; ++iter) {
  174. (*iter)->print(dbgs(), 0);
  175. }
  176. }
  177. // UTILITY FUNCTIONS
  178. int getSCCNum(MachineBasicBlock *MBB) const;
  179. MachineBasicBlock *getLoopLandInfo(MachineLoop *LoopRep) const;
  180. bool hasBackEdge(MachineBasicBlock *MBB) const;
  181. static unsigned getLoopDepth(MachineLoop *LoopRep);
  182. bool isRetiredBlock(MachineBasicBlock *MBB) const;
  183. bool isActiveLoophead(MachineBasicBlock *MBB) const;
  184. PathToKind singlePathTo(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
  185. bool AllowSideEntry = true) const;
  186. int countActiveBlock(MBBVector::const_iterator It,
  187. MBBVector::const_iterator E) const;
  188. bool needMigrateBlock(MachineBasicBlock *MBB) const;
  189. // Utility Functions
  190. void reversePredicateSetter(MachineBasicBlock::iterator I);
  191. /// Compute the reversed DFS post order of Blocks
  192. void orderBlocks(MachineFunction *MF);
  193. // Function originally from CFGStructTraits
  194. void insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode,
  195. DebugLoc DL = DebugLoc());
  196. MachineInstr *insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode,
  197. DebugLoc DL = DebugLoc());
  198. MachineInstr *insertInstrBefore(MachineBasicBlock::iterator I, int NewOpcode);
  199. void insertCondBranchBefore(MachineBasicBlock::iterator I, int NewOpcode,
  200. DebugLoc DL);
  201. void insertCondBranchBefore(MachineBasicBlock *MBB,
  202. MachineBasicBlock::iterator I, int NewOpcode, int RegNum,
  203. DebugLoc DL);
  204. void insertCondBranchEnd(MachineBasicBlock *MBB, int NewOpcode, int RegNum);
  205. static int getBranchNzeroOpcode(int OldOpcode);
  206. static int getBranchZeroOpcode(int OldOpcode);
  207. static int getContinueNzeroOpcode(int OldOpcode);
  208. static int getContinueZeroOpcode(int OldOpcode);
  209. static MachineBasicBlock *getTrueBranch(MachineInstr *MI);
  210. static void setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB);
  211. static MachineBasicBlock *getFalseBranch(MachineBasicBlock *MBB,
  212. MachineInstr *MI);
  213. static bool isCondBranch(MachineInstr *MI);
  214. static bool isUncondBranch(MachineInstr *MI);
  215. static DebugLoc getLastDebugLocInBB(MachineBasicBlock *MBB);
  216. static MachineInstr *getNormalBlockBranchInstr(MachineBasicBlock *MBB);
  217. /// The correct naming for this is getPossibleLoopendBlockBranchInstr.
  218. ///
  219. /// BB with backward-edge could have move instructions after the branch
  220. /// instruction. Such move instruction "belong to" the loop backward-edge.
  221. MachineInstr *getLoopendBlockBranchInstr(MachineBasicBlock *MBB);
  222. static MachineInstr *getReturnInstr(MachineBasicBlock *MBB);
  223. static MachineInstr *getContinueInstr(MachineBasicBlock *MBB);
  224. static bool isReturnBlock(MachineBasicBlock *MBB);
  225. static void cloneSuccessorList(MachineBasicBlock *DstMBB,
  226. MachineBasicBlock *SrcMBB) ;
  227. static MachineBasicBlock *clone(MachineBasicBlock *MBB);
  228. /// MachineBasicBlock::ReplaceUsesOfBlockWith doesn't serve the purpose
  229. /// because the AMDGPU instruction is not recognized as terminator fix this
  230. /// and retire this routine
  231. void replaceInstrUseOfBlockWith(MachineBasicBlock *SrcMBB,
  232. MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk);
  233. static void wrapup(MachineBasicBlock *MBB);
  234. int patternMatch(MachineBasicBlock *MBB);
  235. int patternMatchGroup(MachineBasicBlock *MBB);
  236. int serialPatternMatch(MachineBasicBlock *MBB);
  237. int ifPatternMatch(MachineBasicBlock *MBB);
  238. int loopendPatternMatch();
  239. int mergeLoop(MachineLoop *LoopRep);
  240. int loopcontPatternMatch(MachineLoop *LoopRep, MachineBasicBlock *LoopHeader);
  241. void handleLoopcontBlock(MachineBasicBlock *ContingMBB,
  242. MachineLoop *ContingLoop, MachineBasicBlock *ContMBB,
  243. MachineLoop *ContLoop);
  244. /// return true iff src1Blk->succ_size() == 0 && src1Blk and src2Blk are in
  245. /// the same loop with LoopLandInfo without explicitly keeping track of
  246. /// loopContBlks and loopBreakBlks, this is a method to get the information.
  247. bool isSameloopDetachedContbreak(MachineBasicBlock *Src1MBB,
  248. MachineBasicBlock *Src2MBB);
  249. int handleJumpintoIf(MachineBasicBlock *HeadMBB,
  250. MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
  251. int handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
  252. MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
  253. int improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
  254. MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
  255. MachineBasicBlock **LandMBBPtr);
  256. void showImproveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
  257. MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
  258. MachineBasicBlock *LandMBB, bool Detail = false);
  259. int cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
  260. MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB);
  261. void mergeSerialBlock(MachineBasicBlock *DstMBB,
  262. MachineBasicBlock *SrcMBB);
  263. void mergeIfthenelseBlock(MachineInstr *BranchMI,
  264. MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
  265. MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB);
  266. void mergeLooplandBlock(MachineBasicBlock *DstMBB,
  267. MachineBasicBlock *LandMBB);
  268. void mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
  269. MachineBasicBlock *LandMBB);
  270. void settleLoopcontBlock(MachineBasicBlock *ContingMBB,
  271. MachineBasicBlock *ContMBB);
  272. /// normalizeInfiniteLoopExit change
  273. /// B1:
  274. /// uncond_br LoopHeader
  275. ///
  276. /// to
  277. /// B1:
  278. /// cond_br 1 LoopHeader dummyExit
  279. /// and return the newly added dummy exit block
  280. MachineBasicBlock *normalizeInfiniteLoopExit(MachineLoop *LoopRep);
  281. void removeUnconditionalBranch(MachineBasicBlock *MBB);
  282. /// Remove duplicate branches instructions in a block.
  283. /// For instance
  284. /// B0:
  285. /// cond_br X B1 B2
  286. /// cond_br X B1 B2
  287. /// is transformed to
  288. /// B0:
  289. /// cond_br X B1 B2
  290. void removeRedundantConditionalBranch(MachineBasicBlock *MBB);
  291. void addDummyExitBlock(SmallVectorImpl<MachineBasicBlock *> &RetMBB);
  292. void removeSuccessor(MachineBasicBlock *MBB);
  293. MachineBasicBlock *cloneBlockForPredecessor(MachineBasicBlock *MBB,
  294. MachineBasicBlock *PredMBB);
  295. void migrateInstruction(MachineBasicBlock *SrcMBB,
  296. MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I);
  297. void recordSccnum(MachineBasicBlock *MBB, int SCCNum);
  298. void retireBlock(MachineBasicBlock *MBB);
  299. void setLoopLandBlock(MachineLoop *LoopRep, MachineBasicBlock *MBB = NULL);
  300. MachineBasicBlock *findNearestCommonPostDom(std::set<MachineBasicBlock *>&);
  301. /// This is work around solution for findNearestCommonDominator not avaiable
  302. /// to post dom a proper fix should go to Dominators.h.
  303. MachineBasicBlock *findNearestCommonPostDom(MachineBasicBlock *MBB1,
  304. MachineBasicBlock *MBB2);
  305. private:
  306. MBBInfoMap BlockInfoMap;
  307. LoopLandInfoMap LLInfoMap;
  308. std::map<MachineLoop *, bool> Visited;
  309. MachineFunction *FuncRep;
  310. SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> OrderedBlks;
  311. };
  312. int AMDGPUCFGStructurizer::getSCCNum(MachineBasicBlock *MBB) const {
  313. MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
  314. if (It == BlockInfoMap.end())
  315. return INVALIDSCCNUM;
  316. return (*It).second->SccNum;
  317. }
  318. MachineBasicBlock *AMDGPUCFGStructurizer::getLoopLandInfo(MachineLoop *LoopRep)
  319. const {
  320. LoopLandInfoMap::const_iterator It = LLInfoMap.find(LoopRep);
  321. if (It == LLInfoMap.end())
  322. return NULL;
  323. return (*It).second;
  324. }
  325. bool AMDGPUCFGStructurizer::hasBackEdge(MachineBasicBlock *MBB) const {
  326. MachineLoop *LoopRep = MLI->getLoopFor(MBB);
  327. if (!LoopRep)
  328. return false;
  329. MachineBasicBlock *LoopHeader = LoopRep->getHeader();
  330. return MBB->isSuccessor(LoopHeader);
  331. }
  332. unsigned AMDGPUCFGStructurizer::getLoopDepth(MachineLoop *LoopRep) {
  333. return LoopRep ? LoopRep->getLoopDepth() : 0;
  334. }
  335. bool AMDGPUCFGStructurizer::isRetiredBlock(MachineBasicBlock *MBB) const {
  336. MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
  337. if (It == BlockInfoMap.end())
  338. return false;
  339. return (*It).second->IsRetired;
  340. }
  341. bool AMDGPUCFGStructurizer::isActiveLoophead(MachineBasicBlock *MBB) const {
  342. MachineLoop *LoopRep = MLI->getLoopFor(MBB);
  343. while (LoopRep && LoopRep->getHeader() == MBB) {
  344. MachineBasicBlock *LoopLand = getLoopLandInfo(LoopRep);
  345. if(!LoopLand)
  346. return true;
  347. if (!isRetiredBlock(LoopLand))
  348. return true;
  349. LoopRep = LoopRep->getParentLoop();
  350. }
  351. return false;
  352. }
  353. AMDGPUCFGStructurizer::PathToKind AMDGPUCFGStructurizer::singlePathTo(
  354. MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
  355. bool AllowSideEntry) const {
  356. assert(DstMBB);
  357. if (SrcMBB == DstMBB)
  358. return SinglePath_InPath;
  359. while (SrcMBB && SrcMBB->succ_size() == 1) {
  360. SrcMBB = *SrcMBB->succ_begin();
  361. if (SrcMBB == DstMBB)
  362. return SinglePath_InPath;
  363. if (!AllowSideEntry && SrcMBB->pred_size() > 1)
  364. return Not_SinglePath;
  365. }
  366. if (SrcMBB && SrcMBB->succ_size()==0)
  367. return SinglePath_NotInPath;
  368. return Not_SinglePath;
  369. }
  370. int AMDGPUCFGStructurizer::countActiveBlock(MBBVector::const_iterator It,
  371. MBBVector::const_iterator E) const {
  372. int Count = 0;
  373. while (It != E) {
  374. if (!isRetiredBlock(*It))
  375. ++Count;
  376. ++It;
  377. }
  378. return Count;
  379. }
  380. bool AMDGPUCFGStructurizer::needMigrateBlock(MachineBasicBlock *MBB) const {
  381. unsigned BlockSizeThreshold = 30;
  382. unsigned CloneInstrThreshold = 100;
  383. bool MultiplePreds = MBB && (MBB->pred_size() > 1);
  384. if(!MultiplePreds)
  385. return false;
  386. unsigned BlkSize = MBB->size();
  387. return ((BlkSize > BlockSizeThreshold) &&
  388. (BlkSize * (MBB->pred_size() - 1) > CloneInstrThreshold));
  389. }
  390. void AMDGPUCFGStructurizer::reversePredicateSetter(
  391. MachineBasicBlock::iterator I) {
  392. while (I--) {
  393. if (I->getOpcode() == AMDGPU::PRED_X) {
  394. switch (static_cast<MachineInstr *>(I)->getOperand(2).getImm()) {
  395. case OPCODE_IS_ZERO_INT:
  396. static_cast<MachineInstr *>(I)->getOperand(2)
  397. .setImm(OPCODE_IS_NOT_ZERO_INT);
  398. return;
  399. case OPCODE_IS_NOT_ZERO_INT:
  400. static_cast<MachineInstr *>(I)->getOperand(2)
  401. .setImm(OPCODE_IS_ZERO_INT);
  402. return;
  403. case OPCODE_IS_ZERO:
  404. static_cast<MachineInstr *>(I)->getOperand(2)
  405. .setImm(OPCODE_IS_NOT_ZERO);
  406. return;
  407. case OPCODE_IS_NOT_ZERO:
  408. static_cast<MachineInstr *>(I)->getOperand(2)
  409. .setImm(OPCODE_IS_ZERO);
  410. return;
  411. default:
  412. llvm_unreachable("PRED_X Opcode invalid!");
  413. }
  414. }
  415. }
  416. }
  417. void AMDGPUCFGStructurizer::insertInstrEnd(MachineBasicBlock *MBB,
  418. int NewOpcode, DebugLoc DL) {
  419. MachineInstr *MI = MBB->getParent()
  420. ->CreateMachineInstr(TII->get(NewOpcode), DL);
  421. MBB->push_back(MI);
  422. //assume the instruction doesn't take any reg operand ...
  423. SHOWNEWINSTR(MI);
  424. }
  425. MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(MachineBasicBlock *MBB,
  426. int NewOpcode, DebugLoc DL) {
  427. MachineInstr *MI =
  428. MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
  429. if (MBB->begin() != MBB->end())
  430. MBB->insert(MBB->begin(), MI);
  431. else
  432. MBB->push_back(MI);
  433. SHOWNEWINSTR(MI);
  434. return MI;
  435. }
  436. MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(
  437. MachineBasicBlock::iterator I, int NewOpcode) {
  438. MachineInstr *OldMI = &(*I);
  439. MachineBasicBlock *MBB = OldMI->getParent();
  440. MachineInstr *NewMBB =
  441. MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DebugLoc());
  442. MBB->insert(I, NewMBB);
  443. //assume the instruction doesn't take any reg operand ...
  444. SHOWNEWINSTR(NewMBB);
  445. return NewMBB;
  446. }
  447. void AMDGPUCFGStructurizer::insertCondBranchBefore(
  448. MachineBasicBlock::iterator I, int NewOpcode, DebugLoc DL) {
  449. MachineInstr *OldMI = &(*I);
  450. MachineBasicBlock *MBB = OldMI->getParent();
  451. MachineFunction *MF = MBB->getParent();
  452. MachineInstr *NewMI = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
  453. MBB->insert(I, NewMI);
  454. MachineInstrBuilder MIB(*MF, NewMI);
  455. MIB.addReg(OldMI->getOperand(1).getReg(), false);
  456. SHOWNEWINSTR(NewMI);
  457. //erase later oldInstr->eraseFromParent();
  458. }
  459. void AMDGPUCFGStructurizer::insertCondBranchBefore(MachineBasicBlock *blk,
  460. MachineBasicBlock::iterator I, int NewOpcode, int RegNum,
  461. DebugLoc DL) {
  462. MachineFunction *MF = blk->getParent();
  463. MachineInstr *NewInstr = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
  464. //insert before
  465. blk->insert(I, NewInstr);
  466. MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false);
  467. SHOWNEWINSTR(NewInstr);
  468. }
  469. void AMDGPUCFGStructurizer::insertCondBranchEnd(MachineBasicBlock *MBB,
  470. int NewOpcode, int RegNum) {
  471. MachineFunction *MF = MBB->getParent();
  472. MachineInstr *NewInstr =
  473. MF->CreateMachineInstr(TII->get(NewOpcode), DebugLoc());
  474. MBB->push_back(NewInstr);
  475. MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false);
  476. SHOWNEWINSTR(NewInstr);
  477. }
  478. int AMDGPUCFGStructurizer::getBranchNzeroOpcode(int OldOpcode) {
  479. switch(OldOpcode) {
  480. case AMDGPU::JUMP_COND:
  481. case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
  482. case AMDGPU::BRANCH_COND_i32:
  483. case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALNZ_f32;
  484. default: llvm_unreachable("internal error");
  485. }
  486. return -1;
  487. }
  488. int AMDGPUCFGStructurizer::getBranchZeroOpcode(int OldOpcode) {
  489. switch(OldOpcode) {
  490. case AMDGPU::JUMP_COND:
  491. case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
  492. case AMDGPU::BRANCH_COND_i32:
  493. case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALZ_f32;
  494. default: llvm_unreachable("internal error");
  495. }
  496. return -1;
  497. }
  498. int AMDGPUCFGStructurizer::getContinueNzeroOpcode(int OldOpcode) {
  499. switch(OldOpcode) {
  500. case AMDGPU::JUMP_COND:
  501. case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALNZ_i32;
  502. default: llvm_unreachable("internal error");
  503. };
  504. return -1;
  505. }
  506. int AMDGPUCFGStructurizer::getContinueZeroOpcode(int OldOpcode) {
  507. switch(OldOpcode) {
  508. case AMDGPU::JUMP_COND:
  509. case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALZ_i32;
  510. default: llvm_unreachable("internal error");
  511. }
  512. return -1;
  513. }
  514. MachineBasicBlock *AMDGPUCFGStructurizer::getTrueBranch(MachineInstr *MI) {
  515. return MI->getOperand(0).getMBB();
  516. }
  517. void AMDGPUCFGStructurizer::setTrueBranch(MachineInstr *MI,
  518. MachineBasicBlock *MBB) {
  519. MI->getOperand(0).setMBB(MBB);
  520. }
  521. MachineBasicBlock *
  522. AMDGPUCFGStructurizer::getFalseBranch(MachineBasicBlock *MBB,
  523. MachineInstr *MI) {
  524. assert(MBB->succ_size() == 2);
  525. MachineBasicBlock *TrueBranch = getTrueBranch(MI);
  526. MachineBasicBlock::succ_iterator It = MBB->succ_begin();
  527. MachineBasicBlock::succ_iterator Next = It;
  528. ++Next;
  529. return (*It == TrueBranch) ? *Next : *It;
  530. }
  531. bool AMDGPUCFGStructurizer::isCondBranch(MachineInstr *MI) {
  532. switch (MI->getOpcode()) {
  533. case AMDGPU::JUMP_COND:
  534. case AMDGPU::BRANCH_COND_i32:
  535. case AMDGPU::BRANCH_COND_f32: return true;
  536. default:
  537. return false;
  538. }
  539. return false;
  540. }
  541. bool AMDGPUCFGStructurizer::isUncondBranch(MachineInstr *MI) {
  542. switch (MI->getOpcode()) {
  543. case AMDGPU::JUMP:
  544. case AMDGPU::BRANCH:
  545. return true;
  546. default:
  547. return false;
  548. }
  549. return false;
  550. }
  551. DebugLoc AMDGPUCFGStructurizer::getLastDebugLocInBB(MachineBasicBlock *MBB) {
  552. //get DebugLoc from the first MachineBasicBlock instruction with debug info
  553. DebugLoc DL;
  554. for (MachineBasicBlock::iterator It = MBB->begin(); It != MBB->end();
  555. ++It) {
  556. MachineInstr *instr = &(*It);
  557. if (instr->getDebugLoc().isUnknown() == false)
  558. DL = instr->getDebugLoc();
  559. }
  560. return DL;
  561. }
  562. MachineInstr *AMDGPUCFGStructurizer::getNormalBlockBranchInstr(
  563. MachineBasicBlock *MBB) {
  564. MachineBasicBlock::reverse_iterator It = MBB->rbegin();
  565. MachineInstr *MI = &*It;
  566. if (MI && (isCondBranch(MI) || isUncondBranch(MI)))
  567. return MI;
  568. return NULL;
  569. }
  570. MachineInstr *AMDGPUCFGStructurizer::getLoopendBlockBranchInstr(
  571. MachineBasicBlock *MBB) {
  572. for (MachineBasicBlock::reverse_iterator It = MBB->rbegin(), E = MBB->rend();
  573. It != E; ++It) {
  574. // FIXME: Simplify
  575. MachineInstr *MI = &*It;
  576. if (MI) {
  577. if (isCondBranch(MI) || isUncondBranch(MI))
  578. return MI;
  579. else if (!TII->isMov(MI->getOpcode()))
  580. break;
  581. }
  582. }
  583. return NULL;
  584. }
  585. MachineInstr *AMDGPUCFGStructurizer::getReturnInstr(MachineBasicBlock *MBB) {
  586. MachineBasicBlock::reverse_iterator It = MBB->rbegin();
  587. if (It != MBB->rend()) {
  588. MachineInstr *instr = &(*It);
  589. if (instr->getOpcode() == AMDGPU::RETURN)
  590. return instr;
  591. }
  592. return NULL;
  593. }
  594. MachineInstr *AMDGPUCFGStructurizer::getContinueInstr(MachineBasicBlock *MBB) {
  595. MachineBasicBlock::reverse_iterator It = MBB->rbegin();
  596. if (It != MBB->rend()) {
  597. MachineInstr *MI = &(*It);
  598. if (MI->getOpcode() == AMDGPU::CONTINUE)
  599. return MI;
  600. }
  601. return NULL;
  602. }
  603. bool AMDGPUCFGStructurizer::isReturnBlock(MachineBasicBlock *MBB) {
  604. MachineInstr *MI = getReturnInstr(MBB);
  605. bool IsReturn = (MBB->succ_size() == 0);
  606. if (MI)
  607. assert(IsReturn);
  608. else if (IsReturn)
  609. DEBUG(
  610. dbgs() << "BB" << MBB->getNumber()
  611. <<" is return block without RETURN instr\n";);
  612. return IsReturn;
  613. }
  614. void AMDGPUCFGStructurizer::cloneSuccessorList(MachineBasicBlock *DstMBB,
  615. MachineBasicBlock *SrcMBB) {
  616. for (MachineBasicBlock::succ_iterator It = SrcMBB->succ_begin(),
  617. iterEnd = SrcMBB->succ_end(); It != iterEnd; ++It)
  618. DstMBB->addSuccessor(*It); // *iter's predecessor is also taken care of
  619. }
  620. MachineBasicBlock *AMDGPUCFGStructurizer::clone(MachineBasicBlock *MBB) {
  621. MachineFunction *Func = MBB->getParent();
  622. MachineBasicBlock *NewMBB = Func->CreateMachineBasicBlock();
  623. Func->push_back(NewMBB); //insert to function
  624. for (MachineBasicBlock::iterator It = MBB->begin(), E = MBB->end();
  625. It != E; ++It) {
  626. MachineInstr *MI = Func->CloneMachineInstr(It);
  627. NewMBB->push_back(MI);
  628. }
  629. return NewMBB;
  630. }
  631. void AMDGPUCFGStructurizer::replaceInstrUseOfBlockWith(
  632. MachineBasicBlock *SrcMBB, MachineBasicBlock *OldMBB,
  633. MachineBasicBlock *NewBlk) {
  634. MachineInstr *BranchMI = getLoopendBlockBranchInstr(SrcMBB);
  635. if (BranchMI && isCondBranch(BranchMI) &&
  636. getTrueBranch(BranchMI) == OldMBB)
  637. setTrueBranch(BranchMI, NewBlk);
  638. }
  639. void AMDGPUCFGStructurizer::wrapup(MachineBasicBlock *MBB) {
  640. assert((!MBB->getParent()->getJumpTableInfo()
  641. || MBB->getParent()->getJumpTableInfo()->isEmpty())
  642. && "found a jump table");
  643. //collect continue right before endloop
  644. SmallVector<MachineInstr *, DEFAULT_VEC_SLOTS> ContInstr;
  645. MachineBasicBlock::iterator Pre = MBB->begin();
  646. MachineBasicBlock::iterator E = MBB->end();
  647. MachineBasicBlock::iterator It = Pre;
  648. while (It != E) {
  649. if (Pre->getOpcode() == AMDGPU::CONTINUE
  650. && It->getOpcode() == AMDGPU::ENDLOOP)
  651. ContInstr.push_back(Pre);
  652. Pre = It;
  653. ++It;
  654. }
  655. //delete continue right before endloop
  656. for (unsigned i = 0; i < ContInstr.size(); ++i)
  657. ContInstr[i]->eraseFromParent();
  658. // TODO to fix up jump table so later phase won't be confused. if
  659. // (jumpTableInfo->isEmpty() == false) { need to clean the jump table, but
  660. // there isn't such an interface yet. alternatively, replace all the other
  661. // blocks in the jump table with the entryBlk //}
  662. }
  663. bool AMDGPUCFGStructurizer::prepare() {
  664. bool Changed = false;
  665. //FIXME: if not reducible flow graph, make it so ???
  666. DEBUG(dbgs() << "AMDGPUCFGStructurizer::prepare\n";);
  667. orderBlocks(FuncRep);
  668. SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> RetBlks;
  669. // Add an ExitBlk to loop that don't have one
  670. for (MachineLoopInfo::iterator It = MLI->begin(),
  671. E = MLI->end(); It != E; ++It) {
  672. MachineLoop *LoopRep = (*It);
  673. MBBVector ExitingMBBs;
  674. LoopRep->getExitingBlocks(ExitingMBBs);
  675. if (ExitingMBBs.size() == 0) {
  676. MachineBasicBlock* DummyExitBlk = normalizeInfiniteLoopExit(LoopRep);
  677. if (DummyExitBlk)
  678. RetBlks.push_back(DummyExitBlk);
  679. }
  680. }
  681. // Remove unconditional branch instr.
  682. // Add dummy exit block iff there are multiple returns.
  683. for (SmallVectorImpl<MachineBasicBlock *>::const_iterator
  684. It = OrderedBlks.begin(), E = OrderedBlks.end(); It != E; ++It) {
  685. MachineBasicBlock *MBB = *It;
  686. removeUnconditionalBranch(MBB);
  687. removeRedundantConditionalBranch(MBB);
  688. if (isReturnBlock(MBB)) {
  689. RetBlks.push_back(MBB);
  690. }
  691. assert(MBB->succ_size() <= 2);
  692. }
  693. if (RetBlks.size() >= 2) {
  694. addDummyExitBlock(RetBlks);
  695. Changed = true;
  696. }
  697. return Changed;
  698. }
  699. bool AMDGPUCFGStructurizer::run() {
  700. //Assume reducible CFG...
  701. DEBUG(dbgs() << "AMDGPUCFGStructurizer::run\n";FuncRep->viewCFG(););
  702. #ifdef STRESSTEST
  703. //Use the worse block ordering to test the algorithm.
  704. ReverseVector(orderedBlks);
  705. #endif
  706. DEBUG(dbgs() << "Ordered blocks:\n"; printOrderedBlocks(););
  707. int NumIter = 0;
  708. bool Finish = false;
  709. MachineBasicBlock *MBB;
  710. bool MakeProgress = false;
  711. int NumRemainedBlk = countActiveBlock(OrderedBlks.begin(),
  712. OrderedBlks.end());
  713. do {
  714. ++NumIter;
  715. DEBUG(
  716. dbgs() << "numIter = " << NumIter
  717. << ", numRemaintedBlk = " << NumRemainedBlk << "\n";
  718. );
  719. SmallVectorImpl<MachineBasicBlock *>::const_iterator It =
  720. OrderedBlks.begin();
  721. SmallVectorImpl<MachineBasicBlock *>::const_iterator E =
  722. OrderedBlks.end();
  723. SmallVectorImpl<MachineBasicBlock *>::const_iterator SccBeginIter =
  724. It;
  725. MachineBasicBlock *SccBeginMBB = NULL;
  726. int SccNumBlk = 0; // The number of active blocks, init to a
  727. // maximum possible number.
  728. int SccNumIter; // Number of iteration in this SCC.
  729. while (It != E) {
  730. MBB = *It;
  731. if (!SccBeginMBB) {
  732. SccBeginIter = It;
  733. SccBeginMBB = MBB;
  734. SccNumIter = 0;
  735. SccNumBlk = NumRemainedBlk; // Init to maximum possible number.
  736. DEBUG(
  737. dbgs() << "start processing SCC" << getSCCNum(SccBeginMBB);
  738. dbgs() << "\n";
  739. );
  740. }
  741. if (!isRetiredBlock(MBB))
  742. patternMatch(MBB);
  743. ++It;
  744. bool ContNextScc = true;
  745. if (It == E
  746. || getSCCNum(SccBeginMBB) != getSCCNum(*It)) {
  747. // Just finish one scc.
  748. ++SccNumIter;
  749. int sccRemainedNumBlk = countActiveBlock(SccBeginIter, It);
  750. if (sccRemainedNumBlk != 1 && sccRemainedNumBlk >= SccNumBlk) {
  751. DEBUG(
  752. dbgs() << "Can't reduce SCC " << getSCCNum(MBB)
  753. << ", sccNumIter = " << SccNumIter;
  754. dbgs() << "doesn't make any progress\n";
  755. );
  756. ContNextScc = true;
  757. } else if (sccRemainedNumBlk != 1 && sccRemainedNumBlk < SccNumBlk) {
  758. SccNumBlk = sccRemainedNumBlk;
  759. It = SccBeginIter;
  760. ContNextScc = false;
  761. DEBUG(
  762. dbgs() << "repeat processing SCC" << getSCCNum(MBB)
  763. << "sccNumIter = " << SccNumIter << "\n";
  764. FuncRep->viewCFG();
  765. );
  766. } else {
  767. // Finish the current scc.
  768. ContNextScc = true;
  769. }
  770. } else {
  771. // Continue on next component in the current scc.
  772. ContNextScc = false;
  773. }
  774. if (ContNextScc)
  775. SccBeginMBB = NULL;
  776. } //while, "one iteration" over the function.
  777. MachineBasicBlock *EntryMBB =
  778. GraphTraits<MachineFunction *>::nodes_begin(FuncRep);
  779. if (EntryMBB->succ_size() == 0) {
  780. Finish = true;
  781. DEBUG(
  782. dbgs() << "Reduce to one block\n";
  783. );
  784. } else {
  785. int NewnumRemainedBlk
  786. = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end());
  787. // consider cloned blocks ??
  788. if (NewnumRemainedBlk == 1 || NewnumRemainedBlk < NumRemainedBlk) {
  789. MakeProgress = true;
  790. NumRemainedBlk = NewnumRemainedBlk;
  791. } else {
  792. MakeProgress = false;
  793. DEBUG(
  794. dbgs() << "No progress\n";
  795. );
  796. }
  797. }
  798. } while (!Finish && MakeProgress);
  799. // Misc wrap up to maintain the consistency of the Function representation.
  800. wrapup(GraphTraits<MachineFunction *>::nodes_begin(FuncRep));
  801. // Detach retired Block, release memory.
  802. for (MBBInfoMap::iterator It = BlockInfoMap.begin(), E = BlockInfoMap.end();
  803. It != E; ++It) {
  804. if ((*It).second && (*It).second->IsRetired) {
  805. assert(((*It).first)->getNumber() != -1);
  806. DEBUG(
  807. dbgs() << "Erase BB" << ((*It).first)->getNumber() << "\n";
  808. );
  809. (*It).first->eraseFromParent(); //Remove from the parent Function.
  810. }
  811. delete (*It).second;
  812. }
  813. BlockInfoMap.clear();
  814. LLInfoMap.clear();
  815. DEBUG(
  816. FuncRep->viewCFG();
  817. );
  818. if (!Finish)
  819. llvm_unreachable("IRREDUCIBL_CF");
  820. return true;
  821. }
  822. void AMDGPUCFGStructurizer::orderBlocks(MachineFunction *MF) {
  823. int SccNum = 0;
  824. MachineBasicBlock *MBB;
  825. for (scc_iterator<MachineFunction *> It = scc_begin(MF); !It.isAtEnd();
  826. ++It, ++SccNum) {
  827. std::vector<MachineBasicBlock *> &SccNext = *It;
  828. for (std::vector<MachineBasicBlock *>::const_iterator
  829. blockIter = SccNext.begin(), blockEnd = SccNext.end();
  830. blockIter != blockEnd; ++blockIter) {
  831. MBB = *blockIter;
  832. OrderedBlks.push_back(MBB);
  833. recordSccnum(MBB, SccNum);
  834. }
  835. }
  836. //walk through all the block in func to check for unreachable
  837. typedef GraphTraits<MachineFunction *> GTM;
  838. MachineFunction::iterator It = GTM::nodes_begin(MF), E = GTM::nodes_end(MF);
  839. for (; It != E; ++It) {
  840. MachineBasicBlock *MBB = &(*It);
  841. SccNum = getSCCNum(MBB);
  842. if (SccNum == INVALIDSCCNUM)
  843. dbgs() << "unreachable block BB" << MBB->getNumber() << "\n";
  844. }
  845. }
  846. int AMDGPUCFGStructurizer::patternMatch(MachineBasicBlock *MBB) {
  847. int NumMatch = 0;
  848. int CurMatch;
  849. DEBUG(
  850. dbgs() << "Begin patternMatch BB" << MBB->getNumber() << "\n";
  851. );
  852. while ((CurMatch = patternMatchGroup(MBB)) > 0)
  853. NumMatch += CurMatch;
  854. DEBUG(
  855. dbgs() << "End patternMatch BB" << MBB->getNumber()
  856. << ", numMatch = " << NumMatch << "\n";
  857. );
  858. return NumMatch;
  859. }
  860. int AMDGPUCFGStructurizer::patternMatchGroup(MachineBasicBlock *MBB) {
  861. int NumMatch = 0;
  862. NumMatch += loopendPatternMatch();
  863. NumMatch += serialPatternMatch(MBB);
  864. NumMatch += ifPatternMatch(MBB);
  865. return NumMatch;
  866. }
  867. int AMDGPUCFGStructurizer::serialPatternMatch(MachineBasicBlock *MBB) {
  868. if (MBB->succ_size() != 1)
  869. return 0;
  870. MachineBasicBlock *childBlk = *MBB->succ_begin();
  871. if (childBlk->pred_size() != 1 || isActiveLoophead(childBlk))
  872. return 0;
  873. mergeSerialBlock(MBB, childBlk);
  874. ++numSerialPatternMatch;
  875. return 1;
  876. }
  877. int AMDGPUCFGStructurizer::ifPatternMatch(MachineBasicBlock *MBB) {
  878. //two edges
  879. if (MBB->succ_size() != 2)
  880. return 0;
  881. if (hasBackEdge(MBB))
  882. return 0;
  883. MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
  884. if (!BranchMI)
  885. return 0;
  886. assert(isCondBranch(BranchMI));
  887. int NumMatch = 0;
  888. MachineBasicBlock *TrueMBB = getTrueBranch(BranchMI);
  889. NumMatch += serialPatternMatch(TrueMBB);
  890. NumMatch += ifPatternMatch(TrueMBB);
  891. MachineBasicBlock *FalseMBB = getFalseBranch(MBB, BranchMI);
  892. NumMatch += serialPatternMatch(FalseMBB);
  893. NumMatch += ifPatternMatch(FalseMBB);
  894. MachineBasicBlock *LandBlk;
  895. int Cloned = 0;
  896. assert (!TrueMBB->succ_empty() || !FalseMBB->succ_empty());
  897. // TODO: Simplify
  898. if (TrueMBB->succ_size() == 1 && FalseMBB->succ_size() == 1
  899. && *TrueMBB->succ_begin() == *FalseMBB->succ_begin()) {
  900. // Diamond pattern
  901. LandBlk = *TrueMBB->succ_begin();
  902. } else if (TrueMBB->succ_size() == 1 && *TrueMBB->succ_begin() == FalseMBB) {
  903. // Triangle pattern, false is empty
  904. LandBlk = FalseMBB;
  905. FalseMBB = NULL;
  906. } else if (FalseMBB->succ_size() == 1
  907. && *FalseMBB->succ_begin() == TrueMBB) {
  908. // Triangle pattern, true is empty
  909. // We reverse the predicate to make a triangle, empty false pattern;
  910. std::swap(TrueMBB, FalseMBB);
  911. reversePredicateSetter(MBB->end());
  912. LandBlk = FalseMBB;
  913. FalseMBB = NULL;
  914. } else if (FalseMBB->succ_size() == 1
  915. && isSameloopDetachedContbreak(TrueMBB, FalseMBB)) {
  916. LandBlk = *FalseMBB->succ_begin();
  917. } else if (TrueMBB->succ_size() == 1
  918. && isSameloopDetachedContbreak(FalseMBB, TrueMBB)) {
  919. LandBlk = *TrueMBB->succ_begin();
  920. } else {
  921. return NumMatch + handleJumpintoIf(MBB, TrueMBB, FalseMBB);
  922. }
  923. // improveSimpleJumpinfoIf can handle the case where landBlk == NULL but the
  924. // new BB created for landBlk==NULL may introduce new challenge to the
  925. // reduction process.
  926. if (LandBlk &&
  927. ((TrueMBB && TrueMBB->pred_size() > 1)
  928. || (FalseMBB && FalseMBB->pred_size() > 1))) {
  929. Cloned += improveSimpleJumpintoIf(MBB, TrueMBB, FalseMBB, &LandBlk);
  930. }
  931. if (TrueMBB && TrueMBB->pred_size() > 1) {
  932. TrueMBB = cloneBlockForPredecessor(TrueMBB, MBB);
  933. ++Cloned;
  934. }
  935. if (FalseMBB && FalseMBB->pred_size() > 1) {
  936. FalseMBB = cloneBlockForPredecessor(FalseMBB, MBB);
  937. ++Cloned;
  938. }
  939. mergeIfthenelseBlock(BranchMI, MBB, TrueMBB, FalseMBB, LandBlk);
  940. ++numIfPatternMatch;
  941. numClonedBlock += Cloned;
  942. return 1 + Cloned + NumMatch;
  943. }
  944. int AMDGPUCFGStructurizer::loopendPatternMatch() {
  945. std::vector<MachineLoop *> NestedLoops;
  946. for (MachineLoopInfo::iterator It = MLI->begin(), E = MLI->end();
  947. It != E; ++It) {
  948. df_iterator<MachineLoop *> LpIt = df_begin(*It),
  949. LpE = df_end(*It);
  950. for (; LpIt != LpE; ++LpIt)
  951. NestedLoops.push_back(*LpIt);
  952. }
  953. if (NestedLoops.size() == 0)
  954. return 0;
  955. // Process nested loop outside->inside, so "continue" to a outside loop won't
  956. // be mistaken as "break" of the current loop.
  957. int Num = 0;
  958. for (std::vector<MachineLoop *>::reverse_iterator It = NestedLoops.rbegin(),
  959. E = NestedLoops.rend(); It != E; ++It) {
  960. MachineLoop *ExaminedLoop = *It;
  961. if (ExaminedLoop->getNumBlocks() == 0 || Visited[ExaminedLoop])
  962. continue;
  963. DEBUG(dbgs() << "Processing:\n"; ExaminedLoop->dump(););
  964. int NumBreak = mergeLoop(ExaminedLoop);
  965. if (NumBreak == -1)
  966. break;
  967. Num += NumBreak;
  968. }
  969. return Num;
  970. }
  971. int AMDGPUCFGStructurizer::mergeLoop(MachineLoop *LoopRep) {
  972. MachineBasicBlock *LoopHeader = LoopRep->getHeader();
  973. MBBVector ExitingMBBs;
  974. LoopRep->getExitingBlocks(ExitingMBBs);
  975. assert(!ExitingMBBs.empty() && "Infinite Loop not supported");
  976. DEBUG(dbgs() << "Loop has " << ExitingMBBs.size() << " exiting blocks\n";);
  977. // We assume a single ExitBlk
  978. MBBVector ExitBlks;
  979. LoopRep->getExitBlocks(ExitBlks);
  980. SmallPtrSet<MachineBasicBlock *, 2> ExitBlkSet;
  981. for (unsigned i = 0, e = ExitBlks.size(); i < e; ++i)
  982. ExitBlkSet.insert(ExitBlks[i]);
  983. assert(ExitBlkSet.size() == 1);
  984. MachineBasicBlock *ExitBlk = *ExitBlks.begin();
  985. assert(ExitBlk && "Loop has several exit block");
  986. MBBVector LatchBlks;
  987. typedef GraphTraits<Inverse<MachineBasicBlock*> > InvMBBTraits;
  988. InvMBBTraits::ChildIteratorType PI = InvMBBTraits::child_begin(LoopHeader),
  989. PE = InvMBBTraits::child_end(LoopHeader);
  990. for (; PI != PE; PI++) {
  991. if (LoopRep->contains(*PI))
  992. LatchBlks.push_back(*PI);
  993. }
  994. for (unsigned i = 0, e = ExitingMBBs.size(); i < e; ++i)
  995. mergeLoopbreakBlock(ExitingMBBs[i], ExitBlk);
  996. for (unsigned i = 0, e = LatchBlks.size(); i < e; ++i)
  997. settleLoopcontBlock(LatchBlks[i], LoopHeader);
  998. int Match = 0;
  999. do {
  1000. Match = 0;
  1001. Match += serialPatternMatch(LoopHeader);
  1002. Match += ifPatternMatch(LoopHeader);
  1003. } while (Match > 0);
  1004. mergeLooplandBlock(LoopHeader, ExitBlk);
  1005. MachineLoop *ParentLoop = LoopRep->getParentLoop();
  1006. if (ParentLoop)
  1007. MLI->changeLoopFor(LoopHeader, ParentLoop);
  1008. else
  1009. MLI->removeBlock(LoopHeader);
  1010. Visited[LoopRep] = true;
  1011. return 1;
  1012. }
  1013. int AMDGPUCFGStructurizer::loopcontPatternMatch(MachineLoop *LoopRep,
  1014. MachineBasicBlock *LoopHeader) {
  1015. int NumCont = 0;
  1016. SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> ContMBB;
  1017. typedef GraphTraits<Inverse<MachineBasicBlock *> > GTIM;
  1018. GTIM::ChildIteratorType It = GTIM::child_begin(LoopHeader),
  1019. E = GTIM::child_end(LoopHeader);
  1020. for (; It != E; ++It) {
  1021. MachineBasicBlock *MBB = *It;
  1022. if (LoopRep->contains(MBB)) {
  1023. handleLoopcontBlock(MBB, MLI->getLoopFor(MBB),
  1024. LoopHeader, LoopRep);
  1025. ContMBB.push_back(MBB);
  1026. ++NumCont;
  1027. }
  1028. }
  1029. for (SmallVectorImpl<MachineBasicBlock *>::iterator It = ContMBB.begin(),
  1030. E = ContMBB.end(); It != E; ++It) {
  1031. (*It)->removeSuccessor(LoopHeader);
  1032. }
  1033. numLoopcontPatternMatch += NumCont;
  1034. return NumCont;
  1035. }
  1036. bool AMDGPUCFGStructurizer::isSameloopDetachedContbreak(
  1037. MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB) {
  1038. if (Src1MBB->succ_size() == 0) {
  1039. MachineLoop *LoopRep = MLI->getLoopFor(Src1MBB);
  1040. if (LoopRep&& LoopRep == MLI->getLoopFor(Src2MBB)) {
  1041. MachineBasicBlock *&TheEntry = LLInfoMap[LoopRep];
  1042. if (TheEntry) {
  1043. DEBUG(
  1044. dbgs() << "isLoopContBreakBlock yes src1 = BB"
  1045. << Src1MBB->getNumber()
  1046. << " src2 = BB" << Src2MBB->getNumber() << "\n";
  1047. );
  1048. return true;
  1049. }
  1050. }
  1051. }
  1052. return false;
  1053. }
  1054. int AMDGPUCFGStructurizer::handleJumpintoIf(MachineBasicBlock *HeadMBB,
  1055. MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
  1056. int Num = handleJumpintoIfImp(HeadMBB, TrueMBB, FalseMBB);
  1057. if (Num == 0) {
  1058. DEBUG(
  1059. dbgs() << "handleJumpintoIf swap trueBlk and FalseBlk" << "\n";
  1060. );
  1061. Num = handleJumpintoIfImp(HeadMBB, FalseMBB, TrueMBB);
  1062. }
  1063. return Num;
  1064. }
  1065. int AMDGPUCFGStructurizer::handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
  1066. MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
  1067. int Num = 0;
  1068. MachineBasicBlock *DownBlk;
  1069. //trueBlk could be the common post dominator
  1070. DownBlk = TrueMBB;
  1071. DEBUG(
  1072. dbgs() << "handleJumpintoIfImp head = BB" << HeadMBB->getNumber()
  1073. << " true = BB" << TrueMBB->getNumber()
  1074. << ", numSucc=" << TrueMBB->succ_size()
  1075. << " false = BB" << FalseMBB->getNumber() << "\n";
  1076. );
  1077. while (DownBlk) {
  1078. DEBUG(
  1079. dbgs() << "check down = BB" << DownBlk->getNumber();
  1080. );
  1081. if (singlePathTo(FalseMBB, DownBlk) == SinglePath_InPath) {
  1082. DEBUG(
  1083. dbgs() << " working\n";
  1084. );
  1085. Num += cloneOnSideEntryTo(HeadMBB, TrueMBB, DownBlk);
  1086. Num += cloneOnSideEntryTo(HeadMBB, FalseMBB, DownBlk);
  1087. numClonedBlock += Num;
  1088. Num += serialPatternMatch(*HeadMBB->succ_begin());
  1089. Num += serialPatternMatch(*std::next(HeadMBB->succ_begin()));
  1090. Num += ifPatternMatch(HeadMBB);
  1091. assert(Num > 0);
  1092. break;
  1093. }
  1094. DEBUG(
  1095. dbgs() << " not working\n";
  1096. );
  1097. DownBlk = (DownBlk->succ_size() == 1) ? (*DownBlk->succ_begin()) : NULL;
  1098. } // walk down the postDomTree
  1099. return Num;
  1100. }
  1101. void AMDGPUCFGStructurizer::showImproveSimpleJumpintoIf(
  1102. MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB,
  1103. MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail) {
  1104. dbgs() << "head = BB" << HeadMBB->getNumber()
  1105. << " size = " << HeadMBB->size();
  1106. if (Detail) {
  1107. dbgs() << "\n";
  1108. HeadMBB->print(dbgs());
  1109. dbgs() << "\n";
  1110. }
  1111. if (TrueMBB) {
  1112. dbgs() << ", true = BB" << TrueMBB->getNumber() << " size = "
  1113. << TrueMBB->size() << " numPred = " << TrueMBB->pred_size();
  1114. if (Detail) {
  1115. dbgs() << "\n";
  1116. TrueMBB->print(dbgs());
  1117. dbgs() << "\n";
  1118. }
  1119. }
  1120. if (FalseMBB) {
  1121. dbgs() << ", false = BB" << FalseMBB->getNumber() << " size = "
  1122. << FalseMBB->size() << " numPred = " << FalseMBB->pred_size();
  1123. if (Detail) {
  1124. dbgs() << "\n";
  1125. FalseMBB->print(dbgs());
  1126. dbgs() << "\n";
  1127. }
  1128. }
  1129. if (LandMBB) {
  1130. dbgs() << ", land = BB" << LandMBB->getNumber() << " size = "
  1131. << LandMBB->size() << " numPred = " << LandMBB->pred_size();
  1132. if (Detail) {
  1133. dbgs() << "\n";
  1134. LandMBB->print(dbgs());
  1135. dbgs() << "\n";
  1136. }
  1137. }
  1138. dbgs() << "\n";
  1139. }
  1140. int AMDGPUCFGStructurizer::improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
  1141. MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
  1142. MachineBasicBlock **LandMBBPtr) {
  1143. bool MigrateTrue = false;
  1144. bool MigrateFalse = false;
  1145. MachineBasicBlock *LandBlk = *LandMBBPtr;
  1146. assert((!TrueMBB || TrueMBB->succ_size() <= 1)
  1147. && (!FalseMBB || FalseMBB->succ_size() <= 1));
  1148. if (TrueMBB == FalseMBB)
  1149. return 0;
  1150. MigrateTrue = needMigrateBlock(TrueMBB);
  1151. MigrateFalse = needMigrateBlock(FalseMBB);
  1152. if (!MigrateTrue && !MigrateFalse)
  1153. return 0;
  1154. // If we need to migrate either trueBlk and falseBlk, migrate the rest that
  1155. // have more than one predecessors. without doing this, its predecessor
  1156. // rather than headBlk will have undefined value in initReg.
  1157. if (!MigrateTrue && TrueMBB && TrueMBB->pred_size() > 1)
  1158. MigrateTrue = true;
  1159. if (!MigrateFalse && FalseMBB && FalseMBB->pred_size() > 1)
  1160. MigrateFalse = true;
  1161. DEBUG(
  1162. dbgs() << "before improveSimpleJumpintoIf: ";
  1163. showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
  1164. );
  1165. // org: headBlk => if () {trueBlk} else {falseBlk} => landBlk
  1166. //
  1167. // new: headBlk => if () {initReg = 1; org trueBlk branch} else
  1168. // {initReg = 0; org falseBlk branch }
  1169. // => landBlk => if (initReg) {org trueBlk} else {org falseBlk}
  1170. // => org landBlk
  1171. // if landBlk->pred_size() > 2, put the about if-else inside
  1172. // if (initReg !=2) {...}
  1173. //
  1174. // add initReg = initVal to headBlk
  1175. const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32);
  1176. if (!MigrateTrue || !MigrateFalse) {
  1177. // XXX: We have an opportunity here to optimize the "branch into if" case
  1178. // here. Branch into if looks like this:
  1179. // entry
  1180. // / |
  1181. // diamond_head branch_from
  1182. // / \ |
  1183. // diamond_false diamond_true
  1184. // \ /
  1185. // done
  1186. //
  1187. // The diamond_head block begins the "if" and the diamond_true block
  1188. // is the block being "branched into".
  1189. //
  1190. // If MigrateTrue is true, then TrueBB is the block being "branched into"
  1191. // and if MigrateFalse is true, then FalseBB is the block being
  1192. // "branched into"
  1193. //
  1194. // Here is the pseudo code for how I think the optimization should work:
  1195. // 1. Insert MOV GPR0, 0 before the branch instruction in diamond_head.
  1196. // 2. Insert MOV GPR0, 1 before the branch instruction in branch_from.
  1197. // 3. Move the branch instruction from diamond_head into its own basic
  1198. // block (new_block).
  1199. // 4. Add an unconditional branch from diamond_head to new_block
  1200. // 5. Replace the branch instruction in branch_from with an unconditional
  1201. // branch to new_block. If branch_from has multiple predecessors, then
  1202. // we need to replace the True/False block in the branch
  1203. // instruction instead of replacing it.
  1204. // 6. Change the condition of the branch instruction in new_block from
  1205. // COND to (COND || GPR0)
  1206. //
  1207. // In order insert these MOV instruction, we will need to use the
  1208. // RegisterScavenger. Usually liveness stops being tracked during
  1209. // the late machine optimization passes, however if we implement
  1210. // bool TargetRegisterInfo::requiresRegisterScavenging(
  1211. // const MachineFunction &MF)
  1212. // and have it return true, liveness will be tracked correctly
  1213. // by generic optimization passes. We will also need to make sure that
  1214. // all of our target-specific passes that run after regalloc and before
  1215. // the CFGStructurizer track liveness and we will need to modify this pass
  1216. // to correctly track liveness.
  1217. //
  1218. // After the above changes, the new CFG should look like this:
  1219. // entry
  1220. // / |
  1221. // diamond_head branch_from
  1222. // \ /
  1223. // new_block
  1224. // / |
  1225. // diamond_false diamond_true
  1226. // \ /
  1227. // done
  1228. //
  1229. // Without this optimization, we are forced to duplicate the diamond_true
  1230. // block and we will end up with a CFG like this:
  1231. //
  1232. // entry
  1233. // / |
  1234. // diamond_head branch_from
  1235. // / \ |
  1236. // diamond_false diamond_true diamond_true (duplicate)
  1237. // \ / |
  1238. // done --------------------|
  1239. //
  1240. // Duplicating diamond_true can be very costly especially if it has a
  1241. // lot of instructions.
  1242. return 0;
  1243. }
  1244. int NumNewBlk = 0;
  1245. bool LandBlkHasOtherPred = (LandBlk->pred_size() > 2);
  1246. //insert AMDGPU::ENDIF to avoid special case "input landBlk == NULL"
  1247. MachineBasicBlock::iterator I = insertInstrBefore(LandBlk, AMDGPU::ENDIF);
  1248. if (LandBlkHasOtherPred) {
  1249. llvm_unreachable("Extra register needed to handle CFG");
  1250. unsigned CmpResReg =
  1251. HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
  1252. llvm_unreachable("Extra compare instruction needed to handle CFG");
  1253. insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET,
  1254. CmpResReg, DebugLoc());
  1255. }
  1256. // XXX: We are running this after RA, so creating virtual registers will
  1257. // cause an assertion failure in the PostRA scheduling pass.
  1258. unsigned InitReg =
  1259. HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
  1260. insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET, InitReg,
  1261. DebugLoc());
  1262. if (MigrateTrue) {
  1263. migrateInstruction(TrueMBB, LandBlk, I);
  1264. // need to uncondionally insert the assignment to ensure a path from its
  1265. // predecessor rather than headBlk has valid value in initReg if
  1266. // (initVal != 1).
  1267. llvm_unreachable("Extra register needed to handle CFG");
  1268. }
  1269. insertInstrBefore(I, AMDGPU::ELSE);
  1270. if (MigrateFalse) {
  1271. migrateInstruction(FalseMBB, LandBlk, I);
  1272. // need to uncondionally insert the assignment to ensure a path from its
  1273. // predecessor rather than headBlk has valid value in initReg if
  1274. // (initVal != 0)
  1275. llvm_unreachable("Extra register needed to handle CFG");
  1276. }
  1277. if (LandBlkHasOtherPred) {
  1278. // add endif
  1279. insertInstrBefore(I, AMDGPU::ENDIF);
  1280. // put initReg = 2 to other predecessors of landBlk
  1281. for (MachineBasicBlock::pred_iterator PI = LandBlk->pred_begin(),
  1282. PE = LandBlk->pred_end(); PI != PE; ++PI) {
  1283. MachineBasicBlock *MBB = *PI;
  1284. if (MBB != TrueMBB && MBB != FalseMBB)
  1285. llvm_unreachable("Extra register needed to handle CFG");
  1286. }
  1287. }
  1288. DEBUG(
  1289. dbgs() << "result from improveSimpleJumpintoIf: ";
  1290. showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
  1291. );
  1292. // update landBlk
  1293. *LandMBBPtr = LandBlk;
  1294. return NumNewBlk;
  1295. }
  1296. void AMDGPUCFGStructurizer::handleLoopcontBlock(MachineBasicBlock *ContingMBB,
  1297. MachineLoop *ContingLoop, MachineBasicBlock *ContMBB,
  1298. MachineLoop *ContLoop) {
  1299. DEBUG(dbgs() << "loopcontPattern cont = BB" << ContingMBB->getNumber()
  1300. << " header = BB" << ContMBB->getNumber() << "\n";
  1301. dbgs() << "Trying to continue loop-depth = "
  1302. << getLoopDepth(ContLoop)
  1303. << " from loop-depth = " << getLoopDepth(ContingLoop) << "\n";);
  1304. settleLoopcontBlock(ContingMBB, ContMBB);
  1305. }
  1306. void AMDGPUCFGStructurizer::mergeSerialBlock(MachineBasicBlock *DstMBB,
  1307. MachineBasicBlock *SrcMBB) {
  1308. DEBUG(
  1309. dbgs() << "serialPattern BB" << DstMBB->getNumber()
  1310. << " <= BB" << SrcMBB->getNumber() << "\n";
  1311. );
  1312. DstMBB->splice(DstMBB->end(), SrcMBB, SrcMBB->begin(), SrcMBB->end());
  1313. DstMBB->removeSuccessor(SrcMBB);
  1314. cloneSuccessorList(DstMBB, SrcMBB);
  1315. removeSuccessor(SrcMBB);
  1316. MLI->removeBlock(SrcMBB);
  1317. retireBlock(SrcMBB);
  1318. }
  1319. void AMDGPUCFGStructurizer::mergeIfthenelseBlock(MachineInstr *BranchMI,
  1320. MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
  1321. MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB) {
  1322. assert (TrueMBB);
  1323. DEBUG(
  1324. dbgs() << "ifPattern BB" << MBB->getNumber();
  1325. dbgs() << "{ ";
  1326. if (TrueMBB) {
  1327. dbgs() << "BB" << TrueMBB->getNumber();
  1328. }
  1329. dbgs() << " } else ";
  1330. dbgs() << "{ ";
  1331. if (FalseMBB) {
  1332. dbgs() << "BB" << FalseMBB->getNumber();
  1333. }
  1334. dbgs() << " }\n ";
  1335. dbgs() << "landBlock: ";
  1336. if (!LandMBB) {
  1337. dbgs() << "NULL";
  1338. } else {
  1339. dbgs() << "BB" << LandMBB->getNumber();
  1340. }
  1341. dbgs() << "\n";
  1342. );
  1343. int OldOpcode = BranchMI->getOpcode();
  1344. DebugLoc BranchDL = BranchMI->getDebugLoc();
  1345. // transform to
  1346. // if cond
  1347. // trueBlk
  1348. // else
  1349. // falseBlk
  1350. // endif
  1351. // landBlk
  1352. MachineBasicBlock::iterator I = BranchMI;
  1353. insertCondBranchBefore(I, getBranchNzeroOpcode(OldOpcode),
  1354. BranchDL);
  1355. if (TrueMBB) {
  1356. MBB->splice(I, TrueMBB, TrueMBB->begin(), TrueMBB->end());
  1357. MBB->removeSuccessor(TrueMBB);
  1358. if (LandMBB && TrueMBB->succ_size()!=0)
  1359. TrueMBB->removeSuccessor(LandMBB);
  1360. retireBlock(TrueMBB);
  1361. MLI->removeBlock(TrueMBB);
  1362. }
  1363. if (FalseMBB) {
  1364. insertInstrBefore(I, AMDGPU::ELSE);
  1365. MBB->splice(I, FalseMBB, FalseMBB->begin(),
  1366. FalseMBB->end());
  1367. MBB->removeSuccessor(FalseMBB);
  1368. if (LandMBB && FalseMBB->succ_size() != 0)
  1369. FalseMBB->removeSuccessor(LandMBB);
  1370. retireBlock(FalseMBB);
  1371. MLI->removeBlock(FalseMBB);
  1372. }
  1373. insertInstrBefore(I, AMDGPU::ENDIF);
  1374. BranchMI->eraseFromParent();
  1375. if (LandMBB && TrueMBB && FalseMBB)
  1376. MBB->addSuccessor(LandMBB);
  1377. }
  1378. void AMDGPUCFGStructurizer::mergeLooplandBlock(MachineBasicBlock *DstBlk,
  1379. MachineBasicBlock *LandMBB) {
  1380. DEBUG(dbgs() << "loopPattern header = BB" << DstBlk->getNumber()
  1381. << " land = BB" << LandMBB->getNumber() << "\n";);
  1382. insertInstrBefore(DstBlk, AMDGPU::WHILELOOP, DebugLoc());
  1383. insertInstrEnd(DstBlk, AMDGPU::ENDLOOP, DebugLoc());
  1384. DstBlk->addSuccessor(LandMBB);
  1385. DstBlk->removeSuccessor(DstBlk);
  1386. }
  1387. void AMDGPUCFGStructurizer::mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
  1388. MachineBasicBlock *LandMBB) {
  1389. DEBUG(dbgs() << "loopbreakPattern exiting = BB" << ExitingMBB->getNumber()
  1390. << " land = BB" << LandMBB->getNumber() << "\n";);
  1391. MachineInstr *BranchMI = getLoopendBlockBranchInstr(ExitingMBB);
  1392. assert(BranchMI && isCondBranch(BranchMI));
  1393. DebugLoc DL = BranchMI->getDebugLoc();
  1394. MachineBasicBlock *TrueBranch = getTrueBranch(BranchMI);
  1395. MachineBasicBlock::iterator I = BranchMI;
  1396. if (TrueBranch != LandMBB)
  1397. reversePredicateSetter(I);
  1398. insertCondBranchBefore(ExitingMBB, I, AMDGPU::IF_PREDICATE_SET, AMDGPU::PREDICATE_BIT, DL);
  1399. insertInstrBefore(I, AMDGPU::BREAK);
  1400. insertInstrBefore(I, AMDGPU::ENDIF);
  1401. //now branchInst can be erase safely
  1402. BranchMI->eraseFromParent();
  1403. //now take care of successors, retire blocks
  1404. ExitingMBB->removeSuccessor(LandMBB);
  1405. }
  1406. void AMDGPUCFGStructurizer::settleLoopcontBlock(MachineBasicBlock *ContingMBB,
  1407. MachineBasicBlock *ContMBB) {
  1408. DEBUG(dbgs() << "settleLoopcontBlock conting = BB"
  1409. << ContingMBB->getNumber()
  1410. << ", cont = BB" << ContMBB->getNumber() << "\n";);
  1411. MachineInstr *MI = getLoopendBlockBranchInstr(ContingMBB);
  1412. if (MI) {
  1413. assert(isCondBranch(MI));
  1414. MachineBasicBlock::iterator I = MI;
  1415. MachineBasicBlock *TrueBranch = getTrueBranch(MI);
  1416. int OldOpcode = MI->getOpcode();
  1417. DebugLoc DL = MI->getDebugLoc();
  1418. bool UseContinueLogical = ((&*ContingMBB->rbegin()) == MI);
  1419. if (UseContinueLogical == false) {
  1420. int BranchOpcode =
  1421. TrueBranch == ContMBB ? getBranchNzeroOpcode(OldOpcode) :
  1422. getBranchZeroOpcode(OldOpcode);
  1423. insertCondBranchBefore(I, BranchOpcode, DL);
  1424. // insertEnd to ensure phi-moves, if exist, go before the continue-instr.
  1425. insertInstrEnd(ContingMBB, AMDGPU::CONTINUE, DL);
  1426. insertInstrEnd(ContingMBB, AMDGPU::ENDIF, DL);
  1427. } else {
  1428. int BranchOpcode =
  1429. TrueBranch == ContMBB ? getContinueNzeroOpcode(OldOpcode) :
  1430. getContinueZeroOpcode(OldOpcode);
  1431. insertCondBranchBefore(I, BranchOpcode, DL);
  1432. }
  1433. MI->eraseFromParent();
  1434. } else {
  1435. // if we've arrived here then we've already erased the branch instruction
  1436. // travel back up the basic block to see the last reference of our debug
  1437. // location we've just inserted that reference here so it should be
  1438. // representative insertEnd to ensure phi-moves, if exist, go before the
  1439. // continue-instr.
  1440. insertInstrEnd(ContingMBB, AMDGPU::CONTINUE,
  1441. getLastDebugLocInBB(ContingMBB));
  1442. }
  1443. }
  1444. int AMDGPUCFGStructurizer::cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
  1445. MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB) {
  1446. int Cloned = 0;
  1447. assert(PreMBB->isSuccessor(SrcMBB));
  1448. while (SrcMBB && SrcMBB != DstMBB) {
  1449. assert(SrcMBB->succ_size() == 1);
  1450. if (SrcMBB->pred_size() > 1) {
  1451. SrcMBB = cloneBlockForPredecessor(SrcMBB, PreMBB);
  1452. ++Cloned;
  1453. }
  1454. PreMBB = SrcMBB;
  1455. SrcMBB = *SrcMBB->succ_begin();
  1456. }
  1457. return Cloned;
  1458. }
  1459. MachineBasicBlock *
  1460. AMDGPUCFGStructurizer::cloneBlockForPredecessor(MachineBasicBlock *MBB,
  1461. MachineBasicBlock *PredMBB) {
  1462. assert(PredMBB->isSuccessor(MBB) &&
  1463. "succBlk is not a prececessor of curBlk");
  1464. MachineBasicBlock *CloneMBB = clone(MBB); //clone instructions
  1465. replaceInstrUseOfBlockWith(PredMBB, MBB, CloneMBB);
  1466. //srcBlk, oldBlk, newBlk
  1467. PredMBB->removeSuccessor(MBB);
  1468. PredMBB->addSuccessor(CloneMBB);
  1469. // add all successor to cloneBlk
  1470. cloneSuccessorList(CloneMBB, MBB);
  1471. numClonedInstr += MBB->size();
  1472. DEBUG(
  1473. dbgs() << "Cloned block: " << "BB"
  1474. << MBB->getNumber() << "size " << MBB->size() << "\n";
  1475. );
  1476. SHOWNEWBLK(CloneMBB, "result of Cloned block: ");
  1477. return CloneMBB;
  1478. }
  1479. void AMDGPUCFGStructurizer::migrateInstruction(MachineBasicBlock *SrcMBB,
  1480. MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I) {
  1481. MachineBasicBlock::iterator SpliceEnd;
  1482. //look for the input branchinstr, not the AMDGPU branchinstr
  1483. MachineInstr *BranchMI = getNormalBlockBranchInstr(SrcMBB);
  1484. if (!BranchMI) {
  1485. DEBUG(
  1486. dbgs() << "migrateInstruction don't see branch instr\n" ;
  1487. );
  1488. SpliceEnd = SrcMBB->end();
  1489. } else {
  1490. DEBUG(
  1491. dbgs() << "migrateInstruction see branch instr\n" ;
  1492. BranchMI->dump();
  1493. );
  1494. SpliceEnd = BranchMI;
  1495. }
  1496. DEBUG(
  1497. dbgs() << "migrateInstruction before splice dstSize = " << DstMBB->size()
  1498. << "srcSize = " << SrcMBB->size() << "\n";
  1499. );
  1500. //splice insert before insertPos
  1501. DstMBB->splice(I, SrcMBB, SrcMBB->begin(), SpliceEnd);
  1502. DEBUG(
  1503. dbgs() << "migrateInstruction after splice dstSize = " << DstMBB->size()
  1504. << "srcSize = " << SrcMBB->size() << "\n";
  1505. );
  1506. }
  1507. MachineBasicBlock *
  1508. AMDGPUCFGStructurizer::normalizeInfiniteLoopExit(MachineLoop* LoopRep) {
  1509. MachineBasicBlock *LoopHeader = LoopRep->getHeader();
  1510. MachineBasicBlock *LoopLatch = LoopRep->getLoopLatch();
  1511. const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32);
  1512. if (!LoopHeader || !LoopLatch)
  1513. return NULL;
  1514. MachineInstr *BranchMI = getLoopendBlockBranchInstr(LoopLatch);
  1515. // Is LoopRep an infinite loop ?
  1516. if (!BranchMI || !isUncondBranch(BranchMI))
  1517. return NULL;
  1518. MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
  1519. FuncRep->push_back(DummyExitBlk); //insert to function
  1520. SHOWNEWBLK(DummyExitBlk, "DummyExitBlock to normalize infiniteLoop: ");
  1521. DEBUG(dbgs() << "Old branch instr: " << *BranchMI << "\n";);
  1522. MachineBasicBlock::iterator I = BranchMI;
  1523. unsigned ImmReg = FuncRep->getRegInfo().createVirtualRegister(I32RC);
  1524. llvm_unreachable("Extra register needed to handle CFG");
  1525. MachineInstr *NewMI = insertInstrBefore(I, AMDGPU::BRANCH_COND_i32);
  1526. MachineInstrBuilder MIB(*FuncRep, NewMI);
  1527. MIB.addMBB(LoopHeader);
  1528. MIB.addReg(ImmReg, false);
  1529. SHOWNEWINSTR(NewMI);
  1530. BranchMI->eraseFromParent();
  1531. LoopLatch->addSuccessor(DummyExitBlk);
  1532. return DummyExitBlk;
  1533. }
  1534. void AMDGPUCFGStructurizer::removeUnconditionalBranch(MachineBasicBlock *MBB) {
  1535. MachineInstr *BranchMI;
  1536. // I saw two unconditional branch in one basic block in example
  1537. // test_fc_do_while_or.c need to fix the upstream on this to remove the loop.
  1538. while ((BranchMI = getLoopendBlockBranchInstr(MBB))
  1539. && isUncondBranch(BranchMI)) {
  1540. DEBUG(dbgs() << "Removing uncond branch instr"; BranchMI->dump(););
  1541. BranchMI->eraseFromParent();
  1542. }
  1543. }
  1544. void AMDGPUCFGStructurizer::removeRedundantConditionalBranch(
  1545. MachineBasicBlock *MBB) {
  1546. if (MBB->succ_size() != 2)
  1547. return;
  1548. MachineBasicBlock *MBB1 = *MBB->succ_begin();
  1549. MachineBasicBlock *MBB2 = *std::next(MBB->succ_begin());
  1550. if (MBB1 != MBB2)
  1551. return;
  1552. MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
  1553. assert(BranchMI && isCondBranch(BranchMI));
  1554. DEBUG(dbgs() << "Removing unneeded cond branch instr"; BranchMI->dump(););
  1555. BranchMI->eraseFromParent();
  1556. SHOWNEWBLK(MBB1, "Removing redundant successor");
  1557. MBB->removeSuccessor(MBB1);
  1558. }
  1559. void AMDGPUCFGStructurizer::addDummyExitBlock(
  1560. SmallVectorImpl<MachineBasicBlock*> &RetMBB) {
  1561. MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
  1562. FuncRep->push_back(DummyExitBlk); //insert to function
  1563. insertInstrEnd(DummyExitBlk, AMDGPU::RETURN);
  1564. for (SmallVectorImpl<MachineBasicBlock *>::iterator It = RetMBB.begin(),
  1565. E = RetMBB.end(); It != E; ++It) {
  1566. MachineBasicBlock *MBB = *It;
  1567. MachineInstr *MI = getReturnInstr(MBB);
  1568. if (MI)
  1569. MI->eraseFromParent();
  1570. MBB->addSuccessor(DummyExitBlk);
  1571. DEBUG(
  1572. dbgs() << "Add dummyExitBlock to BB" << MBB->getNumber()
  1573. << " successors\n";
  1574. );
  1575. }
  1576. SHOWNEWBLK(DummyExitBlk, "DummyExitBlock: ");
  1577. }
  1578. void AMDGPUCFGStructurizer::removeSuccessor(MachineBasicBlock *MBB) {
  1579. while (MBB->succ_size())
  1580. MBB->removeSuccessor(*MBB->succ_begin());
  1581. }
  1582. void AMDGPUCFGStructurizer::recordSccnum(MachineBasicBlock *MBB,
  1583. int SccNum) {
  1584. BlockInformation *&srcBlkInfo = BlockInfoMap[MBB];
  1585. if (!srcBlkInfo)
  1586. srcBlkInfo = new BlockInformation();
  1587. srcBlkInfo->SccNum = SccNum;
  1588. }
  1589. void AMDGPUCFGStructurizer::retireBlock(MachineBasicBlock *MBB) {
  1590. DEBUG(
  1591. dbgs() << "Retiring BB" << MBB->getNumber() << "\n";
  1592. );
  1593. BlockInformation *&SrcBlkInfo = BlockInfoMap[MBB];
  1594. if (!SrcBlkInfo)
  1595. SrcBlkInfo = new BlockInformation();
  1596. SrcBlkInfo->IsRetired = true;
  1597. assert(MBB->succ_size() == 0 && MBB->pred_size() == 0
  1598. && "can't retire block yet");
  1599. }
  1600. void AMDGPUCFGStructurizer::setLoopLandBlock(MachineLoop *loopRep,
  1601. MachineBasicBlock *MBB) {
  1602. MachineBasicBlock *&TheEntry = LLInfoMap[loopRep];
  1603. if (!MBB) {
  1604. MBB = FuncRep->CreateMachineBasicBlock();
  1605. FuncRep->push_back(MBB); //insert to function
  1606. SHOWNEWBLK(MBB, "DummyLandingBlock for loop without break: ");
  1607. }
  1608. TheEntry = MBB;
  1609. DEBUG(
  1610. dbgs() << "setLoopLandBlock loop-header = BB"
  1611. << loopRep->getHeader()->getNumber()
  1612. << " landing-block = BB" << MBB->getNumber() << "\n";
  1613. );
  1614. }
  1615. MachineBasicBlock *
  1616. AMDGPUCFGStructurizer::findNearestCommonPostDom(MachineBasicBlock *MBB1,
  1617. MachineBasicBlock *MBB2) {
  1618. if (PDT->dominates(MBB1, MBB2))
  1619. return MBB1;
  1620. if (PDT->dominates(MBB2, MBB1))
  1621. return MBB2;
  1622. MachineDomTreeNode *Node1 = PDT->getNode(MBB1);
  1623. MachineDomTreeNode *Node2 = PDT->getNode(MBB2);
  1624. // Handle newly cloned node.
  1625. if (!Node1 && MBB1->succ_size() == 1)
  1626. return findNearestCommonPostDom(*MBB1->succ_begin(), MBB2);
  1627. if (!Node2 && MBB2->succ_size() == 1)
  1628. return findNearestCommonPostDom(MBB1, *MBB2->succ_begin());
  1629. if (!Node1 || !Node2)
  1630. return NULL;
  1631. Node1 = Node1->getIDom();
  1632. while (Node1) {
  1633. if (PDT->dominates(Node1, Node2))
  1634. return Node1->getBlock();
  1635. Node1 = Node1->getIDom();
  1636. }
  1637. return NULL;
  1638. }
  1639. MachineBasicBlock *
  1640. AMDGPUCFGStructurizer::findNearestCommonPostDom(
  1641. std::set<MachineBasicBlock *> &MBBs) {
  1642. MachineBasicBlock *CommonDom;
  1643. std::set<MachineBasicBlock *>::const_iterator It = MBBs.begin();
  1644. std::set<MachineBasicBlock *>::const_iterator E = MBBs.end();
  1645. for (CommonDom = *It; It != E && CommonDom; ++It) {
  1646. MachineBasicBlock *MBB = *It;
  1647. if (MBB != CommonDom)
  1648. CommonDom = findNearestCommonPostDom(MBB, CommonDom);
  1649. }
  1650. DEBUG(
  1651. dbgs() << "Common post dominator for exit blocks is ";
  1652. if (CommonDom)
  1653. dbgs() << "BB" << CommonDom->getNumber() << "\n";
  1654. else
  1655. dbgs() << "NULL\n";
  1656. );
  1657. return CommonDom;
  1658. }
  1659. char AMDGPUCFGStructurizer::ID = 0;
  1660. } // end anonymous namespace
  1661. INITIALIZE_PASS_BEGIN(AMDGPUCFGStructurizer, "amdgpustructurizer",
  1662. "AMDGPU CFG Structurizer", false, false)
  1663. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  1664. INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
  1665. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  1666. INITIALIZE_PASS_END(AMDGPUCFGStructurizer, "amdgpustructurizer",
  1667. "AMDGPU CFG Structurizer", false, false)
  1668. FunctionPass *llvm::createAMDGPUCFGStructurizerPass() {
  1669. return new AMDGPUCFGStructurizer();
  1670. }