blob: 94a5355c9167678a90784b4dbd79ed801cebce79 [file] [log] [blame]
Tom Stellard75aadc22012-12-11 21:25:42 +00001//===-- 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
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000011#include "AMDGPU.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000012#include "AMDGPUInstrInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000013#include "AMDGPUSubtarget.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000014#include "R600InstrInfo.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000015#include "llvm/ADT/DepthFirstIterator.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000016#include "llvm/ADT/SCCIterator.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000019#include "llvm/CodeGen/MachineDominators.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineFunctionAnalysis.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineJumpTableInfo.h"
25#include "llvm/CodeGen/MachineLoopInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000026#include "llvm/CodeGen/MachinePostDominators.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000029#include "llvm/Support/Debug.h"
30#include "llvm/Support/raw_ostream.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000031#include "llvm/Target/TargetInstrInfo.h"
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000032#include "llvm/Target/TargetMachine.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000033#include <deque>
Tom Stellard75aadc22012-12-11 21:25:42 +000034
35using namespace llvm;
36
Chandler Carruth84e68b22014-04-22 02:41:26 +000037#define DEBUG_TYPE "structcfg"
38
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000039#define DEFAULT_VEC_SLOTS 8
40
Tom Stellard75aadc22012-12-11 21:25:42 +000041// TODO: move-begin.
42
43//===----------------------------------------------------------------------===//
44//
45// Statistics for CFGStructurizer.
46//
47//===----------------------------------------------------------------------===//
48
49STATISTIC(numSerialPatternMatch, "CFGStructurizer number of serial pattern "
50 "matched");
51STATISTIC(numIfPatternMatch, "CFGStructurizer number of if pattern "
52 "matched");
Tom Stellard75aadc22012-12-11 21:25:42 +000053STATISTIC(numClonedBlock, "CFGStructurizer cloned blocks");
54STATISTIC(numClonedInstr, "CFGStructurizer cloned instructions");
55
Tom Stellardf2ba9722013-12-11 17:51:47 +000056namespace llvm {
57 void initializeAMDGPUCFGStructurizerPass(PassRegistry&);
58}
59
Tom Stellard75aadc22012-12-11 21:25:42 +000060//===----------------------------------------------------------------------===//
61//
62// Miscellaneous utility for CFGStructurizer.
63//
64//===----------------------------------------------------------------------===//
Benjamin Kramer635e3682013-05-23 15:43:05 +000065namespace {
Tom Stellard75aadc22012-12-11 21:25:42 +000066#define SHOWNEWINSTR(i) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000067 DEBUG(dbgs() << "New instr: " << *i << "\n");
Tom Stellard75aadc22012-12-11 21:25:42 +000068
69#define SHOWNEWBLK(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000070DEBUG( \
71 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
72 dbgs() << "\n"; \
73);
Tom Stellard75aadc22012-12-11 21:25:42 +000074
75#define SHOWBLK_DETAIL(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000076DEBUG( \
Tom Stellard75aadc22012-12-11 21:25:42 +000077 if (b) { \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000078 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
79 b->print(dbgs()); \
80 dbgs() << "\n"; \
Tom Stellard75aadc22012-12-11 21:25:42 +000081 } \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000082);
Tom Stellard75aadc22012-12-11 21:25:42 +000083
84#define INVALIDSCCNUM -1
Tom Stellard75aadc22012-12-11 21:25:42 +000085
86template<class NodeT>
Craig Topperb94011f2013-07-14 04:42:23 +000087void ReverseVector(SmallVectorImpl<NodeT *> &Src) {
Tom Stellard75aadc22012-12-11 21:25:42 +000088 size_t sz = Src.size();
89 for (size_t i = 0; i < sz/2; ++i) {
90 NodeT *t = Src[i];
91 Src[i] = Src[sz - i - 1];
92 Src[sz - i - 1] = t;
93 }
94}
95
Benjamin Kramer635e3682013-05-23 15:43:05 +000096} // end anonymous namespace
Tom Stellard75aadc22012-12-11 21:25:42 +000097
98//===----------------------------------------------------------------------===//
99//
100// supporting data structure for CFGStructurizer
101//
102//===----------------------------------------------------------------------===//
103
Tom Stellard75aadc22012-12-11 21:25:42 +0000104
Vincent Lejeune960a6222013-07-19 21:45:06 +0000105namespace {
106
Tom Stellard75aadc22012-12-11 21:25:42 +0000107class BlockInformation {
108public:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000109 bool IsRetired;
110 int SccNum;
111 BlockInformation() : IsRetired(false), SccNum(INVALIDSCCNUM) {}
Tom Stellard75aadc22012-12-11 21:25:42 +0000112};
113
Benjamin Kramer635e3682013-05-23 15:43:05 +0000114} // end anonymous namespace
Tom Stellard75aadc22012-12-11 21:25:42 +0000115
116//===----------------------------------------------------------------------===//
117//
118// CFGStructurizer
119//
120//===----------------------------------------------------------------------===//
121
Benjamin Kramer635e3682013-05-23 15:43:05 +0000122namespace {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000123class AMDGPUCFGStructurizer : public MachineFunctionPass {
Tom Stellard75aadc22012-12-11 21:25:42 +0000124public:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000125 typedef SmallVector<MachineBasicBlock *, 32> MBBVector;
126 typedef std::map<MachineBasicBlock *, BlockInformation *> MBBInfoMap;
127 typedef std::map<MachineLoop *, MachineBasicBlock *> LoopLandInfoMap;
128
129 enum PathToKind {
Tom Stellard75aadc22012-12-11 21:25:42 +0000130 Not_SinglePath = 0,
131 SinglePath_InPath = 1,
132 SinglePath_NotInPath = 2
Vincent Lejeune960a6222013-07-19 21:45:06 +0000133 };
Tom Stellard75aadc22012-12-11 21:25:42 +0000134
Vincent Lejeune960a6222013-07-19 21:45:06 +0000135 static char ID;
Tom Stellard75aadc22012-12-11 21:25:42 +0000136
Tom Stellardf2ba9722013-12-11 17:51:47 +0000137 AMDGPUCFGStructurizer() :
Craig Topper062a2ba2014-04-25 05:30:21 +0000138 MachineFunctionPass(ID), TII(nullptr), TRI(nullptr) {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000139 initializeAMDGPUCFGStructurizerPass(*PassRegistry::getPassRegistry());
140 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000141
Craig Topper5656db42014-04-29 07:57:24 +0000142 const char *getPassName() const override {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000143 return "AMDGPU Control Flow Graph structurizer Pass";
Vincent Lejeune960a6222013-07-19 21:45:06 +0000144 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000145
Craig Topper5656db42014-04-29 07:57:24 +0000146 void getAnalysisUsage(AnalysisUsage &AU) const override {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000147 AU.addPreserved<MachineFunctionAnalysis>();
148 AU.addRequired<MachineFunctionAnalysis>();
149 AU.addRequired<MachineDominatorTree>();
150 AU.addRequired<MachinePostDominatorTree>();
151 AU.addRequired<MachineLoopInfo>();
152 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000153
154 /// Perform the CFG structurization
Vincent Lejeune960a6222013-07-19 21:45:06 +0000155 bool run();
Tom Stellard75aadc22012-12-11 21:25:42 +0000156
157 /// Perform the CFG preparation
Vincent Lejeune960a6222013-07-19 21:45:06 +0000158 /// This step will remove every unconditionnal/dead jump instructions and make
159 /// sure all loops have an exit block
160 bool prepare();
Tom Stellard75aadc22012-12-11 21:25:42 +0000161
Craig Topper5656db42014-04-29 07:57:24 +0000162 bool runOnMachineFunction(MachineFunction &MF) override {
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000163 TII = MF.getSubtarget<R600Subtarget>().getInstrInfo();
Tom Stellardf2ba9722013-12-11 17:51:47 +0000164 TRI = &TII->getRegisterInfo();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000165 DEBUG(MF.dump(););
166 OrderedBlks.clear();
Jan Vesely7a9cca92015-03-13 17:32:46 +0000167 Visited.clear();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000168 FuncRep = &MF;
169 MLI = &getAnalysis<MachineLoopInfo>();
170 DEBUG(dbgs() << "LoopInfo:\n"; PrintLoopinfo(*MLI););
171 MDT = &getAnalysis<MachineDominatorTree>();
Craig Toppere73658d2014-04-28 04:05:08 +0000172 DEBUG(MDT->print(dbgs(), (const llvm::Module*)nullptr););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000173 PDT = &getAnalysis<MachinePostDominatorTree>();
174 DEBUG(PDT->print(dbgs()););
175 prepare();
176 run();
177 DEBUG(MF.dump(););
178 return true;
179 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000180
Vincent Lejeune960a6222013-07-19 21:45:06 +0000181protected:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000182 MachineDominatorTree *MDT;
183 MachinePostDominatorTree *PDT;
184 MachineLoopInfo *MLI;
185 const R600InstrInfo *TII;
Matt Arsenault1fafdc82015-09-19 06:41:10 +0000186 const R600RegisterInfo *TRI;
Tom Stellard75aadc22012-12-11 21:25:42 +0000187
Vincent Lejeune960a6222013-07-19 21:45:06 +0000188 // PRINT FUNCTIONS
189 /// Print the ordered Blocks.
190 void printOrderedBlocks() const {
191 size_t i = 0;
192 for (MBBVector::const_iterator iterBlk = OrderedBlks.begin(),
193 iterBlkEnd = OrderedBlks.end(); iterBlk != iterBlkEnd; ++iterBlk, ++i) {
194 dbgs() << "BB" << (*iterBlk)->getNumber();
195 dbgs() << "(" << getSCCNum(*iterBlk) << "," << (*iterBlk)->size() << ")";
196 if (i != 0 && i % 10 == 0) {
197 dbgs() << "\n";
198 } else {
199 dbgs() << " ";
200 }
201 }
202 }
203 static void PrintLoopinfo(const MachineLoopInfo &LoopInfo) {
204 for (MachineLoop::iterator iter = LoopInfo.begin(),
205 iterEnd = LoopInfo.end(); iter != iterEnd; ++iter) {
206 (*iter)->print(dbgs(), 0);
207 }
208 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000209
Vincent Lejeune960a6222013-07-19 21:45:06 +0000210 // UTILITY FUNCTIONS
211 int getSCCNum(MachineBasicBlock *MBB) const;
212 MachineBasicBlock *getLoopLandInfo(MachineLoop *LoopRep) const;
213 bool hasBackEdge(MachineBasicBlock *MBB) const;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000214 bool isRetiredBlock(MachineBasicBlock *MBB) const;
215 bool isActiveLoophead(MachineBasicBlock *MBB) const;
216 PathToKind singlePathTo(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
217 bool AllowSideEntry = true) const;
218 int countActiveBlock(MBBVector::const_iterator It,
219 MBBVector::const_iterator E) const;
220 bool needMigrateBlock(MachineBasicBlock *MBB) const;
221
222 // Utility Functions
223 void reversePredicateSetter(MachineBasicBlock::iterator I);
224 /// Compute the reversed DFS post order of Blocks
225 void orderBlocks(MachineFunction *MF);
226
Alp Tokercb402912014-01-24 17:20:08 +0000227 // Function originally from CFGStructTraits
Vincent Lejeune960a6222013-07-19 21:45:06 +0000228 void insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000229 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000230 MachineInstr *insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000231 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000232 MachineInstr *insertInstrBefore(MachineBasicBlock::iterator I, int NewOpcode);
233 void insertCondBranchBefore(MachineBasicBlock::iterator I, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000234 const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000235 void insertCondBranchBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000236 MachineBasicBlock::iterator I, int NewOpcode,
237 int RegNum, const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000238 static int getBranchNzeroOpcode(int OldOpcode);
239 static int getBranchZeroOpcode(int OldOpcode);
240 static int getContinueNzeroOpcode(int OldOpcode);
241 static int getContinueZeroOpcode(int OldOpcode);
242 static MachineBasicBlock *getTrueBranch(MachineInstr *MI);
243 static void setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB);
244 static MachineBasicBlock *getFalseBranch(MachineBasicBlock *MBB,
245 MachineInstr *MI);
246 static bool isCondBranch(MachineInstr *MI);
247 static bool isUncondBranch(MachineInstr *MI);
248 static DebugLoc getLastDebugLocInBB(MachineBasicBlock *MBB);
249 static MachineInstr *getNormalBlockBranchInstr(MachineBasicBlock *MBB);
250 /// The correct naming for this is getPossibleLoopendBlockBranchInstr.
251 ///
252 /// BB with backward-edge could have move instructions after the branch
253 /// instruction. Such move instruction "belong to" the loop backward-edge.
254 MachineInstr *getLoopendBlockBranchInstr(MachineBasicBlock *MBB);
255 static MachineInstr *getReturnInstr(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000256 static bool isReturnBlock(MachineBasicBlock *MBB);
257 static void cloneSuccessorList(MachineBasicBlock *DstMBB,
258 MachineBasicBlock *SrcMBB) ;
259 static MachineBasicBlock *clone(MachineBasicBlock *MBB);
260 /// MachineBasicBlock::ReplaceUsesOfBlockWith doesn't serve the purpose
261 /// because the AMDGPU instruction is not recognized as terminator fix this
262 /// and retire this routine
263 void replaceInstrUseOfBlockWith(MachineBasicBlock *SrcMBB,
264 MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk);
265 static void wrapup(MachineBasicBlock *MBB);
266
267
268 int patternMatch(MachineBasicBlock *MBB);
269 int patternMatchGroup(MachineBasicBlock *MBB);
270 int serialPatternMatch(MachineBasicBlock *MBB);
271 int ifPatternMatch(MachineBasicBlock *MBB);
272 int loopendPatternMatch();
273 int mergeLoop(MachineLoop *LoopRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000274
Vincent Lejeune960a6222013-07-19 21:45:06 +0000275 /// return true iff src1Blk->succ_size() == 0 && src1Blk and src2Blk are in
276 /// the same loop with LoopLandInfo without explicitly keeping track of
277 /// loopContBlks and loopBreakBlks, this is a method to get the information.
278 bool isSameloopDetachedContbreak(MachineBasicBlock *Src1MBB,
279 MachineBasicBlock *Src2MBB);
280 int handleJumpintoIf(MachineBasicBlock *HeadMBB,
281 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
282 int handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
283 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
284 int improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
285 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
286 MachineBasicBlock **LandMBBPtr);
287 void showImproveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
288 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
289 MachineBasicBlock *LandMBB, bool Detail = false);
290 int cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
291 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB);
292 void mergeSerialBlock(MachineBasicBlock *DstMBB,
293 MachineBasicBlock *SrcMBB);
294
295 void mergeIfthenelseBlock(MachineInstr *BranchMI,
296 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
297 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB);
298 void mergeLooplandBlock(MachineBasicBlock *DstMBB,
299 MachineBasicBlock *LandMBB);
300 void mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
301 MachineBasicBlock *LandMBB);
302 void settleLoopcontBlock(MachineBasicBlock *ContingMBB,
303 MachineBasicBlock *ContMBB);
304 /// normalizeInfiniteLoopExit change
305 /// B1:
306 /// uncond_br LoopHeader
307 ///
308 /// to
309 /// B1:
310 /// cond_br 1 LoopHeader dummyExit
311 /// and return the newly added dummy exit block
312 MachineBasicBlock *normalizeInfiniteLoopExit(MachineLoop *LoopRep);
313 void removeUnconditionalBranch(MachineBasicBlock *MBB);
314 /// Remove duplicate branches instructions in a block.
315 /// For instance
316 /// B0:
317 /// cond_br X B1 B2
318 /// cond_br X B1 B2
319 /// is transformed to
320 /// B0:
321 /// cond_br X B1 B2
322 void removeRedundantConditionalBranch(MachineBasicBlock *MBB);
323 void addDummyExitBlock(SmallVectorImpl<MachineBasicBlock *> &RetMBB);
324 void removeSuccessor(MachineBasicBlock *MBB);
325 MachineBasicBlock *cloneBlockForPredecessor(MachineBasicBlock *MBB,
326 MachineBasicBlock *PredMBB);
327 void migrateInstruction(MachineBasicBlock *SrcMBB,
328 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I);
329 void recordSccnum(MachineBasicBlock *MBB, int SCCNum);
330 void retireBlock(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000331
Vincent Lejeune960a6222013-07-19 21:45:06 +0000332
333private:
334 MBBInfoMap BlockInfoMap;
335 LoopLandInfoMap LLInfoMap;
336 std::map<MachineLoop *, bool> Visited;
337 MachineFunction *FuncRep;
338 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> OrderedBlks;
339};
340
341int AMDGPUCFGStructurizer::getSCCNum(MachineBasicBlock *MBB) const {
342 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
343 if (It == BlockInfoMap.end())
344 return INVALIDSCCNUM;
345 return (*It).second->SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +0000346}
347
Vincent Lejeune960a6222013-07-19 21:45:06 +0000348MachineBasicBlock *AMDGPUCFGStructurizer::getLoopLandInfo(MachineLoop *LoopRep)
349 const {
350 LoopLandInfoMap::const_iterator It = LLInfoMap.find(LoopRep);
351 if (It == LLInfoMap.end())
Craig Topper062a2ba2014-04-25 05:30:21 +0000352 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000353 return (*It).second;
354}
355
356bool AMDGPUCFGStructurizer::hasBackEdge(MachineBasicBlock *MBB) const {
357 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
358 if (!LoopRep)
359 return false;
360 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
361 return MBB->isSuccessor(LoopHeader);
362}
363
Vincent Lejeune960a6222013-07-19 21:45:06 +0000364bool AMDGPUCFGStructurizer::isRetiredBlock(MachineBasicBlock *MBB) const {
365 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
366 if (It == BlockInfoMap.end())
367 return false;
368 return (*It).second->IsRetired;
369}
370
371bool AMDGPUCFGStructurizer::isActiveLoophead(MachineBasicBlock *MBB) const {
372 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
373 while (LoopRep && LoopRep->getHeader() == MBB) {
374 MachineBasicBlock *LoopLand = getLoopLandInfo(LoopRep);
375 if(!LoopLand)
376 return true;
377 if (!isRetiredBlock(LoopLand))
378 return true;
379 LoopRep = LoopRep->getParentLoop();
380 }
381 return false;
382}
383AMDGPUCFGStructurizer::PathToKind AMDGPUCFGStructurizer::singlePathTo(
384 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
385 bool AllowSideEntry) const {
386 assert(DstMBB);
387 if (SrcMBB == DstMBB)
388 return SinglePath_InPath;
389 while (SrcMBB && SrcMBB->succ_size() == 1) {
390 SrcMBB = *SrcMBB->succ_begin();
391 if (SrcMBB == DstMBB)
392 return SinglePath_InPath;
393 if (!AllowSideEntry && SrcMBB->pred_size() > 1)
394 return Not_SinglePath;
395 }
396 if (SrcMBB && SrcMBB->succ_size()==0)
397 return SinglePath_NotInPath;
398 return Not_SinglePath;
399}
400
401int AMDGPUCFGStructurizer::countActiveBlock(MBBVector::const_iterator It,
402 MBBVector::const_iterator E) const {
403 int Count = 0;
404 while (It != E) {
405 if (!isRetiredBlock(*It))
406 ++Count;
407 ++It;
408 }
409 return Count;
410}
411
412bool AMDGPUCFGStructurizer::needMigrateBlock(MachineBasicBlock *MBB) const {
413 unsigned BlockSizeThreshold = 30;
414 unsigned CloneInstrThreshold = 100;
415 bool MultiplePreds = MBB && (MBB->pred_size() > 1);
416
417 if(!MultiplePreds)
418 return false;
419 unsigned BlkSize = MBB->size();
420 return ((BlkSize > BlockSizeThreshold) &&
421 (BlkSize * (MBB->pred_size() - 1) > CloneInstrThreshold));
422}
423
424void AMDGPUCFGStructurizer::reversePredicateSetter(
425 MachineBasicBlock::iterator I) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000426 assert(I.isValid() && "Expected valid iterator");
Duncan P. N. Exon Smith221847e2016-07-08 19:00:17 +0000427 for (;; --I) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000428 if (I->getOpcode() == AMDGPU::PRED_X) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000429 switch (I->getOperand(2).getImm()) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000430 case OPCODE_IS_ZERO_INT:
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000431 I->getOperand(2).setImm(OPCODE_IS_NOT_ZERO_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000432 return;
433 case OPCODE_IS_NOT_ZERO_INT:
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000434 I->getOperand(2).setImm(OPCODE_IS_ZERO_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000435 return;
436 case OPCODE_IS_ZERO:
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000437 I->getOperand(2).setImm(OPCODE_IS_NOT_ZERO);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000438 return;
439 case OPCODE_IS_NOT_ZERO:
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000440 I->getOperand(2).setImm(OPCODE_IS_ZERO);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000441 return;
442 default:
443 llvm_unreachable("PRED_X Opcode invalid!");
444 }
445 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000446 }
447}
448
Vincent Lejeune960a6222013-07-19 21:45:06 +0000449void AMDGPUCFGStructurizer::insertInstrEnd(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000450 int NewOpcode, const DebugLoc &DL) {
451 MachineInstr *MI =
452 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000453 MBB->push_back(MI);
454 //assume the instruction doesn't take any reg operand ...
455 SHOWNEWINSTR(MI);
456}
Tom Stellard75aadc22012-12-11 21:25:42 +0000457
Vincent Lejeune960a6222013-07-19 21:45:06 +0000458MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000459 int NewOpcode,
460 const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000461 MachineInstr *MI =
462 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
463 if (MBB->begin() != MBB->end())
464 MBB->insert(MBB->begin(), MI);
465 else
466 MBB->push_back(MI);
467 SHOWNEWINSTR(MI);
468 return MI;
469}
470
471MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(
472 MachineBasicBlock::iterator I, int NewOpcode) {
473 MachineInstr *OldMI = &(*I);
474 MachineBasicBlock *MBB = OldMI->getParent();
475 MachineInstr *NewMBB =
476 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DebugLoc());
477 MBB->insert(I, NewMBB);
478 //assume the instruction doesn't take any reg operand ...
479 SHOWNEWINSTR(NewMBB);
480 return NewMBB;
481}
482
483void AMDGPUCFGStructurizer::insertCondBranchBefore(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000484 MachineBasicBlock::iterator I, int NewOpcode, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000485 MachineInstr *OldMI = &(*I);
486 MachineBasicBlock *MBB = OldMI->getParent();
487 MachineFunction *MF = MBB->getParent();
488 MachineInstr *NewMI = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
489 MBB->insert(I, NewMI);
490 MachineInstrBuilder MIB(*MF, NewMI);
491 MIB.addReg(OldMI->getOperand(1).getReg(), false);
492 SHOWNEWINSTR(NewMI);
493 //erase later oldInstr->eraseFromParent();
494}
495
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000496void AMDGPUCFGStructurizer::insertCondBranchBefore(
497 MachineBasicBlock *blk, MachineBasicBlock::iterator I, int NewOpcode,
498 int RegNum, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000499 MachineFunction *MF = blk->getParent();
500 MachineInstr *NewInstr = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
501 //insert before
502 blk->insert(I, NewInstr);
503 MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false);
504 SHOWNEWINSTR(NewInstr);
505}
506
Vincent Lejeune960a6222013-07-19 21:45:06 +0000507int AMDGPUCFGStructurizer::getBranchNzeroOpcode(int OldOpcode) {
508 switch(OldOpcode) {
509 case AMDGPU::JUMP_COND:
510 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
511 case AMDGPU::BRANCH_COND_i32:
512 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALNZ_f32;
513 default: llvm_unreachable("internal error");
514 }
515 return -1;
516}
517
518int AMDGPUCFGStructurizer::getBranchZeroOpcode(int OldOpcode) {
519 switch(OldOpcode) {
520 case AMDGPU::JUMP_COND:
521 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
522 case AMDGPU::BRANCH_COND_i32:
523 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALZ_f32;
524 default: llvm_unreachable("internal error");
525 }
526 return -1;
527}
528
529int AMDGPUCFGStructurizer::getContinueNzeroOpcode(int OldOpcode) {
530 switch(OldOpcode) {
531 case AMDGPU::JUMP_COND:
532 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALNZ_i32;
533 default: llvm_unreachable("internal error");
534 };
535 return -1;
536}
537
538int AMDGPUCFGStructurizer::getContinueZeroOpcode(int OldOpcode) {
539 switch(OldOpcode) {
540 case AMDGPU::JUMP_COND:
541 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALZ_i32;
542 default: llvm_unreachable("internal error");
543 }
544 return -1;
545}
546
547MachineBasicBlock *AMDGPUCFGStructurizer::getTrueBranch(MachineInstr *MI) {
548 return MI->getOperand(0).getMBB();
549}
550
551void AMDGPUCFGStructurizer::setTrueBranch(MachineInstr *MI,
552 MachineBasicBlock *MBB) {
553 MI->getOperand(0).setMBB(MBB);
554}
555
556MachineBasicBlock *
557AMDGPUCFGStructurizer::getFalseBranch(MachineBasicBlock *MBB,
558 MachineInstr *MI) {
559 assert(MBB->succ_size() == 2);
560 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
561 MachineBasicBlock::succ_iterator It = MBB->succ_begin();
562 MachineBasicBlock::succ_iterator Next = It;
563 ++Next;
564 return (*It == TrueBranch) ? *Next : *It;
565}
566
567bool AMDGPUCFGStructurizer::isCondBranch(MachineInstr *MI) {
568 switch (MI->getOpcode()) {
569 case AMDGPU::JUMP_COND:
570 case AMDGPU::BRANCH_COND_i32:
571 case AMDGPU::BRANCH_COND_f32: return true;
572 default:
573 return false;
574 }
575 return false;
576}
577
578bool AMDGPUCFGStructurizer::isUncondBranch(MachineInstr *MI) {
579 switch (MI->getOpcode()) {
580 case AMDGPU::JUMP:
581 case AMDGPU::BRANCH:
582 return true;
583 default:
584 return false;
585 }
586 return false;
587}
588
589DebugLoc AMDGPUCFGStructurizer::getLastDebugLocInBB(MachineBasicBlock *MBB) {
590 //get DebugLoc from the first MachineBasicBlock instruction with debug info
591 DebugLoc DL;
592 for (MachineBasicBlock::iterator It = MBB->begin(); It != MBB->end();
593 ++It) {
594 MachineInstr *instr = &(*It);
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000595 if (instr->getDebugLoc())
Vincent Lejeune960a6222013-07-19 21:45:06 +0000596 DL = instr->getDebugLoc();
597 }
598 return DL;
599}
600
601MachineInstr *AMDGPUCFGStructurizer::getNormalBlockBranchInstr(
602 MachineBasicBlock *MBB) {
603 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
604 MachineInstr *MI = &*It;
605 if (MI && (isCondBranch(MI) || isUncondBranch(MI)))
606 return MI;
Craig Topper062a2ba2014-04-25 05:30:21 +0000607 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000608}
609
610MachineInstr *AMDGPUCFGStructurizer::getLoopendBlockBranchInstr(
611 MachineBasicBlock *MBB) {
612 for (MachineBasicBlock::reverse_iterator It = MBB->rbegin(), E = MBB->rend();
613 It != E; ++It) {
614 // FIXME: Simplify
615 MachineInstr *MI = &*It;
616 if (MI) {
617 if (isCondBranch(MI) || isUncondBranch(MI))
618 return MI;
619 else if (!TII->isMov(MI->getOpcode()))
620 break;
621 }
622 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000623 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000624}
625
626MachineInstr *AMDGPUCFGStructurizer::getReturnInstr(MachineBasicBlock *MBB) {
627 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
628 if (It != MBB->rend()) {
629 MachineInstr *instr = &(*It);
630 if (instr->getOpcode() == AMDGPU::RETURN)
631 return instr;
632 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000633 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000634}
635
Vincent Lejeune960a6222013-07-19 21:45:06 +0000636bool AMDGPUCFGStructurizer::isReturnBlock(MachineBasicBlock *MBB) {
637 MachineInstr *MI = getReturnInstr(MBB);
638 bool IsReturn = (MBB->succ_size() == 0);
639 if (MI)
640 assert(IsReturn);
641 else if (IsReturn)
642 DEBUG(
643 dbgs() << "BB" << MBB->getNumber()
644 <<" is return block without RETURN instr\n";);
645 return IsReturn;
646}
647
648void AMDGPUCFGStructurizer::cloneSuccessorList(MachineBasicBlock *DstMBB,
649 MachineBasicBlock *SrcMBB) {
650 for (MachineBasicBlock::succ_iterator It = SrcMBB->succ_begin(),
651 iterEnd = SrcMBB->succ_end(); It != iterEnd; ++It)
652 DstMBB->addSuccessor(*It); // *iter's predecessor is also taken care of
653}
654
655MachineBasicBlock *AMDGPUCFGStructurizer::clone(MachineBasicBlock *MBB) {
656 MachineFunction *Func = MBB->getParent();
657 MachineBasicBlock *NewMBB = Func->CreateMachineBasicBlock();
658 Func->push_back(NewMBB); //insert to function
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000659 for (const MachineInstr &It : *MBB)
660 NewMBB->push_back(Func->CloneMachineInstr(&It));
Vincent Lejeune960a6222013-07-19 21:45:06 +0000661 return NewMBB;
662}
663
664void AMDGPUCFGStructurizer::replaceInstrUseOfBlockWith(
665 MachineBasicBlock *SrcMBB, MachineBasicBlock *OldMBB,
666 MachineBasicBlock *NewBlk) {
667 MachineInstr *BranchMI = getLoopendBlockBranchInstr(SrcMBB);
668 if (BranchMI && isCondBranch(BranchMI) &&
669 getTrueBranch(BranchMI) == OldMBB)
670 setTrueBranch(BranchMI, NewBlk);
671}
672
673void AMDGPUCFGStructurizer::wrapup(MachineBasicBlock *MBB) {
674 assert((!MBB->getParent()->getJumpTableInfo()
675 || MBB->getParent()->getJumpTableInfo()->isEmpty())
676 && "found a jump table");
677
678 //collect continue right before endloop
679 SmallVector<MachineInstr *, DEFAULT_VEC_SLOTS> ContInstr;
680 MachineBasicBlock::iterator Pre = MBB->begin();
681 MachineBasicBlock::iterator E = MBB->end();
682 MachineBasicBlock::iterator It = Pre;
683 while (It != E) {
684 if (Pre->getOpcode() == AMDGPU::CONTINUE
685 && It->getOpcode() == AMDGPU::ENDLOOP)
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000686 ContInstr.push_back(&*Pre);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000687 Pre = It;
688 ++It;
689 }
690
691 //delete continue right before endloop
692 for (unsigned i = 0; i < ContInstr.size(); ++i)
693 ContInstr[i]->eraseFromParent();
694
695 // TODO to fix up jump table so later phase won't be confused. if
696 // (jumpTableInfo->isEmpty() == false) { need to clean the jump table, but
697 // there isn't such an interface yet. alternatively, replace all the other
698 // blocks in the jump table with the entryBlk //}
699
700}
701
702
703bool AMDGPUCFGStructurizer::prepare() {
704 bool Changed = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000705
706 //FIXME: if not reducible flow graph, make it so ???
707
Vincent Lejeune960a6222013-07-19 21:45:06 +0000708 DEBUG(dbgs() << "AMDGPUCFGStructurizer::prepare\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000709
Vincent Lejeune960a6222013-07-19 21:45:06 +0000710 orderBlocks(FuncRep);
Tom Stellard75aadc22012-12-11 21:25:42 +0000711
Vincent Lejeune960a6222013-07-19 21:45:06 +0000712 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> RetBlks;
Tom Stellard75aadc22012-12-11 21:25:42 +0000713
Vincent Lejeune960a6222013-07-19 21:45:06 +0000714 // Add an ExitBlk to loop that don't have one
715 for (MachineLoopInfo::iterator It = MLI->begin(),
716 E = MLI->end(); It != E; ++It) {
717 MachineLoop *LoopRep = (*It);
718 MBBVector ExitingMBBs;
719 LoopRep->getExitingBlocks(ExitingMBBs);
Tom Stellard75aadc22012-12-11 21:25:42 +0000720
Vincent Lejeune960a6222013-07-19 21:45:06 +0000721 if (ExitingMBBs.size() == 0) {
722 MachineBasicBlock* DummyExitBlk = normalizeInfiniteLoopExit(LoopRep);
723 if (DummyExitBlk)
724 RetBlks.push_back(DummyExitBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000725 }
726 }
727
728 // Remove unconditional branch instr.
729 // Add dummy exit block iff there are multiple returns.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000730 for (SmallVectorImpl<MachineBasicBlock *>::const_iterator
731 It = OrderedBlks.begin(), E = OrderedBlks.end(); It != E; ++It) {
732 MachineBasicBlock *MBB = *It;
733 removeUnconditionalBranch(MBB);
734 removeRedundantConditionalBranch(MBB);
735 if (isReturnBlock(MBB)) {
736 RetBlks.push_back(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000737 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000738 assert(MBB->succ_size() <= 2);
Tom Stellard75aadc22012-12-11 21:25:42 +0000739 }
740
Vincent Lejeune960a6222013-07-19 21:45:06 +0000741 if (RetBlks.size() >= 2) {
742 addDummyExitBlock(RetBlks);
743 Changed = true;
744 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000745
Vincent Lejeune960a6222013-07-19 21:45:06 +0000746 return Changed;
747}
748
749bool AMDGPUCFGStructurizer::run() {
Tom Stellard75aadc22012-12-11 21:25:42 +0000750
751 //Assume reducible CFG...
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000752 DEBUG(dbgs() << "AMDGPUCFGStructurizer::run\n");
Tom Stellard75aadc22012-12-11 21:25:42 +0000753
Tom Stellard75aadc22012-12-11 21:25:42 +0000754#ifdef STRESSTEST
755 //Use the worse block ordering to test the algorithm.
756 ReverseVector(orderedBlks);
757#endif
758
Vincent Lejeune960a6222013-07-19 21:45:06 +0000759 DEBUG(dbgs() << "Ordered blocks:\n"; printOrderedBlocks(););
760 int NumIter = 0;
761 bool Finish = false;
762 MachineBasicBlock *MBB;
763 bool MakeProgress = false;
764 int NumRemainedBlk = countActiveBlock(OrderedBlks.begin(),
765 OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000766
767 do {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000768 ++NumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000769 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000770 dbgs() << "numIter = " << NumIter
771 << ", numRemaintedBlk = " << NumRemainedBlk << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000772 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000773
Vincent Lejeune960a6222013-07-19 21:45:06 +0000774 SmallVectorImpl<MachineBasicBlock *>::const_iterator It =
775 OrderedBlks.begin();
776 SmallVectorImpl<MachineBasicBlock *>::const_iterator E =
777 OrderedBlks.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000778
Vincent Lejeune960a6222013-07-19 21:45:06 +0000779 SmallVectorImpl<MachineBasicBlock *>::const_iterator SccBeginIter =
780 It;
Craig Topper062a2ba2014-04-25 05:30:21 +0000781 MachineBasicBlock *SccBeginMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000782 int SccNumBlk = 0; // The number of active blocks, init to a
Tom Stellard75aadc22012-12-11 21:25:42 +0000783 // maximum possible number.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000784 int SccNumIter; // Number of iteration in this SCC.
Tom Stellard75aadc22012-12-11 21:25:42 +0000785
Vincent Lejeune960a6222013-07-19 21:45:06 +0000786 while (It != E) {
787 MBB = *It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000788
Vincent Lejeune960a6222013-07-19 21:45:06 +0000789 if (!SccBeginMBB) {
790 SccBeginIter = It;
791 SccBeginMBB = MBB;
792 SccNumIter = 0;
793 SccNumBlk = NumRemainedBlk; // Init to maximum possible number.
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000794 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000795 dbgs() << "start processing SCC" << getSCCNum(SccBeginMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000796 dbgs() << "\n";
797 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000798 }
799
Vincent Lejeune960a6222013-07-19 21:45:06 +0000800 if (!isRetiredBlock(MBB))
801 patternMatch(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000802
Vincent Lejeune960a6222013-07-19 21:45:06 +0000803 ++It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000804
Vincent Lejeune960a6222013-07-19 21:45:06 +0000805 bool ContNextScc = true;
806 if (It == E
807 || getSCCNum(SccBeginMBB) != getSCCNum(*It)) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000808 // Just finish one scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000809 ++SccNumIter;
810 int sccRemainedNumBlk = countActiveBlock(SccBeginIter, It);
811 if (sccRemainedNumBlk != 1 && sccRemainedNumBlk >= SccNumBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000812 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000813 dbgs() << "Can't reduce SCC " << getSCCNum(MBB)
814 << ", sccNumIter = " << SccNumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000815 dbgs() << "doesn't make any progress\n";
816 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000817 ContNextScc = true;
818 } else if (sccRemainedNumBlk != 1 && sccRemainedNumBlk < SccNumBlk) {
819 SccNumBlk = sccRemainedNumBlk;
820 It = SccBeginIter;
821 ContNextScc = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000822 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000823 dbgs() << "repeat processing SCC" << getSCCNum(MBB)
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000824 << "sccNumIter = " << SccNumIter << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000825 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000826 } else {
827 // Finish the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000828 ContNextScc = true;
Tom Stellard75aadc22012-12-11 21:25:42 +0000829 }
830 } else {
831 // Continue on next component in the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000832 ContNextScc = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000833 }
834
Vincent Lejeune960a6222013-07-19 21:45:06 +0000835 if (ContNextScc)
Craig Topper062a2ba2014-04-25 05:30:21 +0000836 SccBeginMBB = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000837 } //while, "one iteration" over the function.
838
Vincent Lejeune960a6222013-07-19 21:45:06 +0000839 MachineBasicBlock *EntryMBB =
Duncan P. N. Exon Smitha73371a2015-10-13 20:07:10 +0000840 &*GraphTraits<MachineFunction *>::nodes_begin(FuncRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000841 if (EntryMBB->succ_size() == 0) {
842 Finish = true;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000843 DEBUG(
844 dbgs() << "Reduce to one block\n";
845 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000846 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000847 int NewnumRemainedBlk
848 = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000849 // consider cloned blocks ??
Vincent Lejeune960a6222013-07-19 21:45:06 +0000850 if (NewnumRemainedBlk == 1 || NewnumRemainedBlk < NumRemainedBlk) {
851 MakeProgress = true;
852 NumRemainedBlk = NewnumRemainedBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +0000853 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000854 MakeProgress = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000855 DEBUG(
856 dbgs() << "No progress\n";
857 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000858 }
859 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000860 } while (!Finish && MakeProgress);
Tom Stellard75aadc22012-12-11 21:25:42 +0000861
862 // Misc wrap up to maintain the consistency of the Function representation.
Duncan P. N. Exon Smitha73371a2015-10-13 20:07:10 +0000863 wrapup(&*GraphTraits<MachineFunction *>::nodes_begin(FuncRep));
Tom Stellard75aadc22012-12-11 21:25:42 +0000864
865 // Detach retired Block, release memory.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000866 for (MBBInfoMap::iterator It = BlockInfoMap.begin(), E = BlockInfoMap.end();
867 It != E; ++It) {
868 if ((*It).second && (*It).second->IsRetired) {
869 assert(((*It).first)->getNumber() != -1);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000870 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000871 dbgs() << "Erase BB" << ((*It).first)->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000872 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000873 (*It).first->eraseFromParent(); //Remove from the parent Function.
Tom Stellard75aadc22012-12-11 21:25:42 +0000874 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000875 delete (*It).second;
Tom Stellard75aadc22012-12-11 21:25:42 +0000876 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000877 BlockInfoMap.clear();
878 LLInfoMap.clear();
Tom Stellard75aadc22012-12-11 21:25:42 +0000879
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000880 if (!Finish) {
881 DEBUG(FuncRep->viewCFG());
Matt Arsenault5de68cb2016-03-02 03:33:55 +0000882 report_fatal_error("IRREDUCIBLE_CFG");
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000883 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000884
885 return true;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000886}
Tom Stellard75aadc22012-12-11 21:25:42 +0000887
Tom Stellard75aadc22012-12-11 21:25:42 +0000888
Vincent Lejeune960a6222013-07-19 21:45:06 +0000889
890void AMDGPUCFGStructurizer::orderBlocks(MachineFunction *MF) {
891 int SccNum = 0;
892 MachineBasicBlock *MBB;
Duncan P. N. Exon Smith8e661ef2014-02-04 19:19:07 +0000893 for (scc_iterator<MachineFunction *> It = scc_begin(MF); !It.isAtEnd();
894 ++It, ++SccNum) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000895 const std::vector<MachineBasicBlock *> &SccNext = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000896 for (std::vector<MachineBasicBlock *>::const_iterator
897 blockIter = SccNext.begin(), blockEnd = SccNext.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000898 blockIter != blockEnd; ++blockIter) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000899 MBB = *blockIter;
900 OrderedBlks.push_back(MBB);
901 recordSccnum(MBB, SccNum);
Tom Stellard75aadc22012-12-11 21:25:42 +0000902 }
903 }
904
905 //walk through all the block in func to check for unreachable
Vincent Lejeune960a6222013-07-19 21:45:06 +0000906 typedef GraphTraits<MachineFunction *> GTM;
907 MachineFunction::iterator It = GTM::nodes_begin(MF), E = GTM::nodes_end(MF);
908 for (; It != E; ++It) {
909 MachineBasicBlock *MBB = &(*It);
910 SccNum = getSCCNum(MBB);
911 if (SccNum == INVALIDSCCNUM)
912 dbgs() << "unreachable block BB" << MBB->getNumber() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +0000913 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000914}
Tom Stellard75aadc22012-12-11 21:25:42 +0000915
Vincent Lejeune960a6222013-07-19 21:45:06 +0000916int AMDGPUCFGStructurizer::patternMatch(MachineBasicBlock *MBB) {
917 int NumMatch = 0;
918 int CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000919
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000920 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000921 dbgs() << "Begin patternMatch BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000922 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000923
Vincent Lejeune960a6222013-07-19 21:45:06 +0000924 while ((CurMatch = patternMatchGroup(MBB)) > 0)
925 NumMatch += CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000926
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000927 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000928 dbgs() << "End patternMatch BB" << MBB->getNumber()
929 << ", numMatch = " << NumMatch << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000930 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000931
Vincent Lejeune960a6222013-07-19 21:45:06 +0000932 return NumMatch;
933}
Tom Stellard75aadc22012-12-11 21:25:42 +0000934
Vincent Lejeune960a6222013-07-19 21:45:06 +0000935int AMDGPUCFGStructurizer::patternMatchGroup(MachineBasicBlock *MBB) {
936 int NumMatch = 0;
937 NumMatch += loopendPatternMatch();
938 NumMatch += serialPatternMatch(MBB);
939 NumMatch += ifPatternMatch(MBB);
940 return NumMatch;
941}
Tom Stellard75aadc22012-12-11 21:25:42 +0000942
Vincent Lejeune960a6222013-07-19 21:45:06 +0000943
944int AMDGPUCFGStructurizer::serialPatternMatch(MachineBasicBlock *MBB) {
945 if (MBB->succ_size() != 1)
Tom Stellard75aadc22012-12-11 21:25:42 +0000946 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000947
Vincent Lejeune960a6222013-07-19 21:45:06 +0000948 MachineBasicBlock *childBlk = *MBB->succ_begin();
949 if (childBlk->pred_size() != 1 || isActiveLoophead(childBlk))
Tom Stellard75aadc22012-12-11 21:25:42 +0000950 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000951
Vincent Lejeune960a6222013-07-19 21:45:06 +0000952 mergeSerialBlock(MBB, childBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000953 ++numSerialPatternMatch;
954 return 1;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000955}
Tom Stellard75aadc22012-12-11 21:25:42 +0000956
Vincent Lejeune960a6222013-07-19 21:45:06 +0000957int AMDGPUCFGStructurizer::ifPatternMatch(MachineBasicBlock *MBB) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000958 //two edges
Vincent Lejeune960a6222013-07-19 21:45:06 +0000959 if (MBB->succ_size() != 2)
Tom Stellard75aadc22012-12-11 21:25:42 +0000960 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000961 if (hasBackEdge(MBB))
Tom Stellard75aadc22012-12-11 21:25:42 +0000962 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000963 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
964 if (!BranchMI)
Tom Stellard75aadc22012-12-11 21:25:42 +0000965 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000966
Vincent Lejeune960a6222013-07-19 21:45:06 +0000967 assert(isCondBranch(BranchMI));
Tom Stellard827ec9b2013-11-18 19:43:38 +0000968 int NumMatch = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000969
Vincent Lejeune960a6222013-07-19 21:45:06 +0000970 MachineBasicBlock *TrueMBB = getTrueBranch(BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000971 NumMatch += serialPatternMatch(TrueMBB);
972 NumMatch += ifPatternMatch(TrueMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000973 MachineBasicBlock *FalseMBB = getFalseBranch(MBB, BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000974 NumMatch += serialPatternMatch(FalseMBB);
975 NumMatch += ifPatternMatch(FalseMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000976 MachineBasicBlock *LandBlk;
977 int Cloned = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000978
Vincent Lejeune960a6222013-07-19 21:45:06 +0000979 assert (!TrueMBB->succ_empty() || !FalseMBB->succ_empty());
Tom Stellard75aadc22012-12-11 21:25:42 +0000980 // TODO: Simplify
Vincent Lejeune960a6222013-07-19 21:45:06 +0000981 if (TrueMBB->succ_size() == 1 && FalseMBB->succ_size() == 1
982 && *TrueMBB->succ_begin() == *FalseMBB->succ_begin()) {
983 // Diamond pattern
984 LandBlk = *TrueMBB->succ_begin();
985 } else if (TrueMBB->succ_size() == 1 && *TrueMBB->succ_begin() == FalseMBB) {
986 // Triangle pattern, false is empty
987 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000988 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000989 } else if (FalseMBB->succ_size() == 1
990 && *FalseMBB->succ_begin() == TrueMBB) {
991 // Triangle pattern, true is empty
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +0000992 // We reverse the predicate to make a triangle, empty false pattern;
993 std::swap(TrueMBB, FalseMBB);
994 reversePredicateSetter(MBB->end());
995 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000996 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000997 } else if (FalseMBB->succ_size() == 1
998 && isSameloopDetachedContbreak(TrueMBB, FalseMBB)) {
999 LandBlk = *FalseMBB->succ_begin();
1000 } else if (TrueMBB->succ_size() == 1
1001 && isSameloopDetachedContbreak(FalseMBB, TrueMBB)) {
1002 LandBlk = *TrueMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001003 } else {
Tom Stellard827ec9b2013-11-18 19:43:38 +00001004 return NumMatch + handleJumpintoIf(MBB, TrueMBB, FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001005 }
1006
1007 // improveSimpleJumpinfoIf can handle the case where landBlk == NULL but the
1008 // new BB created for landBlk==NULL may introduce new challenge to the
1009 // reduction process.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001010 if (LandBlk &&
1011 ((TrueMBB && TrueMBB->pred_size() > 1)
1012 || (FalseMBB && FalseMBB->pred_size() > 1))) {
1013 Cloned += improveSimpleJumpintoIf(MBB, TrueMBB, FalseMBB, &LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001014 }
1015
Vincent Lejeune960a6222013-07-19 21:45:06 +00001016 if (TrueMBB && TrueMBB->pred_size() > 1) {
1017 TrueMBB = cloneBlockForPredecessor(TrueMBB, MBB);
1018 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001019 }
1020
Vincent Lejeune960a6222013-07-19 21:45:06 +00001021 if (FalseMBB && FalseMBB->pred_size() > 1) {
1022 FalseMBB = cloneBlockForPredecessor(FalseMBB, MBB);
1023 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001024 }
1025
Vincent Lejeune960a6222013-07-19 21:45:06 +00001026 mergeIfthenelseBlock(BranchMI, MBB, TrueMBB, FalseMBB, LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001027
1028 ++numIfPatternMatch;
1029
Vincent Lejeune960a6222013-07-19 21:45:06 +00001030 numClonedBlock += Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001031
Tom Stellard827ec9b2013-11-18 19:43:38 +00001032 return 1 + Cloned + NumMatch;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001033}
Tom Stellard75aadc22012-12-11 21:25:42 +00001034
Vincent Lejeune960a6222013-07-19 21:45:06 +00001035int AMDGPUCFGStructurizer::loopendPatternMatch() {
Jan Vesely18b289f2015-03-13 17:32:43 +00001036 std::deque<MachineLoop *> NestedLoops;
1037 for (auto &It: *MLI)
1038 for (MachineLoop *ML : depth_first(It))
1039 NestedLoops.push_front(ML);
David Blaikieceec2bd2014-04-11 01:50:01 +00001040
Vincent Lejeune960a6222013-07-19 21:45:06 +00001041 if (NestedLoops.size() == 0)
Tom Stellard75aadc22012-12-11 21:25:42 +00001042 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001043
Jan Vesely18b289f2015-03-13 17:32:43 +00001044 // Process nested loop outside->inside (we did push_front),
1045 // so "continue" to a outside loop won't be mistaken as "break"
1046 // of the current loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001047 int Num = 0;
Jan Vesely18b289f2015-03-13 17:32:43 +00001048 for (MachineLoop *ExaminedLoop : NestedLoops) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001049 if (ExaminedLoop->getNumBlocks() == 0 || Visited[ExaminedLoop])
Tom Stellard75aadc22012-12-11 21:25:42 +00001050 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001051 DEBUG(dbgs() << "Processing:\n"; ExaminedLoop->dump(););
1052 int NumBreak = mergeLoop(ExaminedLoop);
1053 if (NumBreak == -1)
Tom Stellard75aadc22012-12-11 21:25:42 +00001054 break;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001055 Num += NumBreak;
1056 }
1057 return Num;
1058}
Tom Stellard75aadc22012-12-11 21:25:42 +00001059
Vincent Lejeune960a6222013-07-19 21:45:06 +00001060int AMDGPUCFGStructurizer::mergeLoop(MachineLoop *LoopRep) {
1061 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1062 MBBVector ExitingMBBs;
1063 LoopRep->getExitingBlocks(ExitingMBBs);
1064 assert(!ExitingMBBs.empty() && "Infinite Loop not supported");
1065 DEBUG(dbgs() << "Loop has " << ExitingMBBs.size() << " exiting blocks\n";);
1066 // We assume a single ExitBlk
1067 MBBVector ExitBlks;
1068 LoopRep->getExitBlocks(ExitBlks);
1069 SmallPtrSet<MachineBasicBlock *, 2> ExitBlkSet;
1070 for (unsigned i = 0, e = ExitBlks.size(); i < e; ++i)
1071 ExitBlkSet.insert(ExitBlks[i]);
1072 assert(ExitBlkSet.size() == 1);
1073 MachineBasicBlock *ExitBlk = *ExitBlks.begin();
1074 assert(ExitBlk && "Loop has several exit block");
1075 MBBVector LatchBlks;
1076 typedef GraphTraits<Inverse<MachineBasicBlock*> > InvMBBTraits;
1077 InvMBBTraits::ChildIteratorType PI = InvMBBTraits::child_begin(LoopHeader),
1078 PE = InvMBBTraits::child_end(LoopHeader);
1079 for (; PI != PE; PI++) {
1080 if (LoopRep->contains(*PI))
1081 LatchBlks.push_back(*PI);
Tom Stellard75aadc22012-12-11 21:25:42 +00001082 }
1083
Vincent Lejeune960a6222013-07-19 21:45:06 +00001084 for (unsigned i = 0, e = ExitingMBBs.size(); i < e; ++i)
1085 mergeLoopbreakBlock(ExitingMBBs[i], ExitBlk);
1086 for (unsigned i = 0, e = LatchBlks.size(); i < e; ++i)
1087 settleLoopcontBlock(LatchBlks[i], LoopHeader);
1088 int Match = 0;
1089 do {
1090 Match = 0;
1091 Match += serialPatternMatch(LoopHeader);
1092 Match += ifPatternMatch(LoopHeader);
1093 } while (Match > 0);
1094 mergeLooplandBlock(LoopHeader, ExitBlk);
1095 MachineLoop *ParentLoop = LoopRep->getParentLoop();
1096 if (ParentLoop)
1097 MLI->changeLoopFor(LoopHeader, ParentLoop);
1098 else
1099 MLI->removeBlock(LoopHeader);
1100 Visited[LoopRep] = true;
1101 return 1;
1102}
Tom Stellard75aadc22012-12-11 21:25:42 +00001103
Vincent Lejeune960a6222013-07-19 21:45:06 +00001104bool AMDGPUCFGStructurizer::isSameloopDetachedContbreak(
1105 MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB) {
1106 if (Src1MBB->succ_size() == 0) {
1107 MachineLoop *LoopRep = MLI->getLoopFor(Src1MBB);
1108 if (LoopRep&& LoopRep == MLI->getLoopFor(Src2MBB)) {
1109 MachineBasicBlock *&TheEntry = LLInfoMap[LoopRep];
1110 if (TheEntry) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001111 DEBUG(
1112 dbgs() << "isLoopContBreakBlock yes src1 = BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001113 << Src1MBB->getNumber()
1114 << " src2 = BB" << Src2MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001115 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001116 return true;
1117 }
1118 }
1119 }
1120 return false;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001121}
Tom Stellard75aadc22012-12-11 21:25:42 +00001122
Vincent Lejeune960a6222013-07-19 21:45:06 +00001123int AMDGPUCFGStructurizer::handleJumpintoIf(MachineBasicBlock *HeadMBB,
1124 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1125 int Num = handleJumpintoIfImp(HeadMBB, TrueMBB, FalseMBB);
1126 if (Num == 0) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001127 DEBUG(
1128 dbgs() << "handleJumpintoIf swap trueBlk and FalseBlk" << "\n";
1129 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001130 Num = handleJumpintoIfImp(HeadMBB, FalseMBB, TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001131 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001132 return Num;
Tom Stellard75aadc22012-12-11 21:25:42 +00001133}
1134
Vincent Lejeune960a6222013-07-19 21:45:06 +00001135int AMDGPUCFGStructurizer::handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
1136 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1137 int Num = 0;
1138 MachineBasicBlock *DownBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001139
1140 //trueBlk could be the common post dominator
Vincent Lejeune960a6222013-07-19 21:45:06 +00001141 DownBlk = TrueMBB;
Tom Stellard75aadc22012-12-11 21:25:42 +00001142
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001143 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001144 dbgs() << "handleJumpintoIfImp head = BB" << HeadMBB->getNumber()
1145 << " true = BB" << TrueMBB->getNumber()
1146 << ", numSucc=" << TrueMBB->succ_size()
1147 << " false = BB" << FalseMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001148 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001149
Vincent Lejeune960a6222013-07-19 21:45:06 +00001150 while (DownBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001151 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001152 dbgs() << "check down = BB" << DownBlk->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001153 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001154
Vincent Lejeune960a6222013-07-19 21:45:06 +00001155 if (singlePathTo(FalseMBB, DownBlk) == SinglePath_InPath) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001156 DEBUG(
1157 dbgs() << " working\n";
1158 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001159
Vincent Lejeune960a6222013-07-19 21:45:06 +00001160 Num += cloneOnSideEntryTo(HeadMBB, TrueMBB, DownBlk);
1161 Num += cloneOnSideEntryTo(HeadMBB, FalseMBB, DownBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001162
Vincent Lejeune960a6222013-07-19 21:45:06 +00001163 numClonedBlock += Num;
1164 Num += serialPatternMatch(*HeadMBB->succ_begin());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001165 Num += serialPatternMatch(*std::next(HeadMBB->succ_begin()));
Vincent Lejeune960a6222013-07-19 21:45:06 +00001166 Num += ifPatternMatch(HeadMBB);
1167 assert(Num > 0);
Tom Stellard75aadc22012-12-11 21:25:42 +00001168
1169 break;
1170 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001171 DEBUG(
1172 dbgs() << " not working\n";
1173 );
Craig Topper062a2ba2014-04-25 05:30:21 +00001174 DownBlk = (DownBlk->succ_size() == 1) ? (*DownBlk->succ_begin()) : nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001175 } // walk down the postDomTree
1176
Vincent Lejeune960a6222013-07-19 21:45:06 +00001177 return Num;
1178}
Tom Stellard75aadc22012-12-11 21:25:42 +00001179
Vincent Lejeune960a6222013-07-19 21:45:06 +00001180void AMDGPUCFGStructurizer::showImproveSimpleJumpintoIf(
1181 MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB,
1182 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail) {
1183 dbgs() << "head = BB" << HeadMBB->getNumber()
1184 << " size = " << HeadMBB->size();
1185 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001186 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001187 HeadMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001188 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001189 }
1190
Vincent Lejeune960a6222013-07-19 21:45:06 +00001191 if (TrueMBB) {
1192 dbgs() << ", true = BB" << TrueMBB->getNumber() << " size = "
1193 << TrueMBB->size() << " numPred = " << TrueMBB->pred_size();
1194 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001195 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001196 TrueMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001197 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001198 }
1199 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001200 if (FalseMBB) {
1201 dbgs() << ", false = BB" << FalseMBB->getNumber() << " size = "
1202 << FalseMBB->size() << " numPred = " << FalseMBB->pred_size();
1203 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001204 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001205 FalseMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001206 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001207 }
1208 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001209 if (LandMBB) {
1210 dbgs() << ", land = BB" << LandMBB->getNumber() << " size = "
1211 << LandMBB->size() << " numPred = " << LandMBB->pred_size();
1212 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001213 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001214 LandMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001215 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001216 }
1217 }
1218
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001219 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001220}
Tom Stellard75aadc22012-12-11 21:25:42 +00001221
Vincent Lejeune960a6222013-07-19 21:45:06 +00001222int AMDGPUCFGStructurizer::improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
1223 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
1224 MachineBasicBlock **LandMBBPtr) {
1225 bool MigrateTrue = false;
1226 bool MigrateFalse = false;
Tom Stellard75aadc22012-12-11 21:25:42 +00001227
Vincent Lejeune960a6222013-07-19 21:45:06 +00001228 MachineBasicBlock *LandBlk = *LandMBBPtr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001229
Vincent Lejeune960a6222013-07-19 21:45:06 +00001230 assert((!TrueMBB || TrueMBB->succ_size() <= 1)
1231 && (!FalseMBB || FalseMBB->succ_size() <= 1));
Tom Stellard75aadc22012-12-11 21:25:42 +00001232
Vincent Lejeune960a6222013-07-19 21:45:06 +00001233 if (TrueMBB == FalseMBB)
Tom Stellard75aadc22012-12-11 21:25:42 +00001234 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001235
Vincent Lejeune960a6222013-07-19 21:45:06 +00001236 MigrateTrue = needMigrateBlock(TrueMBB);
1237 MigrateFalse = needMigrateBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001238
Vincent Lejeune960a6222013-07-19 21:45:06 +00001239 if (!MigrateTrue && !MigrateFalse)
Tom Stellard75aadc22012-12-11 21:25:42 +00001240 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001241
1242 // If we need to migrate either trueBlk and falseBlk, migrate the rest that
1243 // have more than one predecessors. without doing this, its predecessor
1244 // rather than headBlk will have undefined value in initReg.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001245 if (!MigrateTrue && TrueMBB && TrueMBB->pred_size() > 1)
1246 MigrateTrue = true;
1247 if (!MigrateFalse && FalseMBB && FalseMBB->pred_size() > 1)
1248 MigrateFalse = true;
Tom Stellard75aadc22012-12-11 21:25:42 +00001249
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001250 DEBUG(
1251 dbgs() << "before improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001252 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001253 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001254
1255 // org: headBlk => if () {trueBlk} else {falseBlk} => landBlk
1256 //
1257 // new: headBlk => if () {initReg = 1; org trueBlk branch} else
1258 // {initReg = 0; org falseBlk branch }
1259 // => landBlk => if (initReg) {org trueBlk} else {org falseBlk}
1260 // => org landBlk
1261 // if landBlk->pred_size() > 2, put the about if-else inside
1262 // if (initReg !=2) {...}
1263 //
1264 // add initReg = initVal to headBlk
1265
1266 const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32);
Tom Stellardb34186a2013-10-16 17:06:02 +00001267 if (!MigrateTrue || !MigrateFalse) {
1268 // XXX: We have an opportunity here to optimize the "branch into if" case
1269 // here. Branch into if looks like this:
1270 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001271 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001272 // diamond_head branch_from
1273 // / \ |
1274 // diamond_false diamond_true
1275 // \ /
1276 // done
1277 //
1278 // The diamond_head block begins the "if" and the diamond_true block
1279 // is the block being "branched into".
1280 //
1281 // If MigrateTrue is true, then TrueBB is the block being "branched into"
1282 // and if MigrateFalse is true, then FalseBB is the block being
1283 // "branched into"
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001284 //
Tom Stellardb34186a2013-10-16 17:06:02 +00001285 // Here is the pseudo code for how I think the optimization should work:
1286 // 1. Insert MOV GPR0, 0 before the branch instruction in diamond_head.
1287 // 2. Insert MOV GPR0, 1 before the branch instruction in branch_from.
1288 // 3. Move the branch instruction from diamond_head into its own basic
1289 // block (new_block).
1290 // 4. Add an unconditional branch from diamond_head to new_block
1291 // 5. Replace the branch instruction in branch_from with an unconditional
1292 // branch to new_block. If branch_from has multiple predecessors, then
1293 // we need to replace the True/False block in the branch
1294 // instruction instead of replacing it.
1295 // 6. Change the condition of the branch instruction in new_block from
1296 // COND to (COND || GPR0)
1297 //
1298 // In order insert these MOV instruction, we will need to use the
1299 // RegisterScavenger. Usually liveness stops being tracked during
1300 // the late machine optimization passes, however if we implement
1301 // bool TargetRegisterInfo::requiresRegisterScavenging(
1302 // const MachineFunction &MF)
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001303 // and have it return true, liveness will be tracked correctly
Tom Stellardb34186a2013-10-16 17:06:02 +00001304 // by generic optimization passes. We will also need to make sure that
1305 // all of our target-specific passes that run after regalloc and before
1306 // the CFGStructurizer track liveness and we will need to modify this pass
1307 // to correctly track liveness.
1308 //
1309 // After the above changes, the new CFG should look like this:
1310 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001311 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001312 // diamond_head branch_from
1313 // \ /
1314 // new_block
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001315 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001316 // diamond_false diamond_true
1317 // \ /
1318 // done
1319 //
1320 // Without this optimization, we are forced to duplicate the diamond_true
1321 // block and we will end up with a CFG like this:
1322 //
1323 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001324 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001325 // diamond_head branch_from
1326 // / \ |
1327 // diamond_false diamond_true diamond_true (duplicate)
1328 // \ / |
1329 // done --------------------|
1330 //
1331 // Duplicating diamond_true can be very costly especially if it has a
1332 // lot of instructions.
1333 return 0;
1334 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001335
Vincent Lejeune960a6222013-07-19 21:45:06 +00001336 int NumNewBlk = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001337
Vincent Lejeune960a6222013-07-19 21:45:06 +00001338 bool LandBlkHasOtherPred = (LandBlk->pred_size() > 2);
Tom Stellard75aadc22012-12-11 21:25:42 +00001339
1340 //insert AMDGPU::ENDIF to avoid special case "input landBlk == NULL"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001341 MachineBasicBlock::iterator I = insertInstrBefore(LandBlk, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001342
Vincent Lejeune960a6222013-07-19 21:45:06 +00001343 if (LandBlkHasOtherPred) {
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001344 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001345 unsigned CmpResReg =
1346 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001347 report_fatal_error("Extra compare instruction needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001348 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET,
1349 CmpResReg, DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001350 }
1351
Tom Stellard69f86d12013-10-16 17:05:56 +00001352 // XXX: We are running this after RA, so creating virtual registers will
1353 // cause an assertion failure in the PostRA scheduling pass.
1354 unsigned InitReg =
1355 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001356 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET, InitReg,
1357 DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001358
Vincent Lejeune960a6222013-07-19 21:45:06 +00001359 if (MigrateTrue) {
1360 migrateInstruction(TrueMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001361 // need to uncondionally insert the assignment to ensure a path from its
1362 // predecessor rather than headBlk has valid value in initReg if
1363 // (initVal != 1).
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001364 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001365 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001366 insertInstrBefore(I, AMDGPU::ELSE);
Tom Stellard75aadc22012-12-11 21:25:42 +00001367
Vincent Lejeune960a6222013-07-19 21:45:06 +00001368 if (MigrateFalse) {
1369 migrateInstruction(FalseMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001370 // need to uncondionally insert the assignment to ensure a path from its
1371 // predecessor rather than headBlk has valid value in initReg if
1372 // (initVal != 0)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001373 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001374 }
1375
Vincent Lejeune960a6222013-07-19 21:45:06 +00001376 if (LandBlkHasOtherPred) {
Tom Stellard75aadc22012-12-11 21:25:42 +00001377 // add endif
Vincent Lejeune960a6222013-07-19 21:45:06 +00001378 insertInstrBefore(I, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001379
1380 // put initReg = 2 to other predecessors of landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001381 for (MachineBasicBlock::pred_iterator PI = LandBlk->pred_begin(),
1382 PE = LandBlk->pred_end(); PI != PE; ++PI) {
1383 MachineBasicBlock *MBB = *PI;
1384 if (MBB != TrueMBB && MBB != FalseMBB)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001385 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001386 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001387 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001388 DEBUG(
1389 dbgs() << "result from improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001390 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001391 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001392
1393 // update landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001394 *LandMBBPtr = LandBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001395
Vincent Lejeune960a6222013-07-19 21:45:06 +00001396 return NumNewBlk;
1397}
Tom Stellard75aadc22012-12-11 21:25:42 +00001398
Vincent Lejeune960a6222013-07-19 21:45:06 +00001399void AMDGPUCFGStructurizer::mergeSerialBlock(MachineBasicBlock *DstMBB,
1400 MachineBasicBlock *SrcMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001401 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001402 dbgs() << "serialPattern BB" << DstMBB->getNumber()
1403 << " <= BB" << SrcMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001404 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001405 DstMBB->splice(DstMBB->end(), SrcMBB, SrcMBB->begin(), SrcMBB->end());
Tom Stellard75aadc22012-12-11 21:25:42 +00001406
Cong Houc1069892015-12-13 09:26:17 +00001407 DstMBB->removeSuccessor(SrcMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001408 cloneSuccessorList(DstMBB, SrcMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001409
Vincent Lejeune960a6222013-07-19 21:45:06 +00001410 removeSuccessor(SrcMBB);
1411 MLI->removeBlock(SrcMBB);
1412 retireBlock(SrcMBB);
1413}
Tom Stellard75aadc22012-12-11 21:25:42 +00001414
Vincent Lejeune960a6222013-07-19 21:45:06 +00001415void AMDGPUCFGStructurizer::mergeIfthenelseBlock(MachineInstr *BranchMI,
1416 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
1417 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB) {
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001418 assert (TrueMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001419 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001420 dbgs() << "ifPattern BB" << MBB->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001421 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001422 if (TrueMBB) {
1423 dbgs() << "BB" << TrueMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001424 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001425 dbgs() << " } else ";
1426 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001427 if (FalseMBB) {
1428 dbgs() << "BB" << FalseMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001429 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001430 dbgs() << " }\n ";
1431 dbgs() << "landBlock: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001432 if (!LandMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001433 dbgs() << "NULL";
Tom Stellard75aadc22012-12-11 21:25:42 +00001434 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001435 dbgs() << "BB" << LandMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001436 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001437 dbgs() << "\n";
1438 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001439
Vincent Lejeune960a6222013-07-19 21:45:06 +00001440 int OldOpcode = BranchMI->getOpcode();
1441 DebugLoc BranchDL = BranchMI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001442
1443// transform to
1444// if cond
1445// trueBlk
1446// else
1447// falseBlk
1448// endif
1449// landBlk
1450
Vincent Lejeune960a6222013-07-19 21:45:06 +00001451 MachineBasicBlock::iterator I = BranchMI;
1452 insertCondBranchBefore(I, getBranchNzeroOpcode(OldOpcode),
1453 BranchDL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001454
Vincent Lejeune960a6222013-07-19 21:45:06 +00001455 if (TrueMBB) {
1456 MBB->splice(I, TrueMBB, TrueMBB->begin(), TrueMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001457 MBB->removeSuccessor(TrueMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001458 if (LandMBB && TrueMBB->succ_size()!=0)
Cong Houc1069892015-12-13 09:26:17 +00001459 TrueMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001460 retireBlock(TrueMBB);
1461 MLI->removeBlock(TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001462 }
1463
Vincent Lejeune960a6222013-07-19 21:45:06 +00001464 if (FalseMBB) {
1465 insertInstrBefore(I, AMDGPU::ELSE);
1466 MBB->splice(I, FalseMBB, FalseMBB->begin(),
1467 FalseMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001468 MBB->removeSuccessor(FalseMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001469 if (LandMBB && FalseMBB->succ_size() != 0)
Cong Houc1069892015-12-13 09:26:17 +00001470 FalseMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001471 retireBlock(FalseMBB);
1472 MLI->removeBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001473 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001474 insertInstrBefore(I, AMDGPU::ENDIF);
1475
1476 BranchMI->eraseFromParent();
1477
1478 if (LandMBB && TrueMBB && FalseMBB)
1479 MBB->addSuccessor(LandMBB);
1480
1481}
1482
1483void AMDGPUCFGStructurizer::mergeLooplandBlock(MachineBasicBlock *DstBlk,
1484 MachineBasicBlock *LandMBB) {
1485 DEBUG(dbgs() << "loopPattern header = BB" << DstBlk->getNumber()
1486 << " land = BB" << LandMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001487
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001488 insertInstrBefore(DstBlk, AMDGPU::WHILELOOP, DebugLoc());
1489 insertInstrEnd(DstBlk, AMDGPU::ENDLOOP, DebugLoc());
Cong Houd97c1002015-12-01 05:29:22 +00001490 DstBlk->replaceSuccessor(DstBlk, LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001491}
Tom Stellard75aadc22012-12-11 21:25:42 +00001492
Tom Stellard75aadc22012-12-11 21:25:42 +00001493
Vincent Lejeune960a6222013-07-19 21:45:06 +00001494void AMDGPUCFGStructurizer::mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
1495 MachineBasicBlock *LandMBB) {
1496 DEBUG(dbgs() << "loopbreakPattern exiting = BB" << ExitingMBB->getNumber()
1497 << " land = BB" << LandMBB->getNumber() << "\n";);
1498 MachineInstr *BranchMI = getLoopendBlockBranchInstr(ExitingMBB);
1499 assert(BranchMI && isCondBranch(BranchMI));
1500 DebugLoc DL = BranchMI->getDebugLoc();
1501 MachineBasicBlock *TrueBranch = getTrueBranch(BranchMI);
1502 MachineBasicBlock::iterator I = BranchMI;
1503 if (TrueBranch != LandMBB)
1504 reversePredicateSetter(I);
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001505 insertCondBranchBefore(ExitingMBB, I, AMDGPU::IF_PREDICATE_SET, AMDGPU::PREDICATE_BIT, DL);
1506 insertInstrBefore(I, AMDGPU::BREAK);
1507 insertInstrBefore(I, AMDGPU::ENDIF);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001508 //now branchInst can be erase safely
1509 BranchMI->eraseFromParent();
1510 //now take care of successors, retire blocks
Cong Houc1069892015-12-13 09:26:17 +00001511 ExitingMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001512}
Tom Stellard75aadc22012-12-11 21:25:42 +00001513
Vincent Lejeune960a6222013-07-19 21:45:06 +00001514void AMDGPUCFGStructurizer::settleLoopcontBlock(MachineBasicBlock *ContingMBB,
1515 MachineBasicBlock *ContMBB) {
1516 DEBUG(dbgs() << "settleLoopcontBlock conting = BB"
1517 << ContingMBB->getNumber()
1518 << ", cont = BB" << ContMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001519
Vincent Lejeune960a6222013-07-19 21:45:06 +00001520 MachineInstr *MI = getLoopendBlockBranchInstr(ContingMBB);
1521 if (MI) {
1522 assert(isCondBranch(MI));
1523 MachineBasicBlock::iterator I = MI;
1524 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
1525 int OldOpcode = MI->getOpcode();
1526 DebugLoc DL = MI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001527
Vincent Lejeune960a6222013-07-19 21:45:06 +00001528 bool UseContinueLogical = ((&*ContingMBB->rbegin()) == MI);
1529
David Blaikie4eaa79c2015-03-23 20:56:44 +00001530 if (!UseContinueLogical) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001531 int BranchOpcode =
1532 TrueBranch == ContMBB ? getBranchNzeroOpcode(OldOpcode) :
1533 getBranchZeroOpcode(OldOpcode);
1534 insertCondBranchBefore(I, BranchOpcode, DL);
1535 // insertEnd to ensure phi-moves, if exist, go before the continue-instr.
1536 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE, DL);
1537 insertInstrEnd(ContingMBB, AMDGPU::ENDIF, DL);
1538 } else {
1539 int BranchOpcode =
1540 TrueBranch == ContMBB ? getContinueNzeroOpcode(OldOpcode) :
1541 getContinueZeroOpcode(OldOpcode);
1542 insertCondBranchBefore(I, BranchOpcode, DL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001543 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001544
1545 MI->eraseFromParent();
1546 } else {
1547 // if we've arrived here then we've already erased the branch instruction
1548 // travel back up the basic block to see the last reference of our debug
1549 // location we've just inserted that reference here so it should be
1550 // representative insertEnd to ensure phi-moves, if exist, go before the
1551 // continue-instr.
1552 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE,
1553 getLastDebugLocInBB(ContingMBB));
Tom Stellard75aadc22012-12-11 21:25:42 +00001554 }
1555}
1556
Vincent Lejeune960a6222013-07-19 21:45:06 +00001557int AMDGPUCFGStructurizer::cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
1558 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB) {
1559 int Cloned = 0;
1560 assert(PreMBB->isSuccessor(SrcMBB));
1561 while (SrcMBB && SrcMBB != DstMBB) {
1562 assert(SrcMBB->succ_size() == 1);
1563 if (SrcMBB->pred_size() > 1) {
1564 SrcMBB = cloneBlockForPredecessor(SrcMBB, PreMBB);
1565 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001566 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001567
Vincent Lejeune960a6222013-07-19 21:45:06 +00001568 PreMBB = SrcMBB;
1569 SrcMBB = *SrcMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001570 }
1571
Vincent Lejeune960a6222013-07-19 21:45:06 +00001572 return Cloned;
1573}
Tom Stellard75aadc22012-12-11 21:25:42 +00001574
Vincent Lejeune960a6222013-07-19 21:45:06 +00001575MachineBasicBlock *
1576AMDGPUCFGStructurizer::cloneBlockForPredecessor(MachineBasicBlock *MBB,
1577 MachineBasicBlock *PredMBB) {
1578 assert(PredMBB->isSuccessor(MBB) &&
Tom Stellard75aadc22012-12-11 21:25:42 +00001579 "succBlk is not a prececessor of curBlk");
1580
Vincent Lejeune960a6222013-07-19 21:45:06 +00001581 MachineBasicBlock *CloneMBB = clone(MBB); //clone instructions
1582 replaceInstrUseOfBlockWith(PredMBB, MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001583 //srcBlk, oldBlk, newBlk
1584
Cong Houd97c1002015-12-01 05:29:22 +00001585 PredMBB->replaceSuccessor(MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001586
1587 // add all successor to cloneBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001588 cloneSuccessorList(CloneMBB, MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001589
Vincent Lejeune960a6222013-07-19 21:45:06 +00001590 numClonedInstr += MBB->size();
Tom Stellard75aadc22012-12-11 21:25:42 +00001591
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001592 DEBUG(
1593 dbgs() << "Cloned block: " << "BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001594 << MBB->getNumber() << "size " << MBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001595 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001596
Vincent Lejeune960a6222013-07-19 21:45:06 +00001597 SHOWNEWBLK(CloneMBB, "result of Cloned block: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001598
Vincent Lejeune960a6222013-07-19 21:45:06 +00001599 return CloneMBB;
1600}
Tom Stellard75aadc22012-12-11 21:25:42 +00001601
Vincent Lejeune960a6222013-07-19 21:45:06 +00001602void AMDGPUCFGStructurizer::migrateInstruction(MachineBasicBlock *SrcMBB,
1603 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I) {
1604 MachineBasicBlock::iterator SpliceEnd;
Tom Stellard75aadc22012-12-11 21:25:42 +00001605 //look for the input branchinstr, not the AMDGPU branchinstr
Vincent Lejeune960a6222013-07-19 21:45:06 +00001606 MachineInstr *BranchMI = getNormalBlockBranchInstr(SrcMBB);
1607 if (!BranchMI) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001608 DEBUG(
1609 dbgs() << "migrateInstruction don't see branch instr\n" ;
1610 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001611 SpliceEnd = SrcMBB->end();
Tom Stellard75aadc22012-12-11 21:25:42 +00001612 } else {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001613 DEBUG(dbgs() << "migrateInstruction see branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001614 SpliceEnd = BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001615 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001616 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001617 dbgs() << "migrateInstruction before splice dstSize = " << DstMBB->size()
1618 << "srcSize = " << SrcMBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001619 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001620
1621 //splice insert before insertPos
Vincent Lejeune960a6222013-07-19 21:45:06 +00001622 DstMBB->splice(I, SrcMBB, SrcMBB->begin(), SpliceEnd);
Tom Stellard75aadc22012-12-11 21:25:42 +00001623
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001624 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001625 dbgs() << "migrateInstruction after splice dstSize = " << DstMBB->size()
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001626 << "srcSize = " << SrcMBB->size() << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001627 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001628}
Tom Stellard75aadc22012-12-11 21:25:42 +00001629
Vincent Lejeune960a6222013-07-19 21:45:06 +00001630MachineBasicBlock *
1631AMDGPUCFGStructurizer::normalizeInfiniteLoopExit(MachineLoop* LoopRep) {
1632 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1633 MachineBasicBlock *LoopLatch = LoopRep->getLoopLatch();
Tom Stellard75aadc22012-12-11 21:25:42 +00001634
Vincent Lejeune960a6222013-07-19 21:45:06 +00001635 if (!LoopHeader || !LoopLatch)
Craig Topper062a2ba2014-04-25 05:30:21 +00001636 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001637 MachineInstr *BranchMI = getLoopendBlockBranchInstr(LoopLatch);
1638 // Is LoopRep an infinite loop ?
1639 if (!BranchMI || !isUncondBranch(BranchMI))
Craig Topper062a2ba2014-04-25 05:30:21 +00001640 return nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001641
Vincent Lejeune960a6222013-07-19 21:45:06 +00001642 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1643 FuncRep->push_back(DummyExitBlk); //insert to function
1644 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock to normalize infiniteLoop: ");
1645 DEBUG(dbgs() << "Old branch instr: " << *BranchMI << "\n";);
Tom Stellard1d46fb22015-07-16 15:38:29 +00001646 LLVMContext &Ctx = LoopHeader->getParent()->getFunction()->getContext();
1647 Ctx.emitError("Extra register needed to handle CFG");
1648 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001649}
Tom Stellard75aadc22012-12-11 21:25:42 +00001650
Vincent Lejeune960a6222013-07-19 21:45:06 +00001651void AMDGPUCFGStructurizer::removeUnconditionalBranch(MachineBasicBlock *MBB) {
1652 MachineInstr *BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001653
1654 // I saw two unconditional branch in one basic block in example
1655 // test_fc_do_while_or.c need to fix the upstream on this to remove the loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001656 while ((BranchMI = getLoopendBlockBranchInstr(MBB))
1657 && isUncondBranch(BranchMI)) {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001658 DEBUG(dbgs() << "Removing uncond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001659 BranchMI->eraseFromParent();
Tom Stellard75aadc22012-12-11 21:25:42 +00001660 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001661}
Tom Stellard75aadc22012-12-11 21:25:42 +00001662
Vincent Lejeune960a6222013-07-19 21:45:06 +00001663void AMDGPUCFGStructurizer::removeRedundantConditionalBranch(
1664 MachineBasicBlock *MBB) {
1665 if (MBB->succ_size() != 2)
1666 return;
1667 MachineBasicBlock *MBB1 = *MBB->succ_begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001668 MachineBasicBlock *MBB2 = *std::next(MBB->succ_begin());
Vincent Lejeune960a6222013-07-19 21:45:06 +00001669 if (MBB1 != MBB2)
1670 return;
Tom Stellard75aadc22012-12-11 21:25:42 +00001671
Vincent Lejeune960a6222013-07-19 21:45:06 +00001672 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
1673 assert(BranchMI && isCondBranch(BranchMI));
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001674 DEBUG(dbgs() << "Removing unneeded cond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001675 BranchMI->eraseFromParent();
1676 SHOWNEWBLK(MBB1, "Removing redundant successor");
Cong Houc1069892015-12-13 09:26:17 +00001677 MBB->removeSuccessor(MBB1, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001678}
Tom Stellard75aadc22012-12-11 21:25:42 +00001679
Vincent Lejeune960a6222013-07-19 21:45:06 +00001680void AMDGPUCFGStructurizer::addDummyExitBlock(
1681 SmallVectorImpl<MachineBasicBlock*> &RetMBB) {
1682 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1683 FuncRep->push_back(DummyExitBlk); //insert to function
1684 insertInstrEnd(DummyExitBlk, AMDGPU::RETURN);
Tom Stellard75aadc22012-12-11 21:25:42 +00001685
Vincent Lejeune960a6222013-07-19 21:45:06 +00001686 for (SmallVectorImpl<MachineBasicBlock *>::iterator It = RetMBB.begin(),
1687 E = RetMBB.end(); It != E; ++It) {
1688 MachineBasicBlock *MBB = *It;
1689 MachineInstr *MI = getReturnInstr(MBB);
1690 if (MI)
1691 MI->eraseFromParent();
1692 MBB->addSuccessor(DummyExitBlk);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001693 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001694 dbgs() << "Add dummyExitBlock to BB" << MBB->getNumber()
Tom Stellard75aadc22012-12-11 21:25:42 +00001695 << " successors\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001696 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001697 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001698 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001699}
1700
Vincent Lejeune960a6222013-07-19 21:45:06 +00001701void AMDGPUCFGStructurizer::removeSuccessor(MachineBasicBlock *MBB) {
1702 while (MBB->succ_size())
1703 MBB->removeSuccessor(*MBB->succ_begin());
Tom Stellard75aadc22012-12-11 21:25:42 +00001704}
1705
Vincent Lejeune960a6222013-07-19 21:45:06 +00001706void AMDGPUCFGStructurizer::recordSccnum(MachineBasicBlock *MBB,
1707 int SccNum) {
1708 BlockInformation *&srcBlkInfo = BlockInfoMap[MBB];
1709 if (!srcBlkInfo)
1710 srcBlkInfo = new BlockInformation();
1711 srcBlkInfo->SccNum = SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +00001712}
1713
Vincent Lejeune960a6222013-07-19 21:45:06 +00001714void AMDGPUCFGStructurizer::retireBlock(MachineBasicBlock *MBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001715 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001716 dbgs() << "Retiring BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001717 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001718
Vincent Lejeune960a6222013-07-19 21:45:06 +00001719 BlockInformation *&SrcBlkInfo = BlockInfoMap[MBB];
Tom Stellard75aadc22012-12-11 21:25:42 +00001720
Vincent Lejeune960a6222013-07-19 21:45:06 +00001721 if (!SrcBlkInfo)
1722 SrcBlkInfo = new BlockInformation();
Tom Stellard75aadc22012-12-11 21:25:42 +00001723
Vincent Lejeune960a6222013-07-19 21:45:06 +00001724 SrcBlkInfo->IsRetired = true;
1725 assert(MBB->succ_size() == 0 && MBB->pred_size() == 0
Tom Stellard75aadc22012-12-11 21:25:42 +00001726 && "can't retire block yet");
1727}
1728
Vincent Lejeune960a6222013-07-19 21:45:06 +00001729char AMDGPUCFGStructurizer::ID = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001730
Benjamin Kramer635e3682013-05-23 15:43:05 +00001731} // end anonymous namespace
Tom Stellard75aadc22012-12-11 21:25:42 +00001732
Tom Stellard75aadc22012-12-11 21:25:42 +00001733
Tom Stellardf2ba9722013-12-11 17:51:47 +00001734INITIALIZE_PASS_BEGIN(AMDGPUCFGStructurizer, "amdgpustructurizer",
1735 "AMDGPU CFG Structurizer", false, false)
1736INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1737INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
1738INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
1739INITIALIZE_PASS_END(AMDGPUCFGStructurizer, "amdgpustructurizer",
1740 "AMDGPU CFG Structurizer", false, false)
1741
1742FunctionPass *llvm::createAMDGPUCFGStructurizerPass() {
1743 return new AMDGPUCFGStructurizer();
Tom Stellard75aadc22012-12-11 21:25:42 +00001744}