blob: 236942cb6efd06ba049efea79f4b703566f754ab [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
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000223 void reversePredicateSetter(MachineBasicBlock::iterator I,
224 MachineBasicBlock &MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000225 /// Compute the reversed DFS post order of Blocks
226 void orderBlocks(MachineFunction *MF);
227
Alp Tokercb402912014-01-24 17:20:08 +0000228 // Function originally from CFGStructTraits
Vincent Lejeune960a6222013-07-19 21:45:06 +0000229 void insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000230 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000231 MachineInstr *insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000232 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000233 MachineInstr *insertInstrBefore(MachineBasicBlock::iterator I, int NewOpcode);
234 void insertCondBranchBefore(MachineBasicBlock::iterator I, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000235 const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000236 void insertCondBranchBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000237 MachineBasicBlock::iterator I, int NewOpcode,
238 int RegNum, const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000239 static int getBranchNzeroOpcode(int OldOpcode);
240 static int getBranchZeroOpcode(int OldOpcode);
241 static int getContinueNzeroOpcode(int OldOpcode);
242 static int getContinueZeroOpcode(int OldOpcode);
243 static MachineBasicBlock *getTrueBranch(MachineInstr *MI);
244 static void setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB);
245 static MachineBasicBlock *getFalseBranch(MachineBasicBlock *MBB,
246 MachineInstr *MI);
247 static bool isCondBranch(MachineInstr *MI);
248 static bool isUncondBranch(MachineInstr *MI);
249 static DebugLoc getLastDebugLocInBB(MachineBasicBlock *MBB);
250 static MachineInstr *getNormalBlockBranchInstr(MachineBasicBlock *MBB);
251 /// The correct naming for this is getPossibleLoopendBlockBranchInstr.
252 ///
253 /// BB with backward-edge could have move instructions after the branch
254 /// instruction. Such move instruction "belong to" the loop backward-edge.
255 MachineInstr *getLoopendBlockBranchInstr(MachineBasicBlock *MBB);
256 static MachineInstr *getReturnInstr(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000257 static bool isReturnBlock(MachineBasicBlock *MBB);
258 static void cloneSuccessorList(MachineBasicBlock *DstMBB,
259 MachineBasicBlock *SrcMBB) ;
260 static MachineBasicBlock *clone(MachineBasicBlock *MBB);
261 /// MachineBasicBlock::ReplaceUsesOfBlockWith doesn't serve the purpose
262 /// because the AMDGPU instruction is not recognized as terminator fix this
263 /// and retire this routine
264 void replaceInstrUseOfBlockWith(MachineBasicBlock *SrcMBB,
265 MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk);
266 static void wrapup(MachineBasicBlock *MBB);
267
268
269 int patternMatch(MachineBasicBlock *MBB);
270 int patternMatchGroup(MachineBasicBlock *MBB);
271 int serialPatternMatch(MachineBasicBlock *MBB);
272 int ifPatternMatch(MachineBasicBlock *MBB);
273 int loopendPatternMatch();
274 int mergeLoop(MachineLoop *LoopRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000275
Vincent Lejeune960a6222013-07-19 21:45:06 +0000276 /// return true iff src1Blk->succ_size() == 0 && src1Blk and src2Blk are in
277 /// the same loop with LoopLandInfo without explicitly keeping track of
278 /// loopContBlks and loopBreakBlks, this is a method to get the information.
279 bool isSameloopDetachedContbreak(MachineBasicBlock *Src1MBB,
280 MachineBasicBlock *Src2MBB);
281 int handleJumpintoIf(MachineBasicBlock *HeadMBB,
282 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
283 int handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
284 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
285 int improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
286 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
287 MachineBasicBlock **LandMBBPtr);
288 void showImproveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
289 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
290 MachineBasicBlock *LandMBB, bool Detail = false);
291 int cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
292 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB);
293 void mergeSerialBlock(MachineBasicBlock *DstMBB,
294 MachineBasicBlock *SrcMBB);
295
296 void mergeIfthenelseBlock(MachineInstr *BranchMI,
297 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
298 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB);
299 void mergeLooplandBlock(MachineBasicBlock *DstMBB,
300 MachineBasicBlock *LandMBB);
301 void mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
302 MachineBasicBlock *LandMBB);
303 void settleLoopcontBlock(MachineBasicBlock *ContingMBB,
304 MachineBasicBlock *ContMBB);
305 /// normalizeInfiniteLoopExit change
306 /// B1:
307 /// uncond_br LoopHeader
308 ///
309 /// to
310 /// B1:
311 /// cond_br 1 LoopHeader dummyExit
312 /// and return the newly added dummy exit block
313 MachineBasicBlock *normalizeInfiniteLoopExit(MachineLoop *LoopRep);
314 void removeUnconditionalBranch(MachineBasicBlock *MBB);
315 /// Remove duplicate branches instructions in a block.
316 /// For instance
317 /// B0:
318 /// cond_br X B1 B2
319 /// cond_br X B1 B2
320 /// is transformed to
321 /// B0:
322 /// cond_br X B1 B2
323 void removeRedundantConditionalBranch(MachineBasicBlock *MBB);
324 void addDummyExitBlock(SmallVectorImpl<MachineBasicBlock *> &RetMBB);
325 void removeSuccessor(MachineBasicBlock *MBB);
326 MachineBasicBlock *cloneBlockForPredecessor(MachineBasicBlock *MBB,
327 MachineBasicBlock *PredMBB);
328 void migrateInstruction(MachineBasicBlock *SrcMBB,
329 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I);
330 void recordSccnum(MachineBasicBlock *MBB, int SCCNum);
331 void retireBlock(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000332
Vincent Lejeune960a6222013-07-19 21:45:06 +0000333
334private:
335 MBBInfoMap BlockInfoMap;
336 LoopLandInfoMap LLInfoMap;
337 std::map<MachineLoop *, bool> Visited;
338 MachineFunction *FuncRep;
339 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> OrderedBlks;
340};
341
342int AMDGPUCFGStructurizer::getSCCNum(MachineBasicBlock *MBB) const {
343 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
344 if (It == BlockInfoMap.end())
345 return INVALIDSCCNUM;
346 return (*It).second->SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +0000347}
348
Vincent Lejeune960a6222013-07-19 21:45:06 +0000349MachineBasicBlock *AMDGPUCFGStructurizer::getLoopLandInfo(MachineLoop *LoopRep)
350 const {
351 LoopLandInfoMap::const_iterator It = LLInfoMap.find(LoopRep);
352 if (It == LLInfoMap.end())
Craig Topper062a2ba2014-04-25 05:30:21 +0000353 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000354 return (*It).second;
355}
356
357bool AMDGPUCFGStructurizer::hasBackEdge(MachineBasicBlock *MBB) const {
358 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
359 if (!LoopRep)
360 return false;
361 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
362 return MBB->isSuccessor(LoopHeader);
363}
364
Vincent Lejeune960a6222013-07-19 21:45:06 +0000365bool AMDGPUCFGStructurizer::isRetiredBlock(MachineBasicBlock *MBB) const {
366 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
367 if (It == BlockInfoMap.end())
368 return false;
369 return (*It).second->IsRetired;
370}
371
372bool AMDGPUCFGStructurizer::isActiveLoophead(MachineBasicBlock *MBB) const {
373 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
374 while (LoopRep && LoopRep->getHeader() == MBB) {
375 MachineBasicBlock *LoopLand = getLoopLandInfo(LoopRep);
376 if(!LoopLand)
377 return true;
378 if (!isRetiredBlock(LoopLand))
379 return true;
380 LoopRep = LoopRep->getParentLoop();
381 }
382 return false;
383}
384AMDGPUCFGStructurizer::PathToKind AMDGPUCFGStructurizer::singlePathTo(
385 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
386 bool AllowSideEntry) const {
387 assert(DstMBB);
388 if (SrcMBB == DstMBB)
389 return SinglePath_InPath;
390 while (SrcMBB && SrcMBB->succ_size() == 1) {
391 SrcMBB = *SrcMBB->succ_begin();
392 if (SrcMBB == DstMBB)
393 return SinglePath_InPath;
394 if (!AllowSideEntry && SrcMBB->pred_size() > 1)
395 return Not_SinglePath;
396 }
397 if (SrcMBB && SrcMBB->succ_size()==0)
398 return SinglePath_NotInPath;
399 return Not_SinglePath;
400}
401
402int AMDGPUCFGStructurizer::countActiveBlock(MBBVector::const_iterator It,
403 MBBVector::const_iterator E) const {
404 int Count = 0;
405 while (It != E) {
406 if (!isRetiredBlock(*It))
407 ++Count;
408 ++It;
409 }
410 return Count;
411}
412
413bool AMDGPUCFGStructurizer::needMigrateBlock(MachineBasicBlock *MBB) const {
414 unsigned BlockSizeThreshold = 30;
415 unsigned CloneInstrThreshold = 100;
416 bool MultiplePreds = MBB && (MBB->pred_size() > 1);
417
418 if(!MultiplePreds)
419 return false;
420 unsigned BlkSize = MBB->size();
421 return ((BlkSize > BlockSizeThreshold) &&
422 (BlkSize * (MBB->pred_size() - 1) > CloneInstrThreshold));
423}
424
425void AMDGPUCFGStructurizer::reversePredicateSetter(
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000426 MachineBasicBlock::iterator I, MachineBasicBlock &MBB) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000427 assert(I.isValid() && "Expected valid iterator");
Duncan P. N. Exon Smith221847e2016-07-08 19:00:17 +0000428 for (;; --I) {
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000429 if (I == MBB.end())
430 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000431 if (I->getOpcode() == AMDGPU::PRED_X) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000432 switch (I->getOperand(2).getImm()) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000433 case OPCODE_IS_ZERO_INT:
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000434 I->getOperand(2).setImm(OPCODE_IS_NOT_ZERO_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000435 return;
436 case OPCODE_IS_NOT_ZERO_INT:
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000437 I->getOperand(2).setImm(OPCODE_IS_ZERO_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000438 return;
439 case OPCODE_IS_ZERO:
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000440 I->getOperand(2).setImm(OPCODE_IS_NOT_ZERO);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000441 return;
442 case OPCODE_IS_NOT_ZERO:
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000443 I->getOperand(2).setImm(OPCODE_IS_ZERO);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000444 return;
445 default:
446 llvm_unreachable("PRED_X Opcode invalid!");
447 }
448 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000449 }
450}
451
Vincent Lejeune960a6222013-07-19 21:45:06 +0000452void AMDGPUCFGStructurizer::insertInstrEnd(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000453 int NewOpcode, const DebugLoc &DL) {
454 MachineInstr *MI =
455 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000456 MBB->push_back(MI);
457 //assume the instruction doesn't take any reg operand ...
458 SHOWNEWINSTR(MI);
459}
Tom Stellard75aadc22012-12-11 21:25:42 +0000460
Vincent Lejeune960a6222013-07-19 21:45:06 +0000461MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000462 int NewOpcode,
463 const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000464 MachineInstr *MI =
465 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
466 if (MBB->begin() != MBB->end())
467 MBB->insert(MBB->begin(), MI);
468 else
469 MBB->push_back(MI);
470 SHOWNEWINSTR(MI);
471 return MI;
472}
473
474MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(
475 MachineBasicBlock::iterator I, int NewOpcode) {
476 MachineInstr *OldMI = &(*I);
477 MachineBasicBlock *MBB = OldMI->getParent();
478 MachineInstr *NewMBB =
479 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DebugLoc());
480 MBB->insert(I, NewMBB);
481 //assume the instruction doesn't take any reg operand ...
482 SHOWNEWINSTR(NewMBB);
483 return NewMBB;
484}
485
486void AMDGPUCFGStructurizer::insertCondBranchBefore(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000487 MachineBasicBlock::iterator I, int NewOpcode, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000488 MachineInstr *OldMI = &(*I);
489 MachineBasicBlock *MBB = OldMI->getParent();
490 MachineFunction *MF = MBB->getParent();
491 MachineInstr *NewMI = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
492 MBB->insert(I, NewMI);
493 MachineInstrBuilder MIB(*MF, NewMI);
494 MIB.addReg(OldMI->getOperand(1).getReg(), false);
495 SHOWNEWINSTR(NewMI);
496 //erase later oldInstr->eraseFromParent();
497}
498
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000499void AMDGPUCFGStructurizer::insertCondBranchBefore(
500 MachineBasicBlock *blk, MachineBasicBlock::iterator I, int NewOpcode,
501 int RegNum, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000502 MachineFunction *MF = blk->getParent();
503 MachineInstr *NewInstr = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
504 //insert before
505 blk->insert(I, NewInstr);
506 MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false);
507 SHOWNEWINSTR(NewInstr);
508}
509
Vincent Lejeune960a6222013-07-19 21:45:06 +0000510int AMDGPUCFGStructurizer::getBranchNzeroOpcode(int OldOpcode) {
511 switch(OldOpcode) {
512 case AMDGPU::JUMP_COND:
513 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
514 case AMDGPU::BRANCH_COND_i32:
515 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALNZ_f32;
516 default: llvm_unreachable("internal error");
517 }
518 return -1;
519}
520
521int AMDGPUCFGStructurizer::getBranchZeroOpcode(int OldOpcode) {
522 switch(OldOpcode) {
523 case AMDGPU::JUMP_COND:
524 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
525 case AMDGPU::BRANCH_COND_i32:
526 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALZ_f32;
527 default: llvm_unreachable("internal error");
528 }
529 return -1;
530}
531
532int AMDGPUCFGStructurizer::getContinueNzeroOpcode(int OldOpcode) {
533 switch(OldOpcode) {
534 case AMDGPU::JUMP_COND:
535 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALNZ_i32;
536 default: llvm_unreachable("internal error");
537 };
538 return -1;
539}
540
541int AMDGPUCFGStructurizer::getContinueZeroOpcode(int OldOpcode) {
542 switch(OldOpcode) {
543 case AMDGPU::JUMP_COND:
544 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALZ_i32;
545 default: llvm_unreachable("internal error");
546 }
547 return -1;
548}
549
550MachineBasicBlock *AMDGPUCFGStructurizer::getTrueBranch(MachineInstr *MI) {
551 return MI->getOperand(0).getMBB();
552}
553
554void AMDGPUCFGStructurizer::setTrueBranch(MachineInstr *MI,
555 MachineBasicBlock *MBB) {
556 MI->getOperand(0).setMBB(MBB);
557}
558
559MachineBasicBlock *
560AMDGPUCFGStructurizer::getFalseBranch(MachineBasicBlock *MBB,
561 MachineInstr *MI) {
562 assert(MBB->succ_size() == 2);
563 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
564 MachineBasicBlock::succ_iterator It = MBB->succ_begin();
565 MachineBasicBlock::succ_iterator Next = It;
566 ++Next;
567 return (*It == TrueBranch) ? *Next : *It;
568}
569
570bool AMDGPUCFGStructurizer::isCondBranch(MachineInstr *MI) {
571 switch (MI->getOpcode()) {
572 case AMDGPU::JUMP_COND:
573 case AMDGPU::BRANCH_COND_i32:
574 case AMDGPU::BRANCH_COND_f32: return true;
575 default:
576 return false;
577 }
578 return false;
579}
580
581bool AMDGPUCFGStructurizer::isUncondBranch(MachineInstr *MI) {
582 switch (MI->getOpcode()) {
583 case AMDGPU::JUMP:
584 case AMDGPU::BRANCH:
585 return true;
586 default:
587 return false;
588 }
589 return false;
590}
591
592DebugLoc AMDGPUCFGStructurizer::getLastDebugLocInBB(MachineBasicBlock *MBB) {
593 //get DebugLoc from the first MachineBasicBlock instruction with debug info
594 DebugLoc DL;
595 for (MachineBasicBlock::iterator It = MBB->begin(); It != MBB->end();
596 ++It) {
597 MachineInstr *instr = &(*It);
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000598 if (instr->getDebugLoc())
Vincent Lejeune960a6222013-07-19 21:45:06 +0000599 DL = instr->getDebugLoc();
600 }
601 return DL;
602}
603
604MachineInstr *AMDGPUCFGStructurizer::getNormalBlockBranchInstr(
605 MachineBasicBlock *MBB) {
606 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
607 MachineInstr *MI = &*It;
608 if (MI && (isCondBranch(MI) || isUncondBranch(MI)))
609 return MI;
Craig Topper062a2ba2014-04-25 05:30:21 +0000610 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000611}
612
613MachineInstr *AMDGPUCFGStructurizer::getLoopendBlockBranchInstr(
614 MachineBasicBlock *MBB) {
615 for (MachineBasicBlock::reverse_iterator It = MBB->rbegin(), E = MBB->rend();
616 It != E; ++It) {
617 // FIXME: Simplify
618 MachineInstr *MI = &*It;
619 if (MI) {
620 if (isCondBranch(MI) || isUncondBranch(MI))
621 return MI;
622 else if (!TII->isMov(MI->getOpcode()))
623 break;
624 }
625 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000626 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000627}
628
629MachineInstr *AMDGPUCFGStructurizer::getReturnInstr(MachineBasicBlock *MBB) {
630 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
631 if (It != MBB->rend()) {
632 MachineInstr *instr = &(*It);
633 if (instr->getOpcode() == AMDGPU::RETURN)
634 return instr;
635 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000636 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000637}
638
Vincent Lejeune960a6222013-07-19 21:45:06 +0000639bool AMDGPUCFGStructurizer::isReturnBlock(MachineBasicBlock *MBB) {
640 MachineInstr *MI = getReturnInstr(MBB);
641 bool IsReturn = (MBB->succ_size() == 0);
642 if (MI)
643 assert(IsReturn);
644 else if (IsReturn)
645 DEBUG(
646 dbgs() << "BB" << MBB->getNumber()
647 <<" is return block without RETURN instr\n";);
648 return IsReturn;
649}
650
651void AMDGPUCFGStructurizer::cloneSuccessorList(MachineBasicBlock *DstMBB,
652 MachineBasicBlock *SrcMBB) {
653 for (MachineBasicBlock::succ_iterator It = SrcMBB->succ_begin(),
654 iterEnd = SrcMBB->succ_end(); It != iterEnd; ++It)
655 DstMBB->addSuccessor(*It); // *iter's predecessor is also taken care of
656}
657
658MachineBasicBlock *AMDGPUCFGStructurizer::clone(MachineBasicBlock *MBB) {
659 MachineFunction *Func = MBB->getParent();
660 MachineBasicBlock *NewMBB = Func->CreateMachineBasicBlock();
661 Func->push_back(NewMBB); //insert to function
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000662 for (const MachineInstr &It : *MBB)
663 NewMBB->push_back(Func->CloneMachineInstr(&It));
Vincent Lejeune960a6222013-07-19 21:45:06 +0000664 return NewMBB;
665}
666
667void AMDGPUCFGStructurizer::replaceInstrUseOfBlockWith(
668 MachineBasicBlock *SrcMBB, MachineBasicBlock *OldMBB,
669 MachineBasicBlock *NewBlk) {
670 MachineInstr *BranchMI = getLoopendBlockBranchInstr(SrcMBB);
671 if (BranchMI && isCondBranch(BranchMI) &&
672 getTrueBranch(BranchMI) == OldMBB)
673 setTrueBranch(BranchMI, NewBlk);
674}
675
676void AMDGPUCFGStructurizer::wrapup(MachineBasicBlock *MBB) {
677 assert((!MBB->getParent()->getJumpTableInfo()
678 || MBB->getParent()->getJumpTableInfo()->isEmpty())
679 && "found a jump table");
680
681 //collect continue right before endloop
682 SmallVector<MachineInstr *, DEFAULT_VEC_SLOTS> ContInstr;
683 MachineBasicBlock::iterator Pre = MBB->begin();
684 MachineBasicBlock::iterator E = MBB->end();
685 MachineBasicBlock::iterator It = Pre;
686 while (It != E) {
687 if (Pre->getOpcode() == AMDGPU::CONTINUE
688 && It->getOpcode() == AMDGPU::ENDLOOP)
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000689 ContInstr.push_back(&*Pre);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000690 Pre = It;
691 ++It;
692 }
693
694 //delete continue right before endloop
695 for (unsigned i = 0; i < ContInstr.size(); ++i)
696 ContInstr[i]->eraseFromParent();
697
698 // TODO to fix up jump table so later phase won't be confused. if
699 // (jumpTableInfo->isEmpty() == false) { need to clean the jump table, but
700 // there isn't such an interface yet. alternatively, replace all the other
701 // blocks in the jump table with the entryBlk //}
702
703}
704
705
706bool AMDGPUCFGStructurizer::prepare() {
707 bool Changed = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000708
709 //FIXME: if not reducible flow graph, make it so ???
710
Vincent Lejeune960a6222013-07-19 21:45:06 +0000711 DEBUG(dbgs() << "AMDGPUCFGStructurizer::prepare\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000712
Vincent Lejeune960a6222013-07-19 21:45:06 +0000713 orderBlocks(FuncRep);
Tom Stellard75aadc22012-12-11 21:25:42 +0000714
Vincent Lejeune960a6222013-07-19 21:45:06 +0000715 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> RetBlks;
Tom Stellard75aadc22012-12-11 21:25:42 +0000716
Vincent Lejeune960a6222013-07-19 21:45:06 +0000717 // Add an ExitBlk to loop that don't have one
718 for (MachineLoopInfo::iterator It = MLI->begin(),
719 E = MLI->end(); It != E; ++It) {
720 MachineLoop *LoopRep = (*It);
721 MBBVector ExitingMBBs;
722 LoopRep->getExitingBlocks(ExitingMBBs);
Tom Stellard75aadc22012-12-11 21:25:42 +0000723
Vincent Lejeune960a6222013-07-19 21:45:06 +0000724 if (ExitingMBBs.size() == 0) {
725 MachineBasicBlock* DummyExitBlk = normalizeInfiniteLoopExit(LoopRep);
726 if (DummyExitBlk)
727 RetBlks.push_back(DummyExitBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000728 }
729 }
730
731 // Remove unconditional branch instr.
732 // Add dummy exit block iff there are multiple returns.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000733 for (SmallVectorImpl<MachineBasicBlock *>::const_iterator
734 It = OrderedBlks.begin(), E = OrderedBlks.end(); It != E; ++It) {
735 MachineBasicBlock *MBB = *It;
736 removeUnconditionalBranch(MBB);
737 removeRedundantConditionalBranch(MBB);
738 if (isReturnBlock(MBB)) {
739 RetBlks.push_back(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000740 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000741 assert(MBB->succ_size() <= 2);
Tom Stellard75aadc22012-12-11 21:25:42 +0000742 }
743
Vincent Lejeune960a6222013-07-19 21:45:06 +0000744 if (RetBlks.size() >= 2) {
745 addDummyExitBlock(RetBlks);
746 Changed = true;
747 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000748
Vincent Lejeune960a6222013-07-19 21:45:06 +0000749 return Changed;
750}
751
752bool AMDGPUCFGStructurizer::run() {
Tom Stellard75aadc22012-12-11 21:25:42 +0000753
754 //Assume reducible CFG...
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000755 DEBUG(dbgs() << "AMDGPUCFGStructurizer::run\n");
Tom Stellard75aadc22012-12-11 21:25:42 +0000756
Tom Stellard75aadc22012-12-11 21:25:42 +0000757#ifdef STRESSTEST
758 //Use the worse block ordering to test the algorithm.
759 ReverseVector(orderedBlks);
760#endif
761
Vincent Lejeune960a6222013-07-19 21:45:06 +0000762 DEBUG(dbgs() << "Ordered blocks:\n"; printOrderedBlocks(););
763 int NumIter = 0;
764 bool Finish = false;
765 MachineBasicBlock *MBB;
766 bool MakeProgress = false;
767 int NumRemainedBlk = countActiveBlock(OrderedBlks.begin(),
768 OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000769
770 do {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000771 ++NumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000772 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000773 dbgs() << "numIter = " << NumIter
774 << ", numRemaintedBlk = " << NumRemainedBlk << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000775 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000776
Vincent Lejeune960a6222013-07-19 21:45:06 +0000777 SmallVectorImpl<MachineBasicBlock *>::const_iterator It =
778 OrderedBlks.begin();
779 SmallVectorImpl<MachineBasicBlock *>::const_iterator E =
780 OrderedBlks.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000781
Vincent Lejeune960a6222013-07-19 21:45:06 +0000782 SmallVectorImpl<MachineBasicBlock *>::const_iterator SccBeginIter =
783 It;
Craig Topper062a2ba2014-04-25 05:30:21 +0000784 MachineBasicBlock *SccBeginMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000785 int SccNumBlk = 0; // The number of active blocks, init to a
Tom Stellard75aadc22012-12-11 21:25:42 +0000786 // maximum possible number.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000787 int SccNumIter; // Number of iteration in this SCC.
Tom Stellard75aadc22012-12-11 21:25:42 +0000788
Vincent Lejeune960a6222013-07-19 21:45:06 +0000789 while (It != E) {
790 MBB = *It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000791
Vincent Lejeune960a6222013-07-19 21:45:06 +0000792 if (!SccBeginMBB) {
793 SccBeginIter = It;
794 SccBeginMBB = MBB;
795 SccNumIter = 0;
796 SccNumBlk = NumRemainedBlk; // Init to maximum possible number.
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000797 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000798 dbgs() << "start processing SCC" << getSCCNum(SccBeginMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000799 dbgs() << "\n";
800 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000801 }
802
Vincent Lejeune960a6222013-07-19 21:45:06 +0000803 if (!isRetiredBlock(MBB))
804 patternMatch(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000805
Vincent Lejeune960a6222013-07-19 21:45:06 +0000806 ++It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000807
Vincent Lejeune960a6222013-07-19 21:45:06 +0000808 bool ContNextScc = true;
809 if (It == E
810 || getSCCNum(SccBeginMBB) != getSCCNum(*It)) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000811 // Just finish one scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000812 ++SccNumIter;
813 int sccRemainedNumBlk = countActiveBlock(SccBeginIter, It);
814 if (sccRemainedNumBlk != 1 && sccRemainedNumBlk >= SccNumBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000815 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000816 dbgs() << "Can't reduce SCC " << getSCCNum(MBB)
817 << ", sccNumIter = " << SccNumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000818 dbgs() << "doesn't make any progress\n";
819 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000820 ContNextScc = true;
821 } else if (sccRemainedNumBlk != 1 && sccRemainedNumBlk < SccNumBlk) {
822 SccNumBlk = sccRemainedNumBlk;
823 It = SccBeginIter;
824 ContNextScc = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000825 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000826 dbgs() << "repeat processing SCC" << getSCCNum(MBB)
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000827 << "sccNumIter = " << SccNumIter << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000828 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000829 } else {
830 // Finish the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000831 ContNextScc = true;
Tom Stellard75aadc22012-12-11 21:25:42 +0000832 }
833 } else {
834 // Continue on next component in the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000835 ContNextScc = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000836 }
837
Vincent Lejeune960a6222013-07-19 21:45:06 +0000838 if (ContNextScc)
Craig Topper062a2ba2014-04-25 05:30:21 +0000839 SccBeginMBB = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000840 } //while, "one iteration" over the function.
841
Vincent Lejeune960a6222013-07-19 21:45:06 +0000842 MachineBasicBlock *EntryMBB =
Duncan P. N. Exon Smitha73371a2015-10-13 20:07:10 +0000843 &*GraphTraits<MachineFunction *>::nodes_begin(FuncRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000844 if (EntryMBB->succ_size() == 0) {
845 Finish = true;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000846 DEBUG(
847 dbgs() << "Reduce to one block\n";
848 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000849 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000850 int NewnumRemainedBlk
851 = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000852 // consider cloned blocks ??
Vincent Lejeune960a6222013-07-19 21:45:06 +0000853 if (NewnumRemainedBlk == 1 || NewnumRemainedBlk < NumRemainedBlk) {
854 MakeProgress = true;
855 NumRemainedBlk = NewnumRemainedBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +0000856 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000857 MakeProgress = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000858 DEBUG(
859 dbgs() << "No progress\n";
860 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000861 }
862 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000863 } while (!Finish && MakeProgress);
Tom Stellard75aadc22012-12-11 21:25:42 +0000864
865 // Misc wrap up to maintain the consistency of the Function representation.
Duncan P. N. Exon Smitha73371a2015-10-13 20:07:10 +0000866 wrapup(&*GraphTraits<MachineFunction *>::nodes_begin(FuncRep));
Tom Stellard75aadc22012-12-11 21:25:42 +0000867
868 // Detach retired Block, release memory.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000869 for (MBBInfoMap::iterator It = BlockInfoMap.begin(), E = BlockInfoMap.end();
870 It != E; ++It) {
871 if ((*It).second && (*It).second->IsRetired) {
872 assert(((*It).first)->getNumber() != -1);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000873 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000874 dbgs() << "Erase BB" << ((*It).first)->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000875 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000876 (*It).first->eraseFromParent(); //Remove from the parent Function.
Tom Stellard75aadc22012-12-11 21:25:42 +0000877 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000878 delete (*It).second;
Tom Stellard75aadc22012-12-11 21:25:42 +0000879 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000880 BlockInfoMap.clear();
881 LLInfoMap.clear();
Tom Stellard75aadc22012-12-11 21:25:42 +0000882
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000883 if (!Finish) {
884 DEBUG(FuncRep->viewCFG());
Matt Arsenault5de68cb2016-03-02 03:33:55 +0000885 report_fatal_error("IRREDUCIBLE_CFG");
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000886 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000887
888 return true;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000889}
Tom Stellard75aadc22012-12-11 21:25:42 +0000890
Tom Stellard75aadc22012-12-11 21:25:42 +0000891
Vincent Lejeune960a6222013-07-19 21:45:06 +0000892
893void AMDGPUCFGStructurizer::orderBlocks(MachineFunction *MF) {
894 int SccNum = 0;
895 MachineBasicBlock *MBB;
Duncan P. N. Exon Smith8e661ef2014-02-04 19:19:07 +0000896 for (scc_iterator<MachineFunction *> It = scc_begin(MF); !It.isAtEnd();
897 ++It, ++SccNum) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000898 const std::vector<MachineBasicBlock *> &SccNext = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000899 for (std::vector<MachineBasicBlock *>::const_iterator
900 blockIter = SccNext.begin(), blockEnd = SccNext.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000901 blockIter != blockEnd; ++blockIter) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000902 MBB = *blockIter;
903 OrderedBlks.push_back(MBB);
904 recordSccnum(MBB, SccNum);
Tom Stellard75aadc22012-12-11 21:25:42 +0000905 }
906 }
907
908 //walk through all the block in func to check for unreachable
Vincent Lejeune960a6222013-07-19 21:45:06 +0000909 typedef GraphTraits<MachineFunction *> GTM;
910 MachineFunction::iterator It = GTM::nodes_begin(MF), E = GTM::nodes_end(MF);
911 for (; It != E; ++It) {
912 MachineBasicBlock *MBB = &(*It);
913 SccNum = getSCCNum(MBB);
914 if (SccNum == INVALIDSCCNUM)
915 dbgs() << "unreachable block BB" << MBB->getNumber() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +0000916 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000917}
Tom Stellard75aadc22012-12-11 21:25:42 +0000918
Vincent Lejeune960a6222013-07-19 21:45:06 +0000919int AMDGPUCFGStructurizer::patternMatch(MachineBasicBlock *MBB) {
920 int NumMatch = 0;
921 int CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000922
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000923 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000924 dbgs() << "Begin patternMatch BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000925 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000926
Vincent Lejeune960a6222013-07-19 21:45:06 +0000927 while ((CurMatch = patternMatchGroup(MBB)) > 0)
928 NumMatch += CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000929
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000930 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000931 dbgs() << "End patternMatch BB" << MBB->getNumber()
932 << ", numMatch = " << NumMatch << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000933 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000934
Vincent Lejeune960a6222013-07-19 21:45:06 +0000935 return NumMatch;
936}
Tom Stellard75aadc22012-12-11 21:25:42 +0000937
Vincent Lejeune960a6222013-07-19 21:45:06 +0000938int AMDGPUCFGStructurizer::patternMatchGroup(MachineBasicBlock *MBB) {
939 int NumMatch = 0;
940 NumMatch += loopendPatternMatch();
941 NumMatch += serialPatternMatch(MBB);
942 NumMatch += ifPatternMatch(MBB);
943 return NumMatch;
944}
Tom Stellard75aadc22012-12-11 21:25:42 +0000945
Vincent Lejeune960a6222013-07-19 21:45:06 +0000946
947int AMDGPUCFGStructurizer::serialPatternMatch(MachineBasicBlock *MBB) {
948 if (MBB->succ_size() != 1)
Tom Stellard75aadc22012-12-11 21:25:42 +0000949 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000950
Vincent Lejeune960a6222013-07-19 21:45:06 +0000951 MachineBasicBlock *childBlk = *MBB->succ_begin();
952 if (childBlk->pred_size() != 1 || isActiveLoophead(childBlk))
Tom Stellard75aadc22012-12-11 21:25:42 +0000953 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000954
Vincent Lejeune960a6222013-07-19 21:45:06 +0000955 mergeSerialBlock(MBB, childBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000956 ++numSerialPatternMatch;
957 return 1;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000958}
Tom Stellard75aadc22012-12-11 21:25:42 +0000959
Vincent Lejeune960a6222013-07-19 21:45:06 +0000960int AMDGPUCFGStructurizer::ifPatternMatch(MachineBasicBlock *MBB) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000961 //two edges
Vincent Lejeune960a6222013-07-19 21:45:06 +0000962 if (MBB->succ_size() != 2)
Tom Stellard75aadc22012-12-11 21:25:42 +0000963 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000964 if (hasBackEdge(MBB))
Tom Stellard75aadc22012-12-11 21:25:42 +0000965 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000966 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
967 if (!BranchMI)
Tom Stellard75aadc22012-12-11 21:25:42 +0000968 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000969
Vincent Lejeune960a6222013-07-19 21:45:06 +0000970 assert(isCondBranch(BranchMI));
Tom Stellard827ec9b2013-11-18 19:43:38 +0000971 int NumMatch = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000972
Vincent Lejeune960a6222013-07-19 21:45:06 +0000973 MachineBasicBlock *TrueMBB = getTrueBranch(BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000974 NumMatch += serialPatternMatch(TrueMBB);
975 NumMatch += ifPatternMatch(TrueMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000976 MachineBasicBlock *FalseMBB = getFalseBranch(MBB, BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000977 NumMatch += serialPatternMatch(FalseMBB);
978 NumMatch += ifPatternMatch(FalseMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000979 MachineBasicBlock *LandBlk;
980 int Cloned = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000981
Vincent Lejeune960a6222013-07-19 21:45:06 +0000982 assert (!TrueMBB->succ_empty() || !FalseMBB->succ_empty());
Tom Stellard75aadc22012-12-11 21:25:42 +0000983 // TODO: Simplify
Vincent Lejeune960a6222013-07-19 21:45:06 +0000984 if (TrueMBB->succ_size() == 1 && FalseMBB->succ_size() == 1
985 && *TrueMBB->succ_begin() == *FalseMBB->succ_begin()) {
986 // Diamond pattern
987 LandBlk = *TrueMBB->succ_begin();
988 } else if (TrueMBB->succ_size() == 1 && *TrueMBB->succ_begin() == FalseMBB) {
989 // Triangle pattern, false is empty
990 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000991 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000992 } else if (FalseMBB->succ_size() == 1
993 && *FalseMBB->succ_begin() == TrueMBB) {
994 // Triangle pattern, true is empty
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +0000995 // We reverse the predicate to make a triangle, empty false pattern;
996 std::swap(TrueMBB, FalseMBB);
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000997 reversePredicateSetter(MBB->end(), *MBB);
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +0000998 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000999 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001000 } else if (FalseMBB->succ_size() == 1
1001 && isSameloopDetachedContbreak(TrueMBB, FalseMBB)) {
1002 LandBlk = *FalseMBB->succ_begin();
1003 } else if (TrueMBB->succ_size() == 1
1004 && isSameloopDetachedContbreak(FalseMBB, TrueMBB)) {
1005 LandBlk = *TrueMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001006 } else {
Tom Stellard827ec9b2013-11-18 19:43:38 +00001007 return NumMatch + handleJumpintoIf(MBB, TrueMBB, FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001008 }
1009
1010 // improveSimpleJumpinfoIf can handle the case where landBlk == NULL but the
1011 // new BB created for landBlk==NULL may introduce new challenge to the
1012 // reduction process.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001013 if (LandBlk &&
1014 ((TrueMBB && TrueMBB->pred_size() > 1)
1015 || (FalseMBB && FalseMBB->pred_size() > 1))) {
1016 Cloned += improveSimpleJumpintoIf(MBB, TrueMBB, FalseMBB, &LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001017 }
1018
Vincent Lejeune960a6222013-07-19 21:45:06 +00001019 if (TrueMBB && TrueMBB->pred_size() > 1) {
1020 TrueMBB = cloneBlockForPredecessor(TrueMBB, MBB);
1021 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001022 }
1023
Vincent Lejeune960a6222013-07-19 21:45:06 +00001024 if (FalseMBB && FalseMBB->pred_size() > 1) {
1025 FalseMBB = cloneBlockForPredecessor(FalseMBB, MBB);
1026 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001027 }
1028
Vincent Lejeune960a6222013-07-19 21:45:06 +00001029 mergeIfthenelseBlock(BranchMI, MBB, TrueMBB, FalseMBB, LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001030
1031 ++numIfPatternMatch;
1032
Vincent Lejeune960a6222013-07-19 21:45:06 +00001033 numClonedBlock += Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001034
Tom Stellard827ec9b2013-11-18 19:43:38 +00001035 return 1 + Cloned + NumMatch;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001036}
Tom Stellard75aadc22012-12-11 21:25:42 +00001037
Vincent Lejeune960a6222013-07-19 21:45:06 +00001038int AMDGPUCFGStructurizer::loopendPatternMatch() {
Jan Vesely18b289f2015-03-13 17:32:43 +00001039 std::deque<MachineLoop *> NestedLoops;
1040 for (auto &It: *MLI)
1041 for (MachineLoop *ML : depth_first(It))
1042 NestedLoops.push_front(ML);
David Blaikieceec2bd2014-04-11 01:50:01 +00001043
Vincent Lejeune960a6222013-07-19 21:45:06 +00001044 if (NestedLoops.size() == 0)
Tom Stellard75aadc22012-12-11 21:25:42 +00001045 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001046
Jan Vesely18b289f2015-03-13 17:32:43 +00001047 // Process nested loop outside->inside (we did push_front),
1048 // so "continue" to a outside loop won't be mistaken as "break"
1049 // of the current loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001050 int Num = 0;
Jan Vesely18b289f2015-03-13 17:32:43 +00001051 for (MachineLoop *ExaminedLoop : NestedLoops) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001052 if (ExaminedLoop->getNumBlocks() == 0 || Visited[ExaminedLoop])
Tom Stellard75aadc22012-12-11 21:25:42 +00001053 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001054 DEBUG(dbgs() << "Processing:\n"; ExaminedLoop->dump(););
1055 int NumBreak = mergeLoop(ExaminedLoop);
1056 if (NumBreak == -1)
Tom Stellard75aadc22012-12-11 21:25:42 +00001057 break;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001058 Num += NumBreak;
1059 }
1060 return Num;
1061}
Tom Stellard75aadc22012-12-11 21:25:42 +00001062
Vincent Lejeune960a6222013-07-19 21:45:06 +00001063int AMDGPUCFGStructurizer::mergeLoop(MachineLoop *LoopRep) {
1064 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1065 MBBVector ExitingMBBs;
1066 LoopRep->getExitingBlocks(ExitingMBBs);
1067 assert(!ExitingMBBs.empty() && "Infinite Loop not supported");
1068 DEBUG(dbgs() << "Loop has " << ExitingMBBs.size() << " exiting blocks\n";);
1069 // We assume a single ExitBlk
1070 MBBVector ExitBlks;
1071 LoopRep->getExitBlocks(ExitBlks);
1072 SmallPtrSet<MachineBasicBlock *, 2> ExitBlkSet;
1073 for (unsigned i = 0, e = ExitBlks.size(); i < e; ++i)
1074 ExitBlkSet.insert(ExitBlks[i]);
1075 assert(ExitBlkSet.size() == 1);
1076 MachineBasicBlock *ExitBlk = *ExitBlks.begin();
1077 assert(ExitBlk && "Loop has several exit block");
1078 MBBVector LatchBlks;
1079 typedef GraphTraits<Inverse<MachineBasicBlock*> > InvMBBTraits;
1080 InvMBBTraits::ChildIteratorType PI = InvMBBTraits::child_begin(LoopHeader),
1081 PE = InvMBBTraits::child_end(LoopHeader);
1082 for (; PI != PE; PI++) {
1083 if (LoopRep->contains(*PI))
1084 LatchBlks.push_back(*PI);
Tom Stellard75aadc22012-12-11 21:25:42 +00001085 }
1086
Vincent Lejeune960a6222013-07-19 21:45:06 +00001087 for (unsigned i = 0, e = ExitingMBBs.size(); i < e; ++i)
1088 mergeLoopbreakBlock(ExitingMBBs[i], ExitBlk);
1089 for (unsigned i = 0, e = LatchBlks.size(); i < e; ++i)
1090 settleLoopcontBlock(LatchBlks[i], LoopHeader);
1091 int Match = 0;
1092 do {
1093 Match = 0;
1094 Match += serialPatternMatch(LoopHeader);
1095 Match += ifPatternMatch(LoopHeader);
1096 } while (Match > 0);
1097 mergeLooplandBlock(LoopHeader, ExitBlk);
1098 MachineLoop *ParentLoop = LoopRep->getParentLoop();
1099 if (ParentLoop)
1100 MLI->changeLoopFor(LoopHeader, ParentLoop);
1101 else
1102 MLI->removeBlock(LoopHeader);
1103 Visited[LoopRep] = true;
1104 return 1;
1105}
Tom Stellard75aadc22012-12-11 21:25:42 +00001106
Vincent Lejeune960a6222013-07-19 21:45:06 +00001107bool AMDGPUCFGStructurizer::isSameloopDetachedContbreak(
1108 MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB) {
1109 if (Src1MBB->succ_size() == 0) {
1110 MachineLoop *LoopRep = MLI->getLoopFor(Src1MBB);
1111 if (LoopRep&& LoopRep == MLI->getLoopFor(Src2MBB)) {
1112 MachineBasicBlock *&TheEntry = LLInfoMap[LoopRep];
1113 if (TheEntry) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001114 DEBUG(
1115 dbgs() << "isLoopContBreakBlock yes src1 = BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001116 << Src1MBB->getNumber()
1117 << " src2 = BB" << Src2MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001118 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001119 return true;
1120 }
1121 }
1122 }
1123 return false;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001124}
Tom Stellard75aadc22012-12-11 21:25:42 +00001125
Vincent Lejeune960a6222013-07-19 21:45:06 +00001126int AMDGPUCFGStructurizer::handleJumpintoIf(MachineBasicBlock *HeadMBB,
1127 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1128 int Num = handleJumpintoIfImp(HeadMBB, TrueMBB, FalseMBB);
1129 if (Num == 0) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001130 DEBUG(
1131 dbgs() << "handleJumpintoIf swap trueBlk and FalseBlk" << "\n";
1132 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001133 Num = handleJumpintoIfImp(HeadMBB, FalseMBB, TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001134 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001135 return Num;
Tom Stellard75aadc22012-12-11 21:25:42 +00001136}
1137
Vincent Lejeune960a6222013-07-19 21:45:06 +00001138int AMDGPUCFGStructurizer::handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
1139 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1140 int Num = 0;
1141 MachineBasicBlock *DownBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001142
1143 //trueBlk could be the common post dominator
Vincent Lejeune960a6222013-07-19 21:45:06 +00001144 DownBlk = TrueMBB;
Tom Stellard75aadc22012-12-11 21:25:42 +00001145
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001146 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001147 dbgs() << "handleJumpintoIfImp head = BB" << HeadMBB->getNumber()
1148 << " true = BB" << TrueMBB->getNumber()
1149 << ", numSucc=" << TrueMBB->succ_size()
1150 << " false = BB" << FalseMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001151 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001152
Vincent Lejeune960a6222013-07-19 21:45:06 +00001153 while (DownBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001154 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001155 dbgs() << "check down = BB" << DownBlk->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001156 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001157
Vincent Lejeune960a6222013-07-19 21:45:06 +00001158 if (singlePathTo(FalseMBB, DownBlk) == SinglePath_InPath) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001159 DEBUG(
1160 dbgs() << " working\n";
1161 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001162
Vincent Lejeune960a6222013-07-19 21:45:06 +00001163 Num += cloneOnSideEntryTo(HeadMBB, TrueMBB, DownBlk);
1164 Num += cloneOnSideEntryTo(HeadMBB, FalseMBB, DownBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001165
Vincent Lejeune960a6222013-07-19 21:45:06 +00001166 numClonedBlock += Num;
1167 Num += serialPatternMatch(*HeadMBB->succ_begin());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001168 Num += serialPatternMatch(*std::next(HeadMBB->succ_begin()));
Vincent Lejeune960a6222013-07-19 21:45:06 +00001169 Num += ifPatternMatch(HeadMBB);
1170 assert(Num > 0);
Tom Stellard75aadc22012-12-11 21:25:42 +00001171
1172 break;
1173 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001174 DEBUG(
1175 dbgs() << " not working\n";
1176 );
Craig Topper062a2ba2014-04-25 05:30:21 +00001177 DownBlk = (DownBlk->succ_size() == 1) ? (*DownBlk->succ_begin()) : nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001178 } // walk down the postDomTree
1179
Vincent Lejeune960a6222013-07-19 21:45:06 +00001180 return Num;
1181}
Tom Stellard75aadc22012-12-11 21:25:42 +00001182
Vincent Lejeune960a6222013-07-19 21:45:06 +00001183void AMDGPUCFGStructurizer::showImproveSimpleJumpintoIf(
1184 MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB,
1185 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail) {
1186 dbgs() << "head = BB" << HeadMBB->getNumber()
1187 << " size = " << HeadMBB->size();
1188 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001189 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001190 HeadMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001191 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001192 }
1193
Vincent Lejeune960a6222013-07-19 21:45:06 +00001194 if (TrueMBB) {
1195 dbgs() << ", true = BB" << TrueMBB->getNumber() << " size = "
1196 << TrueMBB->size() << " numPred = " << TrueMBB->pred_size();
1197 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001198 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001199 TrueMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001200 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001201 }
1202 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001203 if (FalseMBB) {
1204 dbgs() << ", false = BB" << FalseMBB->getNumber() << " size = "
1205 << FalseMBB->size() << " numPred = " << FalseMBB->pred_size();
1206 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001207 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001208 FalseMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001209 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001210 }
1211 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001212 if (LandMBB) {
1213 dbgs() << ", land = BB" << LandMBB->getNumber() << " size = "
1214 << LandMBB->size() << " numPred = " << LandMBB->pred_size();
1215 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001216 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001217 LandMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001218 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001219 }
1220 }
1221
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001222 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001223}
Tom Stellard75aadc22012-12-11 21:25:42 +00001224
Vincent Lejeune960a6222013-07-19 21:45:06 +00001225int AMDGPUCFGStructurizer::improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
1226 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
1227 MachineBasicBlock **LandMBBPtr) {
1228 bool MigrateTrue = false;
1229 bool MigrateFalse = false;
Tom Stellard75aadc22012-12-11 21:25:42 +00001230
Vincent Lejeune960a6222013-07-19 21:45:06 +00001231 MachineBasicBlock *LandBlk = *LandMBBPtr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001232
Vincent Lejeune960a6222013-07-19 21:45:06 +00001233 assert((!TrueMBB || TrueMBB->succ_size() <= 1)
1234 && (!FalseMBB || FalseMBB->succ_size() <= 1));
Tom Stellard75aadc22012-12-11 21:25:42 +00001235
Vincent Lejeune960a6222013-07-19 21:45:06 +00001236 if (TrueMBB == FalseMBB)
Tom Stellard75aadc22012-12-11 21:25:42 +00001237 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001238
Vincent Lejeune960a6222013-07-19 21:45:06 +00001239 MigrateTrue = needMigrateBlock(TrueMBB);
1240 MigrateFalse = needMigrateBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001241
Vincent Lejeune960a6222013-07-19 21:45:06 +00001242 if (!MigrateTrue && !MigrateFalse)
Tom Stellard75aadc22012-12-11 21:25:42 +00001243 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001244
1245 // If we need to migrate either trueBlk and falseBlk, migrate the rest that
1246 // have more than one predecessors. without doing this, its predecessor
1247 // rather than headBlk will have undefined value in initReg.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001248 if (!MigrateTrue && TrueMBB && TrueMBB->pred_size() > 1)
1249 MigrateTrue = true;
1250 if (!MigrateFalse && FalseMBB && FalseMBB->pred_size() > 1)
1251 MigrateFalse = true;
Tom Stellard75aadc22012-12-11 21:25:42 +00001252
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001253 DEBUG(
1254 dbgs() << "before improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001255 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001256 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001257
1258 // org: headBlk => if () {trueBlk} else {falseBlk} => landBlk
1259 //
1260 // new: headBlk => if () {initReg = 1; org trueBlk branch} else
1261 // {initReg = 0; org falseBlk branch }
1262 // => landBlk => if (initReg) {org trueBlk} else {org falseBlk}
1263 // => org landBlk
1264 // if landBlk->pred_size() > 2, put the about if-else inside
1265 // if (initReg !=2) {...}
1266 //
1267 // add initReg = initVal to headBlk
1268
1269 const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32);
Tom Stellardb34186a2013-10-16 17:06:02 +00001270 if (!MigrateTrue || !MigrateFalse) {
1271 // XXX: We have an opportunity here to optimize the "branch into if" case
1272 // here. Branch into if looks like this:
1273 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001274 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001275 // diamond_head branch_from
1276 // / \ |
1277 // diamond_false diamond_true
1278 // \ /
1279 // done
1280 //
1281 // The diamond_head block begins the "if" and the diamond_true block
1282 // is the block being "branched into".
1283 //
1284 // If MigrateTrue is true, then TrueBB is the block being "branched into"
1285 // and if MigrateFalse is true, then FalseBB is the block being
1286 // "branched into"
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001287 //
Tom Stellardb34186a2013-10-16 17:06:02 +00001288 // Here is the pseudo code for how I think the optimization should work:
1289 // 1. Insert MOV GPR0, 0 before the branch instruction in diamond_head.
1290 // 2. Insert MOV GPR0, 1 before the branch instruction in branch_from.
1291 // 3. Move the branch instruction from diamond_head into its own basic
1292 // block (new_block).
1293 // 4. Add an unconditional branch from diamond_head to new_block
1294 // 5. Replace the branch instruction in branch_from with an unconditional
1295 // branch to new_block. If branch_from has multiple predecessors, then
1296 // we need to replace the True/False block in the branch
1297 // instruction instead of replacing it.
1298 // 6. Change the condition of the branch instruction in new_block from
1299 // COND to (COND || GPR0)
1300 //
1301 // In order insert these MOV instruction, we will need to use the
1302 // RegisterScavenger. Usually liveness stops being tracked during
1303 // the late machine optimization passes, however if we implement
1304 // bool TargetRegisterInfo::requiresRegisterScavenging(
1305 // const MachineFunction &MF)
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001306 // and have it return true, liveness will be tracked correctly
Tom Stellardb34186a2013-10-16 17:06:02 +00001307 // by generic optimization passes. We will also need to make sure that
1308 // all of our target-specific passes that run after regalloc and before
1309 // the CFGStructurizer track liveness and we will need to modify this pass
1310 // to correctly track liveness.
1311 //
1312 // After the above changes, the new CFG should look like this:
1313 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001314 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001315 // diamond_head branch_from
1316 // \ /
1317 // new_block
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001318 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001319 // diamond_false diamond_true
1320 // \ /
1321 // done
1322 //
1323 // Without this optimization, we are forced to duplicate the diamond_true
1324 // block and we will end up with a CFG like this:
1325 //
1326 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001327 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001328 // diamond_head branch_from
1329 // / \ |
1330 // diamond_false diamond_true diamond_true (duplicate)
1331 // \ / |
1332 // done --------------------|
1333 //
1334 // Duplicating diamond_true can be very costly especially if it has a
1335 // lot of instructions.
1336 return 0;
1337 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001338
Vincent Lejeune960a6222013-07-19 21:45:06 +00001339 int NumNewBlk = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001340
Vincent Lejeune960a6222013-07-19 21:45:06 +00001341 bool LandBlkHasOtherPred = (LandBlk->pred_size() > 2);
Tom Stellard75aadc22012-12-11 21:25:42 +00001342
1343 //insert AMDGPU::ENDIF to avoid special case "input landBlk == NULL"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001344 MachineBasicBlock::iterator I = insertInstrBefore(LandBlk, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001345
Vincent Lejeune960a6222013-07-19 21:45:06 +00001346 if (LandBlkHasOtherPred) {
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001347 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001348 unsigned CmpResReg =
1349 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001350 report_fatal_error("Extra compare instruction needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001351 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET,
1352 CmpResReg, DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001353 }
1354
Tom Stellard69f86d12013-10-16 17:05:56 +00001355 // XXX: We are running this after RA, so creating virtual registers will
1356 // cause an assertion failure in the PostRA scheduling pass.
1357 unsigned InitReg =
1358 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001359 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET, InitReg,
1360 DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001361
Vincent Lejeune960a6222013-07-19 21:45:06 +00001362 if (MigrateTrue) {
1363 migrateInstruction(TrueMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001364 // need to uncondionally insert the assignment to ensure a path from its
1365 // predecessor rather than headBlk has valid value in initReg if
1366 // (initVal != 1).
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001367 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001368 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001369 insertInstrBefore(I, AMDGPU::ELSE);
Tom Stellard75aadc22012-12-11 21:25:42 +00001370
Vincent Lejeune960a6222013-07-19 21:45:06 +00001371 if (MigrateFalse) {
1372 migrateInstruction(FalseMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001373 // need to uncondionally insert the assignment to ensure a path from its
1374 // predecessor rather than headBlk has valid value in initReg if
1375 // (initVal != 0)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001376 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001377 }
1378
Vincent Lejeune960a6222013-07-19 21:45:06 +00001379 if (LandBlkHasOtherPred) {
Tom Stellard75aadc22012-12-11 21:25:42 +00001380 // add endif
Vincent Lejeune960a6222013-07-19 21:45:06 +00001381 insertInstrBefore(I, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001382
1383 // put initReg = 2 to other predecessors of landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001384 for (MachineBasicBlock::pred_iterator PI = LandBlk->pred_begin(),
1385 PE = LandBlk->pred_end(); PI != PE; ++PI) {
1386 MachineBasicBlock *MBB = *PI;
1387 if (MBB != TrueMBB && MBB != FalseMBB)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001388 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001389 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001390 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001391 DEBUG(
1392 dbgs() << "result from improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001393 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001394 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001395
1396 // update landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001397 *LandMBBPtr = LandBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001398
Vincent Lejeune960a6222013-07-19 21:45:06 +00001399 return NumNewBlk;
1400}
Tom Stellard75aadc22012-12-11 21:25:42 +00001401
Vincent Lejeune960a6222013-07-19 21:45:06 +00001402void AMDGPUCFGStructurizer::mergeSerialBlock(MachineBasicBlock *DstMBB,
1403 MachineBasicBlock *SrcMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001404 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001405 dbgs() << "serialPattern BB" << DstMBB->getNumber()
1406 << " <= BB" << SrcMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001407 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001408 DstMBB->splice(DstMBB->end(), SrcMBB, SrcMBB->begin(), SrcMBB->end());
Tom Stellard75aadc22012-12-11 21:25:42 +00001409
Cong Houc1069892015-12-13 09:26:17 +00001410 DstMBB->removeSuccessor(SrcMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001411 cloneSuccessorList(DstMBB, SrcMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001412
Vincent Lejeune960a6222013-07-19 21:45:06 +00001413 removeSuccessor(SrcMBB);
1414 MLI->removeBlock(SrcMBB);
1415 retireBlock(SrcMBB);
1416}
Tom Stellard75aadc22012-12-11 21:25:42 +00001417
Vincent Lejeune960a6222013-07-19 21:45:06 +00001418void AMDGPUCFGStructurizer::mergeIfthenelseBlock(MachineInstr *BranchMI,
1419 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
1420 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB) {
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001421 assert (TrueMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001422 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001423 dbgs() << "ifPattern BB" << MBB->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001424 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001425 if (TrueMBB) {
1426 dbgs() << "BB" << TrueMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001427 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001428 dbgs() << " } else ";
1429 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001430 if (FalseMBB) {
1431 dbgs() << "BB" << FalseMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001432 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001433 dbgs() << " }\n ";
1434 dbgs() << "landBlock: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001435 if (!LandMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001436 dbgs() << "NULL";
Tom Stellard75aadc22012-12-11 21:25:42 +00001437 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001438 dbgs() << "BB" << LandMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001439 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001440 dbgs() << "\n";
1441 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001442
Vincent Lejeune960a6222013-07-19 21:45:06 +00001443 int OldOpcode = BranchMI->getOpcode();
1444 DebugLoc BranchDL = BranchMI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001445
1446// transform to
1447// if cond
1448// trueBlk
1449// else
1450// falseBlk
1451// endif
1452// landBlk
1453
Vincent Lejeune960a6222013-07-19 21:45:06 +00001454 MachineBasicBlock::iterator I = BranchMI;
1455 insertCondBranchBefore(I, getBranchNzeroOpcode(OldOpcode),
1456 BranchDL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001457
Vincent Lejeune960a6222013-07-19 21:45:06 +00001458 if (TrueMBB) {
1459 MBB->splice(I, TrueMBB, TrueMBB->begin(), TrueMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001460 MBB->removeSuccessor(TrueMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001461 if (LandMBB && TrueMBB->succ_size()!=0)
Cong Houc1069892015-12-13 09:26:17 +00001462 TrueMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001463 retireBlock(TrueMBB);
1464 MLI->removeBlock(TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001465 }
1466
Vincent Lejeune960a6222013-07-19 21:45:06 +00001467 if (FalseMBB) {
1468 insertInstrBefore(I, AMDGPU::ELSE);
1469 MBB->splice(I, FalseMBB, FalseMBB->begin(),
1470 FalseMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001471 MBB->removeSuccessor(FalseMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001472 if (LandMBB && FalseMBB->succ_size() != 0)
Cong Houc1069892015-12-13 09:26:17 +00001473 FalseMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001474 retireBlock(FalseMBB);
1475 MLI->removeBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001476 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001477 insertInstrBefore(I, AMDGPU::ENDIF);
1478
1479 BranchMI->eraseFromParent();
1480
1481 if (LandMBB && TrueMBB && FalseMBB)
1482 MBB->addSuccessor(LandMBB);
1483
1484}
1485
1486void AMDGPUCFGStructurizer::mergeLooplandBlock(MachineBasicBlock *DstBlk,
1487 MachineBasicBlock *LandMBB) {
1488 DEBUG(dbgs() << "loopPattern header = BB" << DstBlk->getNumber()
1489 << " land = BB" << LandMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001490
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001491 insertInstrBefore(DstBlk, AMDGPU::WHILELOOP, DebugLoc());
1492 insertInstrEnd(DstBlk, AMDGPU::ENDLOOP, DebugLoc());
Cong Houd97c1002015-12-01 05:29:22 +00001493 DstBlk->replaceSuccessor(DstBlk, LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001494}
Tom Stellard75aadc22012-12-11 21:25:42 +00001495
Tom Stellard75aadc22012-12-11 21:25:42 +00001496
Vincent Lejeune960a6222013-07-19 21:45:06 +00001497void AMDGPUCFGStructurizer::mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
1498 MachineBasicBlock *LandMBB) {
1499 DEBUG(dbgs() << "loopbreakPattern exiting = BB" << ExitingMBB->getNumber()
1500 << " land = BB" << LandMBB->getNumber() << "\n";);
1501 MachineInstr *BranchMI = getLoopendBlockBranchInstr(ExitingMBB);
1502 assert(BranchMI && isCondBranch(BranchMI));
1503 DebugLoc DL = BranchMI->getDebugLoc();
1504 MachineBasicBlock *TrueBranch = getTrueBranch(BranchMI);
1505 MachineBasicBlock::iterator I = BranchMI;
1506 if (TrueBranch != LandMBB)
Hans Wennborg0dd9ed12016-08-13 01:12:49 +00001507 reversePredicateSetter(I, *I->getParent());
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001508 insertCondBranchBefore(ExitingMBB, I, AMDGPU::IF_PREDICATE_SET, AMDGPU::PREDICATE_BIT, DL);
1509 insertInstrBefore(I, AMDGPU::BREAK);
1510 insertInstrBefore(I, AMDGPU::ENDIF);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001511 //now branchInst can be erase safely
1512 BranchMI->eraseFromParent();
1513 //now take care of successors, retire blocks
Cong Houc1069892015-12-13 09:26:17 +00001514 ExitingMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001515}
Tom Stellard75aadc22012-12-11 21:25:42 +00001516
Vincent Lejeune960a6222013-07-19 21:45:06 +00001517void AMDGPUCFGStructurizer::settleLoopcontBlock(MachineBasicBlock *ContingMBB,
1518 MachineBasicBlock *ContMBB) {
1519 DEBUG(dbgs() << "settleLoopcontBlock conting = BB"
1520 << ContingMBB->getNumber()
1521 << ", cont = BB" << ContMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001522
Vincent Lejeune960a6222013-07-19 21:45:06 +00001523 MachineInstr *MI = getLoopendBlockBranchInstr(ContingMBB);
1524 if (MI) {
1525 assert(isCondBranch(MI));
1526 MachineBasicBlock::iterator I = MI;
1527 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
1528 int OldOpcode = MI->getOpcode();
1529 DebugLoc DL = MI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001530
Vincent Lejeune960a6222013-07-19 21:45:06 +00001531 bool UseContinueLogical = ((&*ContingMBB->rbegin()) == MI);
1532
David Blaikie4eaa79c2015-03-23 20:56:44 +00001533 if (!UseContinueLogical) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001534 int BranchOpcode =
1535 TrueBranch == ContMBB ? getBranchNzeroOpcode(OldOpcode) :
1536 getBranchZeroOpcode(OldOpcode);
1537 insertCondBranchBefore(I, BranchOpcode, DL);
1538 // insertEnd to ensure phi-moves, if exist, go before the continue-instr.
1539 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE, DL);
1540 insertInstrEnd(ContingMBB, AMDGPU::ENDIF, DL);
1541 } else {
1542 int BranchOpcode =
1543 TrueBranch == ContMBB ? getContinueNzeroOpcode(OldOpcode) :
1544 getContinueZeroOpcode(OldOpcode);
1545 insertCondBranchBefore(I, BranchOpcode, DL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001546 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001547
1548 MI->eraseFromParent();
1549 } else {
1550 // if we've arrived here then we've already erased the branch instruction
1551 // travel back up the basic block to see the last reference of our debug
1552 // location we've just inserted that reference here so it should be
1553 // representative insertEnd to ensure phi-moves, if exist, go before the
1554 // continue-instr.
1555 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE,
1556 getLastDebugLocInBB(ContingMBB));
Tom Stellard75aadc22012-12-11 21:25:42 +00001557 }
1558}
1559
Vincent Lejeune960a6222013-07-19 21:45:06 +00001560int AMDGPUCFGStructurizer::cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
1561 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB) {
1562 int Cloned = 0;
1563 assert(PreMBB->isSuccessor(SrcMBB));
1564 while (SrcMBB && SrcMBB != DstMBB) {
1565 assert(SrcMBB->succ_size() == 1);
1566 if (SrcMBB->pred_size() > 1) {
1567 SrcMBB = cloneBlockForPredecessor(SrcMBB, PreMBB);
1568 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001569 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001570
Vincent Lejeune960a6222013-07-19 21:45:06 +00001571 PreMBB = SrcMBB;
1572 SrcMBB = *SrcMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001573 }
1574
Vincent Lejeune960a6222013-07-19 21:45:06 +00001575 return Cloned;
1576}
Tom Stellard75aadc22012-12-11 21:25:42 +00001577
Vincent Lejeune960a6222013-07-19 21:45:06 +00001578MachineBasicBlock *
1579AMDGPUCFGStructurizer::cloneBlockForPredecessor(MachineBasicBlock *MBB,
1580 MachineBasicBlock *PredMBB) {
1581 assert(PredMBB->isSuccessor(MBB) &&
Tom Stellard75aadc22012-12-11 21:25:42 +00001582 "succBlk is not a prececessor of curBlk");
1583
Vincent Lejeune960a6222013-07-19 21:45:06 +00001584 MachineBasicBlock *CloneMBB = clone(MBB); //clone instructions
1585 replaceInstrUseOfBlockWith(PredMBB, MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001586 //srcBlk, oldBlk, newBlk
1587
Cong Houd97c1002015-12-01 05:29:22 +00001588 PredMBB->replaceSuccessor(MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001589
1590 // add all successor to cloneBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001591 cloneSuccessorList(CloneMBB, MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001592
Vincent Lejeune960a6222013-07-19 21:45:06 +00001593 numClonedInstr += MBB->size();
Tom Stellard75aadc22012-12-11 21:25:42 +00001594
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001595 DEBUG(
1596 dbgs() << "Cloned block: " << "BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001597 << MBB->getNumber() << "size " << MBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001598 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001599
Vincent Lejeune960a6222013-07-19 21:45:06 +00001600 SHOWNEWBLK(CloneMBB, "result of Cloned block: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001601
Vincent Lejeune960a6222013-07-19 21:45:06 +00001602 return CloneMBB;
1603}
Tom Stellard75aadc22012-12-11 21:25:42 +00001604
Vincent Lejeune960a6222013-07-19 21:45:06 +00001605void AMDGPUCFGStructurizer::migrateInstruction(MachineBasicBlock *SrcMBB,
1606 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I) {
1607 MachineBasicBlock::iterator SpliceEnd;
Tom Stellard75aadc22012-12-11 21:25:42 +00001608 //look for the input branchinstr, not the AMDGPU branchinstr
Vincent Lejeune960a6222013-07-19 21:45:06 +00001609 MachineInstr *BranchMI = getNormalBlockBranchInstr(SrcMBB);
1610 if (!BranchMI) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001611 DEBUG(
1612 dbgs() << "migrateInstruction don't see branch instr\n" ;
1613 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001614 SpliceEnd = SrcMBB->end();
Tom Stellard75aadc22012-12-11 21:25:42 +00001615 } else {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001616 DEBUG(dbgs() << "migrateInstruction see branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001617 SpliceEnd = BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001618 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001619 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001620 dbgs() << "migrateInstruction before splice dstSize = " << DstMBB->size()
1621 << "srcSize = " << SrcMBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001622 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001623
1624 //splice insert before insertPos
Vincent Lejeune960a6222013-07-19 21:45:06 +00001625 DstMBB->splice(I, SrcMBB, SrcMBB->begin(), SpliceEnd);
Tom Stellard75aadc22012-12-11 21:25:42 +00001626
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001627 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001628 dbgs() << "migrateInstruction after splice dstSize = " << DstMBB->size()
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001629 << "srcSize = " << SrcMBB->size() << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001630 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001631}
Tom Stellard75aadc22012-12-11 21:25:42 +00001632
Vincent Lejeune960a6222013-07-19 21:45:06 +00001633MachineBasicBlock *
1634AMDGPUCFGStructurizer::normalizeInfiniteLoopExit(MachineLoop* LoopRep) {
1635 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1636 MachineBasicBlock *LoopLatch = LoopRep->getLoopLatch();
Tom Stellard75aadc22012-12-11 21:25:42 +00001637
Vincent Lejeune960a6222013-07-19 21:45:06 +00001638 if (!LoopHeader || !LoopLatch)
Craig Topper062a2ba2014-04-25 05:30:21 +00001639 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001640 MachineInstr *BranchMI = getLoopendBlockBranchInstr(LoopLatch);
1641 // Is LoopRep an infinite loop ?
1642 if (!BranchMI || !isUncondBranch(BranchMI))
Craig Topper062a2ba2014-04-25 05:30:21 +00001643 return nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001644
Vincent Lejeune960a6222013-07-19 21:45:06 +00001645 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1646 FuncRep->push_back(DummyExitBlk); //insert to function
1647 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock to normalize infiniteLoop: ");
1648 DEBUG(dbgs() << "Old branch instr: " << *BranchMI << "\n";);
Tom Stellard1d46fb22015-07-16 15:38:29 +00001649 LLVMContext &Ctx = LoopHeader->getParent()->getFunction()->getContext();
1650 Ctx.emitError("Extra register needed to handle CFG");
1651 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001652}
Tom Stellard75aadc22012-12-11 21:25:42 +00001653
Vincent Lejeune960a6222013-07-19 21:45:06 +00001654void AMDGPUCFGStructurizer::removeUnconditionalBranch(MachineBasicBlock *MBB) {
1655 MachineInstr *BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001656
1657 // I saw two unconditional branch in one basic block in example
1658 // test_fc_do_while_or.c need to fix the upstream on this to remove the loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001659 while ((BranchMI = getLoopendBlockBranchInstr(MBB))
1660 && isUncondBranch(BranchMI)) {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001661 DEBUG(dbgs() << "Removing uncond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001662 BranchMI->eraseFromParent();
Tom Stellard75aadc22012-12-11 21:25:42 +00001663 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001664}
Tom Stellard75aadc22012-12-11 21:25:42 +00001665
Vincent Lejeune960a6222013-07-19 21:45:06 +00001666void AMDGPUCFGStructurizer::removeRedundantConditionalBranch(
1667 MachineBasicBlock *MBB) {
1668 if (MBB->succ_size() != 2)
1669 return;
1670 MachineBasicBlock *MBB1 = *MBB->succ_begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001671 MachineBasicBlock *MBB2 = *std::next(MBB->succ_begin());
Vincent Lejeune960a6222013-07-19 21:45:06 +00001672 if (MBB1 != MBB2)
1673 return;
Tom Stellard75aadc22012-12-11 21:25:42 +00001674
Vincent Lejeune960a6222013-07-19 21:45:06 +00001675 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
1676 assert(BranchMI && isCondBranch(BranchMI));
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001677 DEBUG(dbgs() << "Removing unneeded cond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001678 BranchMI->eraseFromParent();
1679 SHOWNEWBLK(MBB1, "Removing redundant successor");
Cong Houc1069892015-12-13 09:26:17 +00001680 MBB->removeSuccessor(MBB1, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001681}
Tom Stellard75aadc22012-12-11 21:25:42 +00001682
Vincent Lejeune960a6222013-07-19 21:45:06 +00001683void AMDGPUCFGStructurizer::addDummyExitBlock(
1684 SmallVectorImpl<MachineBasicBlock*> &RetMBB) {
1685 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1686 FuncRep->push_back(DummyExitBlk); //insert to function
1687 insertInstrEnd(DummyExitBlk, AMDGPU::RETURN);
Tom Stellard75aadc22012-12-11 21:25:42 +00001688
Vincent Lejeune960a6222013-07-19 21:45:06 +00001689 for (SmallVectorImpl<MachineBasicBlock *>::iterator It = RetMBB.begin(),
1690 E = RetMBB.end(); It != E; ++It) {
1691 MachineBasicBlock *MBB = *It;
1692 MachineInstr *MI = getReturnInstr(MBB);
1693 if (MI)
1694 MI->eraseFromParent();
1695 MBB->addSuccessor(DummyExitBlk);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001696 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001697 dbgs() << "Add dummyExitBlock to BB" << MBB->getNumber()
Tom Stellard75aadc22012-12-11 21:25:42 +00001698 << " successors\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001699 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001700 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001701 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001702}
1703
Vincent Lejeune960a6222013-07-19 21:45:06 +00001704void AMDGPUCFGStructurizer::removeSuccessor(MachineBasicBlock *MBB) {
1705 while (MBB->succ_size())
1706 MBB->removeSuccessor(*MBB->succ_begin());
Tom Stellard75aadc22012-12-11 21:25:42 +00001707}
1708
Vincent Lejeune960a6222013-07-19 21:45:06 +00001709void AMDGPUCFGStructurizer::recordSccnum(MachineBasicBlock *MBB,
1710 int SccNum) {
1711 BlockInformation *&srcBlkInfo = BlockInfoMap[MBB];
1712 if (!srcBlkInfo)
1713 srcBlkInfo = new BlockInformation();
1714 srcBlkInfo->SccNum = SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +00001715}
1716
Vincent Lejeune960a6222013-07-19 21:45:06 +00001717void AMDGPUCFGStructurizer::retireBlock(MachineBasicBlock *MBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001718 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001719 dbgs() << "Retiring BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001720 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001721
Vincent Lejeune960a6222013-07-19 21:45:06 +00001722 BlockInformation *&SrcBlkInfo = BlockInfoMap[MBB];
Tom Stellard75aadc22012-12-11 21:25:42 +00001723
Vincent Lejeune960a6222013-07-19 21:45:06 +00001724 if (!SrcBlkInfo)
1725 SrcBlkInfo = new BlockInformation();
Tom Stellard75aadc22012-12-11 21:25:42 +00001726
Vincent Lejeune960a6222013-07-19 21:45:06 +00001727 SrcBlkInfo->IsRetired = true;
1728 assert(MBB->succ_size() == 0 && MBB->pred_size() == 0
Tom Stellard75aadc22012-12-11 21:25:42 +00001729 && "can't retire block yet");
1730}
1731
Vincent Lejeune960a6222013-07-19 21:45:06 +00001732char AMDGPUCFGStructurizer::ID = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001733
Benjamin Kramer635e3682013-05-23 15:43:05 +00001734} // end anonymous namespace
Tom Stellard75aadc22012-12-11 21:25:42 +00001735
Tom Stellard75aadc22012-12-11 21:25:42 +00001736
Tom Stellardf2ba9722013-12-11 17:51:47 +00001737INITIALIZE_PASS_BEGIN(AMDGPUCFGStructurizer, "amdgpustructurizer",
1738 "AMDGPU CFG Structurizer", false, false)
1739INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1740INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
1741INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
1742INITIALIZE_PASS_END(AMDGPUCFGStructurizer, "amdgpustructurizer",
1743 "AMDGPU CFG Structurizer", false, false)
1744
1745FunctionPass *llvm::createAMDGPUCFGStructurizerPass() {
1746 return new AMDGPUCFGStructurizer();
Tom Stellard75aadc22012-12-11 21:25:42 +00001747}