blob: addcf4e50139824e04a7f5681fb4314940ddfb9f [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"
Eric Christopherd9134482014-08-04 21:25:23 +000012#include "AMDGPUSubtarget.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000013#include "R600InstrInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000014#include "R600RegisterInfo.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"
Eugene Zelenko66203762017-01-21 00:53:49 +000017#include "llvm/ADT/SmallPtrSet.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000020#include "llvm/ADT/StringRef.h"
21#include "llvm/CodeGen/MachineBasicBlock.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000022#include "llvm/CodeGen/MachineDominators.h"
23#include "llvm/CodeGen/MachineFunction.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000024#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000025#include "llvm/CodeGen/MachineInstr.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000028#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000029#include "llvm/CodeGen/MachinePostDominators.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000031#include "llvm/CodeGen/MachineValueType.h"
32#include "llvm/IR/DebugLoc.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/Pass.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000035#include "llvm/Support/Debug.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000036#include "llvm/Support/ErrorHandling.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000037#include "llvm/Support/raw_ostream.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000038#include <cassert>
39#include <cstddef>
Benjamin Kramer799003b2015-03-23 19:32:43 +000040#include <deque>
Eugene Zelenko66203762017-01-21 00:53:49 +000041#include <iterator>
42#include <map>
43#include <utility>
44#include <vector>
Tom Stellard75aadc22012-12-11 21:25:42 +000045
46using namespace llvm;
47
Chandler Carruth84e68b22014-04-22 02:41:26 +000048#define DEBUG_TYPE "structcfg"
49
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000050#define DEFAULT_VEC_SLOTS 8
51
Tom Stellard75aadc22012-12-11 21:25:42 +000052// TODO: move-begin.
53
54//===----------------------------------------------------------------------===//
55//
56// Statistics for CFGStructurizer.
57//
58//===----------------------------------------------------------------------===//
59
60STATISTIC(numSerialPatternMatch, "CFGStructurizer number of serial pattern "
61 "matched");
62STATISTIC(numIfPatternMatch, "CFGStructurizer number of if pattern "
63 "matched");
Tom Stellard75aadc22012-12-11 21:25:42 +000064STATISTIC(numClonedBlock, "CFGStructurizer cloned blocks");
65STATISTIC(numClonedInstr, "CFGStructurizer cloned instructions");
66
Tom Stellardf2ba9722013-12-11 17:51:47 +000067namespace llvm {
Eugene Zelenko66203762017-01-21 00:53:49 +000068
Tom Stellardf2ba9722013-12-11 17:51:47 +000069 void initializeAMDGPUCFGStructurizerPass(PassRegistry&);
Eugene Zelenko66203762017-01-21 00:53:49 +000070
71} // end namespace llvm
72
73namespace {
Tom Stellardf2ba9722013-12-11 17:51:47 +000074
Tom Stellard75aadc22012-12-11 21:25:42 +000075//===----------------------------------------------------------------------===//
76//
77// Miscellaneous utility for CFGStructurizer.
78//
79//===----------------------------------------------------------------------===//
Eugene Zelenko66203762017-01-21 00:53:49 +000080
Tom Stellard75aadc22012-12-11 21:25:42 +000081#define SHOWNEWINSTR(i) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000082 DEBUG(dbgs() << "New instr: " << *i << "\n");
Tom Stellard75aadc22012-12-11 21:25:42 +000083
84#define SHOWNEWBLK(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000085DEBUG( \
86 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
87 dbgs() << "\n"; \
88);
Tom Stellard75aadc22012-12-11 21:25:42 +000089
90#define SHOWBLK_DETAIL(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000091DEBUG( \
Tom Stellard75aadc22012-12-11 21:25:42 +000092 if (b) { \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000093 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
94 b->print(dbgs()); \
95 dbgs() << "\n"; \
Tom Stellard75aadc22012-12-11 21:25:42 +000096 } \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000097);
Tom Stellard75aadc22012-12-11 21:25:42 +000098
99#define INVALIDSCCNUM -1
Tom Stellard75aadc22012-12-11 21:25:42 +0000100
101template<class NodeT>
Craig Topperb94011f2013-07-14 04:42:23 +0000102void ReverseVector(SmallVectorImpl<NodeT *> &Src) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000103 size_t sz = Src.size();
104 for (size_t i = 0; i < sz/2; ++i) {
105 NodeT *t = Src[i];
106 Src[i] = Src[sz - i - 1];
107 Src[sz - i - 1] = t;
108 }
109}
110
Tom Stellard75aadc22012-12-11 21:25:42 +0000111//===----------------------------------------------------------------------===//
112//
113// supporting data structure for CFGStructurizer
114//
115//===----------------------------------------------------------------------===//
116
Tom Stellard75aadc22012-12-11 21:25:42 +0000117class BlockInformation {
118public:
Eugene Zelenko66203762017-01-21 00:53:49 +0000119 bool IsRetired = false;
120 int SccNum = INVALIDSCCNUM;
Tom Stellard75aadc22012-12-11 21:25:42 +0000121
Eugene Zelenko66203762017-01-21 00:53:49 +0000122 BlockInformation() = default;
123};
Tom Stellard75aadc22012-12-11 21:25:42 +0000124
125//===----------------------------------------------------------------------===//
126//
127// CFGStructurizer
128//
129//===----------------------------------------------------------------------===//
130
Vincent Lejeune960a6222013-07-19 21:45:06 +0000131class AMDGPUCFGStructurizer : public MachineFunctionPass {
Tom Stellard75aadc22012-12-11 21:25:42 +0000132public:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000133 typedef SmallVector<MachineBasicBlock *, 32> MBBVector;
134 typedef std::map<MachineBasicBlock *, BlockInformation *> MBBInfoMap;
135 typedef std::map<MachineLoop *, MachineBasicBlock *> LoopLandInfoMap;
136
137 enum PathToKind {
Tom Stellard75aadc22012-12-11 21:25:42 +0000138 Not_SinglePath = 0,
139 SinglePath_InPath = 1,
140 SinglePath_NotInPath = 2
Vincent Lejeune960a6222013-07-19 21:45:06 +0000141 };
Tom Stellard75aadc22012-12-11 21:25:42 +0000142
Vincent Lejeune960a6222013-07-19 21:45:06 +0000143 static char ID;
Tom Stellard75aadc22012-12-11 21:25:42 +0000144
Eugene Zelenko66203762017-01-21 00:53:49 +0000145 AMDGPUCFGStructurizer() : MachineFunctionPass(ID) {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000146 initializeAMDGPUCFGStructurizerPass(*PassRegistry::getPassRegistry());
147 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000148
Mehdi Amini117296c2016-10-01 02:56:57 +0000149 StringRef getPassName() const override {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000150 return "AMDGPU Control Flow Graph structurizer Pass";
Vincent Lejeune960a6222013-07-19 21:45:06 +0000151 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000152
Craig Topper5656db42014-04-29 07:57:24 +0000153 void getAnalysisUsage(AnalysisUsage &AU) const override {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000154 AU.addRequired<MachineDominatorTree>();
155 AU.addRequired<MachinePostDominatorTree>();
156 AU.addRequired<MachineLoopInfo>();
Matthias Braun733fe362016-08-24 01:52:46 +0000157 MachineFunctionPass::getAnalysisUsage(AU);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000158 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000159
160 /// Perform the CFG structurization
Vincent Lejeune960a6222013-07-19 21:45:06 +0000161 bool run();
Tom Stellard75aadc22012-12-11 21:25:42 +0000162
163 /// Perform the CFG preparation
Vincent Lejeune960a6222013-07-19 21:45:06 +0000164 /// This step will remove every unconditionnal/dead jump instructions and make
165 /// sure all loops have an exit block
166 bool prepare();
Tom Stellard75aadc22012-12-11 21:25:42 +0000167
Craig Topper5656db42014-04-29 07:57:24 +0000168 bool runOnMachineFunction(MachineFunction &MF) override {
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000169 TII = MF.getSubtarget<R600Subtarget>().getInstrInfo();
Tom Stellardf2ba9722013-12-11 17:51:47 +0000170 TRI = &TII->getRegisterInfo();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000171 DEBUG(MF.dump(););
172 OrderedBlks.clear();
Jan Vesely7a9cca92015-03-13 17:32:46 +0000173 Visited.clear();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000174 FuncRep = &MF;
175 MLI = &getAnalysis<MachineLoopInfo>();
176 DEBUG(dbgs() << "LoopInfo:\n"; PrintLoopinfo(*MLI););
177 MDT = &getAnalysis<MachineDominatorTree>();
Eugene Zelenko66203762017-01-21 00:53:49 +0000178 DEBUG(MDT->print(dbgs(), (const Module*)nullptr););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000179 PDT = &getAnalysis<MachinePostDominatorTree>();
180 DEBUG(PDT->print(dbgs()););
181 prepare();
182 run();
183 DEBUG(MF.dump(););
184 return true;
185 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000186
Vincent Lejeune960a6222013-07-19 21:45:06 +0000187protected:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000188 MachineDominatorTree *MDT;
189 MachinePostDominatorTree *PDT;
190 MachineLoopInfo *MLI;
Eugene Zelenko66203762017-01-21 00:53:49 +0000191 const R600InstrInfo *TII = nullptr;
192 const R600RegisterInfo *TRI = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000193
Vincent Lejeune960a6222013-07-19 21:45:06 +0000194 // PRINT FUNCTIONS
195 /// Print the ordered Blocks.
196 void printOrderedBlocks() const {
197 size_t i = 0;
198 for (MBBVector::const_iterator iterBlk = OrderedBlks.begin(),
199 iterBlkEnd = OrderedBlks.end(); iterBlk != iterBlkEnd; ++iterBlk, ++i) {
200 dbgs() << "BB" << (*iterBlk)->getNumber();
201 dbgs() << "(" << getSCCNum(*iterBlk) << "," << (*iterBlk)->size() << ")";
202 if (i != 0 && i % 10 == 0) {
203 dbgs() << "\n";
204 } else {
205 dbgs() << " ";
206 }
207 }
208 }
Eugene Zelenko66203762017-01-21 00:53:49 +0000209
Vincent Lejeune960a6222013-07-19 21:45:06 +0000210 static void PrintLoopinfo(const MachineLoopInfo &LoopInfo) {
211 for (MachineLoop::iterator iter = LoopInfo.begin(),
212 iterEnd = LoopInfo.end(); iter != iterEnd; ++iter) {
213 (*iter)->print(dbgs(), 0);
214 }
215 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000216
Vincent Lejeune960a6222013-07-19 21:45:06 +0000217 // UTILITY FUNCTIONS
218 int getSCCNum(MachineBasicBlock *MBB) const;
219 MachineBasicBlock *getLoopLandInfo(MachineLoop *LoopRep) const;
220 bool hasBackEdge(MachineBasicBlock *MBB) const;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000221 bool isRetiredBlock(MachineBasicBlock *MBB) const;
222 bool isActiveLoophead(MachineBasicBlock *MBB) const;
223 PathToKind singlePathTo(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
224 bool AllowSideEntry = true) const;
225 int countActiveBlock(MBBVector::const_iterator It,
226 MBBVector::const_iterator E) const;
227 bool needMigrateBlock(MachineBasicBlock *MBB) const;
228
229 // Utility Functions
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000230 void reversePredicateSetter(MachineBasicBlock::iterator I,
231 MachineBasicBlock &MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000232 /// Compute the reversed DFS post order of Blocks
233 void orderBlocks(MachineFunction *MF);
234
Alp Tokercb402912014-01-24 17:20:08 +0000235 // Function originally from CFGStructTraits
Vincent Lejeune960a6222013-07-19 21:45:06 +0000236 void insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000237 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000238 MachineInstr *insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000239 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000240 MachineInstr *insertInstrBefore(MachineBasicBlock::iterator I, int NewOpcode);
241 void insertCondBranchBefore(MachineBasicBlock::iterator I, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000242 const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000243 void insertCondBranchBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000244 MachineBasicBlock::iterator I, int NewOpcode,
245 int RegNum, const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000246 static int getBranchNzeroOpcode(int OldOpcode);
247 static int getBranchZeroOpcode(int OldOpcode);
248 static int getContinueNzeroOpcode(int OldOpcode);
249 static int getContinueZeroOpcode(int OldOpcode);
250 static MachineBasicBlock *getTrueBranch(MachineInstr *MI);
251 static void setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB);
252 static MachineBasicBlock *getFalseBranch(MachineBasicBlock *MBB,
253 MachineInstr *MI);
254 static bool isCondBranch(MachineInstr *MI);
255 static bool isUncondBranch(MachineInstr *MI);
256 static DebugLoc getLastDebugLocInBB(MachineBasicBlock *MBB);
257 static MachineInstr *getNormalBlockBranchInstr(MachineBasicBlock *MBB);
258 /// The correct naming for this is getPossibleLoopendBlockBranchInstr.
259 ///
260 /// BB with backward-edge could have move instructions after the branch
261 /// instruction. Such move instruction "belong to" the loop backward-edge.
262 MachineInstr *getLoopendBlockBranchInstr(MachineBasicBlock *MBB);
263 static MachineInstr *getReturnInstr(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000264 static bool isReturnBlock(MachineBasicBlock *MBB);
265 static void cloneSuccessorList(MachineBasicBlock *DstMBB,
266 MachineBasicBlock *SrcMBB) ;
267 static MachineBasicBlock *clone(MachineBasicBlock *MBB);
268 /// MachineBasicBlock::ReplaceUsesOfBlockWith doesn't serve the purpose
269 /// because the AMDGPU instruction is not recognized as terminator fix this
270 /// and retire this routine
271 void replaceInstrUseOfBlockWith(MachineBasicBlock *SrcMBB,
272 MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk);
273 static void wrapup(MachineBasicBlock *MBB);
274
Vincent Lejeune960a6222013-07-19 21:45:06 +0000275 int patternMatch(MachineBasicBlock *MBB);
276 int patternMatchGroup(MachineBasicBlock *MBB);
277 int serialPatternMatch(MachineBasicBlock *MBB);
278 int ifPatternMatch(MachineBasicBlock *MBB);
279 int loopendPatternMatch();
280 int mergeLoop(MachineLoop *LoopRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000281
Vincent Lejeune960a6222013-07-19 21:45:06 +0000282 /// return true iff src1Blk->succ_size() == 0 && src1Blk and src2Blk are in
283 /// the same loop with LoopLandInfo without explicitly keeping track of
284 /// loopContBlks and loopBreakBlks, this is a method to get the information.
285 bool isSameloopDetachedContbreak(MachineBasicBlock *Src1MBB,
286 MachineBasicBlock *Src2MBB);
287 int handleJumpintoIf(MachineBasicBlock *HeadMBB,
288 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
289 int handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
290 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
291 int improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
292 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
293 MachineBasicBlock **LandMBBPtr);
294 void showImproveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
295 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
296 MachineBasicBlock *LandMBB, bool Detail = false);
297 int cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
298 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB);
299 void mergeSerialBlock(MachineBasicBlock *DstMBB,
300 MachineBasicBlock *SrcMBB);
301
302 void mergeIfthenelseBlock(MachineInstr *BranchMI,
303 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
304 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB);
305 void mergeLooplandBlock(MachineBasicBlock *DstMBB,
306 MachineBasicBlock *LandMBB);
307 void mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
308 MachineBasicBlock *LandMBB);
309 void settleLoopcontBlock(MachineBasicBlock *ContingMBB,
310 MachineBasicBlock *ContMBB);
311 /// normalizeInfiniteLoopExit change
312 /// B1:
313 /// uncond_br LoopHeader
314 ///
315 /// to
316 /// B1:
317 /// cond_br 1 LoopHeader dummyExit
318 /// and return the newly added dummy exit block
319 MachineBasicBlock *normalizeInfiniteLoopExit(MachineLoop *LoopRep);
320 void removeUnconditionalBranch(MachineBasicBlock *MBB);
321 /// Remove duplicate branches instructions in a block.
322 /// For instance
323 /// B0:
324 /// cond_br X B1 B2
325 /// cond_br X B1 B2
326 /// is transformed to
327 /// B0:
328 /// cond_br X B1 B2
329 void removeRedundantConditionalBranch(MachineBasicBlock *MBB);
330 void addDummyExitBlock(SmallVectorImpl<MachineBasicBlock *> &RetMBB);
331 void removeSuccessor(MachineBasicBlock *MBB);
332 MachineBasicBlock *cloneBlockForPredecessor(MachineBasicBlock *MBB,
333 MachineBasicBlock *PredMBB);
334 void migrateInstruction(MachineBasicBlock *SrcMBB,
335 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I);
336 void recordSccnum(MachineBasicBlock *MBB, int SCCNum);
337 void retireBlock(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000338
Vincent Lejeune960a6222013-07-19 21:45:06 +0000339private:
340 MBBInfoMap BlockInfoMap;
341 LoopLandInfoMap LLInfoMap;
342 std::map<MachineLoop *, bool> Visited;
343 MachineFunction *FuncRep;
344 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> OrderedBlks;
345};
346
Eugene Zelenko66203762017-01-21 00:53:49 +0000347char AMDGPUCFGStructurizer::ID = 0;
348
349} // end anonymous namespace
350
Vincent Lejeune960a6222013-07-19 21:45:06 +0000351int AMDGPUCFGStructurizer::getSCCNum(MachineBasicBlock *MBB) const {
352 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
353 if (It == BlockInfoMap.end())
354 return INVALIDSCCNUM;
355 return (*It).second->SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +0000356}
357
Vincent Lejeune960a6222013-07-19 21:45:06 +0000358MachineBasicBlock *AMDGPUCFGStructurizer::getLoopLandInfo(MachineLoop *LoopRep)
359 const {
360 LoopLandInfoMap::const_iterator It = LLInfoMap.find(LoopRep);
361 if (It == LLInfoMap.end())
Craig Topper062a2ba2014-04-25 05:30:21 +0000362 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000363 return (*It).second;
364}
365
366bool AMDGPUCFGStructurizer::hasBackEdge(MachineBasicBlock *MBB) const {
367 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
368 if (!LoopRep)
369 return false;
370 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
371 return MBB->isSuccessor(LoopHeader);
372}
373
Vincent Lejeune960a6222013-07-19 21:45:06 +0000374bool AMDGPUCFGStructurizer::isRetiredBlock(MachineBasicBlock *MBB) const {
375 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
376 if (It == BlockInfoMap.end())
377 return false;
378 return (*It).second->IsRetired;
379}
380
381bool AMDGPUCFGStructurizer::isActiveLoophead(MachineBasicBlock *MBB) const {
382 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
383 while (LoopRep && LoopRep->getHeader() == MBB) {
384 MachineBasicBlock *LoopLand = getLoopLandInfo(LoopRep);
385 if(!LoopLand)
386 return true;
387 if (!isRetiredBlock(LoopLand))
388 return true;
389 LoopRep = LoopRep->getParentLoop();
390 }
391 return false;
392}
Eugene Zelenko66203762017-01-21 00:53:49 +0000393
Vincent Lejeune960a6222013-07-19 21:45:06 +0000394AMDGPUCFGStructurizer::PathToKind AMDGPUCFGStructurizer::singlePathTo(
395 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
396 bool AllowSideEntry) const {
397 assert(DstMBB);
398 if (SrcMBB == DstMBB)
399 return SinglePath_InPath;
400 while (SrcMBB && SrcMBB->succ_size() == 1) {
401 SrcMBB = *SrcMBB->succ_begin();
402 if (SrcMBB == DstMBB)
403 return SinglePath_InPath;
404 if (!AllowSideEntry && SrcMBB->pred_size() > 1)
405 return Not_SinglePath;
406 }
407 if (SrcMBB && SrcMBB->succ_size()==0)
408 return SinglePath_NotInPath;
409 return Not_SinglePath;
410}
411
412int AMDGPUCFGStructurizer::countActiveBlock(MBBVector::const_iterator It,
413 MBBVector::const_iterator E) const {
414 int Count = 0;
415 while (It != E) {
416 if (!isRetiredBlock(*It))
417 ++Count;
418 ++It;
419 }
420 return Count;
421}
422
423bool AMDGPUCFGStructurizer::needMigrateBlock(MachineBasicBlock *MBB) const {
424 unsigned BlockSizeThreshold = 30;
425 unsigned CloneInstrThreshold = 100;
426 bool MultiplePreds = MBB && (MBB->pred_size() > 1);
427
428 if(!MultiplePreds)
429 return false;
430 unsigned BlkSize = MBB->size();
431 return ((BlkSize > BlockSizeThreshold) &&
432 (BlkSize * (MBB->pred_size() - 1) > CloneInstrThreshold));
433}
434
435void AMDGPUCFGStructurizer::reversePredicateSetter(
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000436 MachineBasicBlock::iterator I, MachineBasicBlock &MBB) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000437 assert(I.isValid() && "Expected valid iterator");
Duncan P. N. Exon Smith221847e2016-07-08 19:00:17 +0000438 for (;; --I) {
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000439 if (I == MBB.end())
440 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000441 if (I->getOpcode() == AMDGPU::PRED_X) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000442 switch (I->getOperand(2).getImm()) {
Matt Arsenault44f6d692016-08-13 01:43:46 +0000443 case AMDGPU::PRED_SETE_INT:
444 I->getOperand(2).setImm(AMDGPU::PRED_SETNE_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000445 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000446 case AMDGPU::PRED_SETNE_INT:
447 I->getOperand(2).setImm(AMDGPU::PRED_SETE_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000448 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000449 case AMDGPU::PRED_SETE:
450 I->getOperand(2).setImm(AMDGPU::PRED_SETNE);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000451 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000452 case AMDGPU::PRED_SETNE:
453 I->getOperand(2).setImm(AMDGPU::PRED_SETE);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000454 return;
455 default:
456 llvm_unreachable("PRED_X Opcode invalid!");
457 }
458 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000459 }
460}
461
Vincent Lejeune960a6222013-07-19 21:45:06 +0000462void AMDGPUCFGStructurizer::insertInstrEnd(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000463 int NewOpcode, const DebugLoc &DL) {
464 MachineInstr *MI =
465 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000466 MBB->push_back(MI);
467 //assume the instruction doesn't take any reg operand ...
468 SHOWNEWINSTR(MI);
469}
Tom Stellard75aadc22012-12-11 21:25:42 +0000470
Vincent Lejeune960a6222013-07-19 21:45:06 +0000471MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000472 int NewOpcode,
473 const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000474 MachineInstr *MI =
475 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
476 if (MBB->begin() != MBB->end())
477 MBB->insert(MBB->begin(), MI);
478 else
479 MBB->push_back(MI);
480 SHOWNEWINSTR(MI);
481 return MI;
482}
483
484MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(
485 MachineBasicBlock::iterator I, int NewOpcode) {
486 MachineInstr *OldMI = &(*I);
487 MachineBasicBlock *MBB = OldMI->getParent();
488 MachineInstr *NewMBB =
489 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DebugLoc());
490 MBB->insert(I, NewMBB);
491 //assume the instruction doesn't take any reg operand ...
492 SHOWNEWINSTR(NewMBB);
493 return NewMBB;
494}
495
496void AMDGPUCFGStructurizer::insertCondBranchBefore(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000497 MachineBasicBlock::iterator I, int NewOpcode, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000498 MachineInstr *OldMI = &(*I);
499 MachineBasicBlock *MBB = OldMI->getParent();
500 MachineFunction *MF = MBB->getParent();
501 MachineInstr *NewMI = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
502 MBB->insert(I, NewMI);
503 MachineInstrBuilder MIB(*MF, NewMI);
504 MIB.addReg(OldMI->getOperand(1).getReg(), false);
505 SHOWNEWINSTR(NewMI);
506 //erase later oldInstr->eraseFromParent();
507}
508
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000509void AMDGPUCFGStructurizer::insertCondBranchBefore(
510 MachineBasicBlock *blk, MachineBasicBlock::iterator I, int NewOpcode,
511 int RegNum, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000512 MachineFunction *MF = blk->getParent();
513 MachineInstr *NewInstr = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
514 //insert before
515 blk->insert(I, NewInstr);
516 MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false);
517 SHOWNEWINSTR(NewInstr);
518}
519
Vincent Lejeune960a6222013-07-19 21:45:06 +0000520int AMDGPUCFGStructurizer::getBranchNzeroOpcode(int OldOpcode) {
521 switch(OldOpcode) {
522 case AMDGPU::JUMP_COND:
523 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
524 case AMDGPU::BRANCH_COND_i32:
525 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALNZ_f32;
526 default: llvm_unreachable("internal error");
527 }
528 return -1;
529}
530
531int AMDGPUCFGStructurizer::getBranchZeroOpcode(int OldOpcode) {
532 switch(OldOpcode) {
533 case AMDGPU::JUMP_COND:
534 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
535 case AMDGPU::BRANCH_COND_i32:
536 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALZ_f32;
537 default: llvm_unreachable("internal error");
538 }
539 return -1;
540}
541
542int AMDGPUCFGStructurizer::getContinueNzeroOpcode(int OldOpcode) {
543 switch(OldOpcode) {
544 case AMDGPU::JUMP_COND:
545 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALNZ_i32;
546 default: llvm_unreachable("internal error");
547 };
548 return -1;
549}
550
551int AMDGPUCFGStructurizer::getContinueZeroOpcode(int OldOpcode) {
552 switch(OldOpcode) {
553 case AMDGPU::JUMP_COND:
554 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALZ_i32;
555 default: llvm_unreachable("internal error");
556 }
557 return -1;
558}
559
560MachineBasicBlock *AMDGPUCFGStructurizer::getTrueBranch(MachineInstr *MI) {
561 return MI->getOperand(0).getMBB();
562}
563
564void AMDGPUCFGStructurizer::setTrueBranch(MachineInstr *MI,
565 MachineBasicBlock *MBB) {
566 MI->getOperand(0).setMBB(MBB);
567}
568
569MachineBasicBlock *
570AMDGPUCFGStructurizer::getFalseBranch(MachineBasicBlock *MBB,
571 MachineInstr *MI) {
572 assert(MBB->succ_size() == 2);
573 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
574 MachineBasicBlock::succ_iterator It = MBB->succ_begin();
575 MachineBasicBlock::succ_iterator Next = It;
576 ++Next;
577 return (*It == TrueBranch) ? *Next : *It;
578}
579
580bool AMDGPUCFGStructurizer::isCondBranch(MachineInstr *MI) {
581 switch (MI->getOpcode()) {
582 case AMDGPU::JUMP_COND:
583 case AMDGPU::BRANCH_COND_i32:
584 case AMDGPU::BRANCH_COND_f32: return true;
585 default:
586 return false;
587 }
588 return false;
589}
590
591bool AMDGPUCFGStructurizer::isUncondBranch(MachineInstr *MI) {
592 switch (MI->getOpcode()) {
593 case AMDGPU::JUMP:
594 case AMDGPU::BRANCH:
595 return true;
596 default:
597 return false;
598 }
599 return false;
600}
601
602DebugLoc AMDGPUCFGStructurizer::getLastDebugLocInBB(MachineBasicBlock *MBB) {
603 //get DebugLoc from the first MachineBasicBlock instruction with debug info
604 DebugLoc DL;
605 for (MachineBasicBlock::iterator It = MBB->begin(); It != MBB->end();
606 ++It) {
607 MachineInstr *instr = &(*It);
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000608 if (instr->getDebugLoc())
Vincent Lejeune960a6222013-07-19 21:45:06 +0000609 DL = instr->getDebugLoc();
610 }
611 return DL;
612}
613
614MachineInstr *AMDGPUCFGStructurizer::getNormalBlockBranchInstr(
615 MachineBasicBlock *MBB) {
616 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
617 MachineInstr *MI = &*It;
618 if (MI && (isCondBranch(MI) || isUncondBranch(MI)))
619 return MI;
Craig Topper062a2ba2014-04-25 05:30:21 +0000620 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000621}
622
623MachineInstr *AMDGPUCFGStructurizer::getLoopendBlockBranchInstr(
624 MachineBasicBlock *MBB) {
625 for (MachineBasicBlock::reverse_iterator It = MBB->rbegin(), E = MBB->rend();
626 It != E; ++It) {
627 // FIXME: Simplify
628 MachineInstr *MI = &*It;
629 if (MI) {
630 if (isCondBranch(MI) || isUncondBranch(MI))
631 return MI;
632 else if (!TII->isMov(MI->getOpcode()))
633 break;
634 }
635 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000636 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000637}
638
639MachineInstr *AMDGPUCFGStructurizer::getReturnInstr(MachineBasicBlock *MBB) {
640 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
641 if (It != MBB->rend()) {
642 MachineInstr *instr = &(*It);
643 if (instr->getOpcode() == AMDGPU::RETURN)
644 return instr;
645 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000646 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000647}
648
Vincent Lejeune960a6222013-07-19 21:45:06 +0000649bool AMDGPUCFGStructurizer::isReturnBlock(MachineBasicBlock *MBB) {
650 MachineInstr *MI = getReturnInstr(MBB);
651 bool IsReturn = (MBB->succ_size() == 0);
652 if (MI)
653 assert(IsReturn);
654 else if (IsReturn)
655 DEBUG(
656 dbgs() << "BB" << MBB->getNumber()
657 <<" is return block without RETURN instr\n";);
658 return IsReturn;
659}
660
661void AMDGPUCFGStructurizer::cloneSuccessorList(MachineBasicBlock *DstMBB,
662 MachineBasicBlock *SrcMBB) {
663 for (MachineBasicBlock::succ_iterator It = SrcMBB->succ_begin(),
664 iterEnd = SrcMBB->succ_end(); It != iterEnd; ++It)
665 DstMBB->addSuccessor(*It); // *iter's predecessor is also taken care of
666}
667
668MachineBasicBlock *AMDGPUCFGStructurizer::clone(MachineBasicBlock *MBB) {
669 MachineFunction *Func = MBB->getParent();
670 MachineBasicBlock *NewMBB = Func->CreateMachineBasicBlock();
671 Func->push_back(NewMBB); //insert to function
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000672 for (const MachineInstr &It : *MBB)
673 NewMBB->push_back(Func->CloneMachineInstr(&It));
Vincent Lejeune960a6222013-07-19 21:45:06 +0000674 return NewMBB;
675}
676
677void AMDGPUCFGStructurizer::replaceInstrUseOfBlockWith(
678 MachineBasicBlock *SrcMBB, MachineBasicBlock *OldMBB,
679 MachineBasicBlock *NewBlk) {
680 MachineInstr *BranchMI = getLoopendBlockBranchInstr(SrcMBB);
681 if (BranchMI && isCondBranch(BranchMI) &&
682 getTrueBranch(BranchMI) == OldMBB)
683 setTrueBranch(BranchMI, NewBlk);
684}
685
686void AMDGPUCFGStructurizer::wrapup(MachineBasicBlock *MBB) {
687 assert((!MBB->getParent()->getJumpTableInfo()
688 || MBB->getParent()->getJumpTableInfo()->isEmpty())
689 && "found a jump table");
690
691 //collect continue right before endloop
692 SmallVector<MachineInstr *, DEFAULT_VEC_SLOTS> ContInstr;
693 MachineBasicBlock::iterator Pre = MBB->begin();
694 MachineBasicBlock::iterator E = MBB->end();
695 MachineBasicBlock::iterator It = Pre;
696 while (It != E) {
697 if (Pre->getOpcode() == AMDGPU::CONTINUE
698 && It->getOpcode() == AMDGPU::ENDLOOP)
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000699 ContInstr.push_back(&*Pre);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000700 Pre = It;
701 ++It;
702 }
703
704 //delete continue right before endloop
705 for (unsigned i = 0; i < ContInstr.size(); ++i)
706 ContInstr[i]->eraseFromParent();
707
708 // TODO to fix up jump table so later phase won't be confused. if
709 // (jumpTableInfo->isEmpty() == false) { need to clean the jump table, but
710 // there isn't such an interface yet. alternatively, replace all the other
711 // blocks in the jump table with the entryBlk //}
Vincent Lejeune960a6222013-07-19 21:45:06 +0000712}
713
Vincent Lejeune960a6222013-07-19 21:45:06 +0000714bool AMDGPUCFGStructurizer::prepare() {
715 bool Changed = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000716
717 //FIXME: if not reducible flow graph, make it so ???
718
Vincent Lejeune960a6222013-07-19 21:45:06 +0000719 DEBUG(dbgs() << "AMDGPUCFGStructurizer::prepare\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000720
Vincent Lejeune960a6222013-07-19 21:45:06 +0000721 orderBlocks(FuncRep);
Tom Stellard75aadc22012-12-11 21:25:42 +0000722
Vincent Lejeune960a6222013-07-19 21:45:06 +0000723 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> RetBlks;
Tom Stellard75aadc22012-12-11 21:25:42 +0000724
Vincent Lejeune960a6222013-07-19 21:45:06 +0000725 // Add an ExitBlk to loop that don't have one
726 for (MachineLoopInfo::iterator It = MLI->begin(),
727 E = MLI->end(); It != E; ++It) {
728 MachineLoop *LoopRep = (*It);
729 MBBVector ExitingMBBs;
730 LoopRep->getExitingBlocks(ExitingMBBs);
Tom Stellard75aadc22012-12-11 21:25:42 +0000731
Vincent Lejeune960a6222013-07-19 21:45:06 +0000732 if (ExitingMBBs.size() == 0) {
733 MachineBasicBlock* DummyExitBlk = normalizeInfiniteLoopExit(LoopRep);
734 if (DummyExitBlk)
735 RetBlks.push_back(DummyExitBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000736 }
737 }
738
739 // Remove unconditional branch instr.
740 // Add dummy exit block iff there are multiple returns.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000741 for (SmallVectorImpl<MachineBasicBlock *>::const_iterator
742 It = OrderedBlks.begin(), E = OrderedBlks.end(); It != E; ++It) {
743 MachineBasicBlock *MBB = *It;
744 removeUnconditionalBranch(MBB);
745 removeRedundantConditionalBranch(MBB);
746 if (isReturnBlock(MBB)) {
747 RetBlks.push_back(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000748 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000749 assert(MBB->succ_size() <= 2);
Tom Stellard75aadc22012-12-11 21:25:42 +0000750 }
751
Vincent Lejeune960a6222013-07-19 21:45:06 +0000752 if (RetBlks.size() >= 2) {
753 addDummyExitBlock(RetBlks);
754 Changed = true;
755 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000756
Vincent Lejeune960a6222013-07-19 21:45:06 +0000757 return Changed;
758}
759
760bool AMDGPUCFGStructurizer::run() {
Tom Stellard75aadc22012-12-11 21:25:42 +0000761 //Assume reducible CFG...
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000762 DEBUG(dbgs() << "AMDGPUCFGStructurizer::run\n");
Tom Stellard75aadc22012-12-11 21:25:42 +0000763
Tom Stellard75aadc22012-12-11 21:25:42 +0000764#ifdef STRESSTEST
765 //Use the worse block ordering to test the algorithm.
766 ReverseVector(orderedBlks);
767#endif
768
Vincent Lejeune960a6222013-07-19 21:45:06 +0000769 DEBUG(dbgs() << "Ordered blocks:\n"; printOrderedBlocks(););
770 int NumIter = 0;
771 bool Finish = false;
772 MachineBasicBlock *MBB;
773 bool MakeProgress = false;
774 int NumRemainedBlk = countActiveBlock(OrderedBlks.begin(),
775 OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000776
777 do {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000778 ++NumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000779 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000780 dbgs() << "numIter = " << NumIter
781 << ", numRemaintedBlk = " << NumRemainedBlk << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000782 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000783
Vincent Lejeune960a6222013-07-19 21:45:06 +0000784 SmallVectorImpl<MachineBasicBlock *>::const_iterator It =
785 OrderedBlks.begin();
786 SmallVectorImpl<MachineBasicBlock *>::const_iterator E =
787 OrderedBlks.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000788
Vincent Lejeune960a6222013-07-19 21:45:06 +0000789 SmallVectorImpl<MachineBasicBlock *>::const_iterator SccBeginIter =
790 It;
Craig Topper062a2ba2014-04-25 05:30:21 +0000791 MachineBasicBlock *SccBeginMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000792 int SccNumBlk = 0; // The number of active blocks, init to a
Tom Stellard75aadc22012-12-11 21:25:42 +0000793 // maximum possible number.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000794 int SccNumIter; // Number of iteration in this SCC.
Tom Stellard75aadc22012-12-11 21:25:42 +0000795
Vincent Lejeune960a6222013-07-19 21:45:06 +0000796 while (It != E) {
797 MBB = *It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000798
Vincent Lejeune960a6222013-07-19 21:45:06 +0000799 if (!SccBeginMBB) {
800 SccBeginIter = It;
801 SccBeginMBB = MBB;
802 SccNumIter = 0;
803 SccNumBlk = NumRemainedBlk; // Init to maximum possible number.
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000804 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000805 dbgs() << "start processing SCC" << getSCCNum(SccBeginMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000806 dbgs() << "\n";
807 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000808 }
809
Vincent Lejeune960a6222013-07-19 21:45:06 +0000810 if (!isRetiredBlock(MBB))
811 patternMatch(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000812
Vincent Lejeune960a6222013-07-19 21:45:06 +0000813 ++It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000814
Vincent Lejeune960a6222013-07-19 21:45:06 +0000815 bool ContNextScc = true;
816 if (It == E
817 || getSCCNum(SccBeginMBB) != getSCCNum(*It)) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000818 // Just finish one scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000819 ++SccNumIter;
820 int sccRemainedNumBlk = countActiveBlock(SccBeginIter, It);
821 if (sccRemainedNumBlk != 1 && sccRemainedNumBlk >= SccNumBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000822 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000823 dbgs() << "Can't reduce SCC " << getSCCNum(MBB)
824 << ", sccNumIter = " << SccNumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000825 dbgs() << "doesn't make any progress\n";
826 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000827 ContNextScc = true;
828 } else if (sccRemainedNumBlk != 1 && sccRemainedNumBlk < SccNumBlk) {
829 SccNumBlk = sccRemainedNumBlk;
830 It = SccBeginIter;
831 ContNextScc = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000832 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000833 dbgs() << "repeat processing SCC" << getSCCNum(MBB)
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000834 << "sccNumIter = " << SccNumIter << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000835 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000836 } else {
837 // Finish the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000838 ContNextScc = true;
Tom Stellard75aadc22012-12-11 21:25:42 +0000839 }
840 } else {
841 // Continue on next component in the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000842 ContNextScc = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000843 }
844
Vincent Lejeune960a6222013-07-19 21:45:06 +0000845 if (ContNextScc)
Craig Topper062a2ba2014-04-25 05:30:21 +0000846 SccBeginMBB = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000847 } //while, "one iteration" over the function.
848
Vincent Lejeune960a6222013-07-19 21:45:06 +0000849 MachineBasicBlock *EntryMBB =
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000850 *GraphTraits<MachineFunction *>::nodes_begin(FuncRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000851 if (EntryMBB->succ_size() == 0) {
852 Finish = true;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000853 DEBUG(
854 dbgs() << "Reduce to one block\n";
855 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000856 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000857 int NewnumRemainedBlk
858 = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000859 // consider cloned blocks ??
Vincent Lejeune960a6222013-07-19 21:45:06 +0000860 if (NewnumRemainedBlk == 1 || NewnumRemainedBlk < NumRemainedBlk) {
861 MakeProgress = true;
862 NumRemainedBlk = NewnumRemainedBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +0000863 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000864 MakeProgress = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000865 DEBUG(
866 dbgs() << "No progress\n";
867 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000868 }
869 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000870 } while (!Finish && MakeProgress);
Tom Stellard75aadc22012-12-11 21:25:42 +0000871
872 // Misc wrap up to maintain the consistency of the Function representation.
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000873 wrapup(*GraphTraits<MachineFunction *>::nodes_begin(FuncRep));
Tom Stellard75aadc22012-12-11 21:25:42 +0000874
875 // Detach retired Block, release memory.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000876 for (MBBInfoMap::iterator It = BlockInfoMap.begin(), E = BlockInfoMap.end();
877 It != E; ++It) {
878 if ((*It).second && (*It).second->IsRetired) {
879 assert(((*It).first)->getNumber() != -1);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000880 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000881 dbgs() << "Erase BB" << ((*It).first)->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000882 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000883 (*It).first->eraseFromParent(); //Remove from the parent Function.
Tom Stellard75aadc22012-12-11 21:25:42 +0000884 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000885 delete (*It).second;
Tom Stellard75aadc22012-12-11 21:25:42 +0000886 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000887 BlockInfoMap.clear();
888 LLInfoMap.clear();
Tom Stellard75aadc22012-12-11 21:25:42 +0000889
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000890 if (!Finish) {
891 DEBUG(FuncRep->viewCFG());
Matt Arsenault5de68cb2016-03-02 03:33:55 +0000892 report_fatal_error("IRREDUCIBLE_CFG");
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000893 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000894
895 return true;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000896}
Tom Stellard75aadc22012-12-11 21:25:42 +0000897
Vincent Lejeune960a6222013-07-19 21:45:06 +0000898void AMDGPUCFGStructurizer::orderBlocks(MachineFunction *MF) {
899 int SccNum = 0;
900 MachineBasicBlock *MBB;
Duncan P. N. Exon Smith8e661ef2014-02-04 19:19:07 +0000901 for (scc_iterator<MachineFunction *> It = scc_begin(MF); !It.isAtEnd();
902 ++It, ++SccNum) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000903 const std::vector<MachineBasicBlock *> &SccNext = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000904 for (std::vector<MachineBasicBlock *>::const_iterator
905 blockIter = SccNext.begin(), blockEnd = SccNext.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000906 blockIter != blockEnd; ++blockIter) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000907 MBB = *blockIter;
908 OrderedBlks.push_back(MBB);
909 recordSccnum(MBB, SccNum);
Tom Stellard75aadc22012-12-11 21:25:42 +0000910 }
911 }
912
913 //walk through all the block in func to check for unreachable
Vincent Lejeune960a6222013-07-19 21:45:06 +0000914 typedef GraphTraits<MachineFunction *> GTM;
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000915 auto It = GTM::nodes_begin(MF), E = GTM::nodes_end(MF);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000916 for (; It != E; ++It) {
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000917 MachineBasicBlock *MBB = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000918 SccNum = getSCCNum(MBB);
919 if (SccNum == INVALIDSCCNUM)
920 dbgs() << "unreachable block BB" << MBB->getNumber() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +0000921 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000922}
Tom Stellard75aadc22012-12-11 21:25:42 +0000923
Vincent Lejeune960a6222013-07-19 21:45:06 +0000924int AMDGPUCFGStructurizer::patternMatch(MachineBasicBlock *MBB) {
925 int NumMatch = 0;
926 int CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000927
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000928 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000929 dbgs() << "Begin patternMatch BB" << MBB->getNumber() << "\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 while ((CurMatch = patternMatchGroup(MBB)) > 0)
933 NumMatch += CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000934
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000935 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000936 dbgs() << "End patternMatch BB" << MBB->getNumber()
937 << ", numMatch = " << NumMatch << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000938 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000939
Vincent Lejeune960a6222013-07-19 21:45:06 +0000940 return NumMatch;
941}
Tom Stellard75aadc22012-12-11 21:25:42 +0000942
Vincent Lejeune960a6222013-07-19 21:45:06 +0000943int AMDGPUCFGStructurizer::patternMatchGroup(MachineBasicBlock *MBB) {
944 int NumMatch = 0;
945 NumMatch += loopendPatternMatch();
946 NumMatch += serialPatternMatch(MBB);
947 NumMatch += ifPatternMatch(MBB);
948 return NumMatch;
949}
Tom Stellard75aadc22012-12-11 21:25:42 +0000950
Vincent Lejeune960a6222013-07-19 21:45:06 +0000951int AMDGPUCFGStructurizer::serialPatternMatch(MachineBasicBlock *MBB) {
952 if (MBB->succ_size() != 1)
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 MachineBasicBlock *childBlk = *MBB->succ_begin();
956 if (childBlk->pred_size() != 1 || isActiveLoophead(childBlk))
Tom Stellard75aadc22012-12-11 21:25:42 +0000957 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000958
Vincent Lejeune960a6222013-07-19 21:45:06 +0000959 mergeSerialBlock(MBB, childBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000960 ++numSerialPatternMatch;
961 return 1;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000962}
Tom Stellard75aadc22012-12-11 21:25:42 +0000963
Vincent Lejeune960a6222013-07-19 21:45:06 +0000964int AMDGPUCFGStructurizer::ifPatternMatch(MachineBasicBlock *MBB) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000965 //two edges
Vincent Lejeune960a6222013-07-19 21:45:06 +0000966 if (MBB->succ_size() != 2)
Tom Stellard75aadc22012-12-11 21:25:42 +0000967 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000968 if (hasBackEdge(MBB))
Tom Stellard75aadc22012-12-11 21:25:42 +0000969 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000970 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
971 if (!BranchMI)
Tom Stellard75aadc22012-12-11 21:25:42 +0000972 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000973
Vincent Lejeune960a6222013-07-19 21:45:06 +0000974 assert(isCondBranch(BranchMI));
Tom Stellard827ec9b2013-11-18 19:43:38 +0000975 int NumMatch = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000976
Vincent Lejeune960a6222013-07-19 21:45:06 +0000977 MachineBasicBlock *TrueMBB = getTrueBranch(BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000978 NumMatch += serialPatternMatch(TrueMBB);
979 NumMatch += ifPatternMatch(TrueMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000980 MachineBasicBlock *FalseMBB = getFalseBranch(MBB, BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000981 NumMatch += serialPatternMatch(FalseMBB);
982 NumMatch += ifPatternMatch(FalseMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000983 MachineBasicBlock *LandBlk;
984 int Cloned = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000985
Vincent Lejeune960a6222013-07-19 21:45:06 +0000986 assert (!TrueMBB->succ_empty() || !FalseMBB->succ_empty());
Tom Stellard75aadc22012-12-11 21:25:42 +0000987 // TODO: Simplify
Vincent Lejeune960a6222013-07-19 21:45:06 +0000988 if (TrueMBB->succ_size() == 1 && FalseMBB->succ_size() == 1
989 && *TrueMBB->succ_begin() == *FalseMBB->succ_begin()) {
990 // Diamond pattern
991 LandBlk = *TrueMBB->succ_begin();
992 } else if (TrueMBB->succ_size() == 1 && *TrueMBB->succ_begin() == FalseMBB) {
993 // Triangle pattern, false is empty
994 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000995 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000996 } else if (FalseMBB->succ_size() == 1
997 && *FalseMBB->succ_begin() == TrueMBB) {
998 // Triangle pattern, true is empty
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +0000999 // We reverse the predicate to make a triangle, empty false pattern;
1000 std::swap(TrueMBB, FalseMBB);
Hans Wennborg0dd9ed12016-08-13 01:12:49 +00001001 reversePredicateSetter(MBB->end(), *MBB);
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001002 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +00001003 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001004 } else if (FalseMBB->succ_size() == 1
1005 && isSameloopDetachedContbreak(TrueMBB, FalseMBB)) {
1006 LandBlk = *FalseMBB->succ_begin();
1007 } else if (TrueMBB->succ_size() == 1
1008 && isSameloopDetachedContbreak(FalseMBB, TrueMBB)) {
1009 LandBlk = *TrueMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001010 } else {
Tom Stellard827ec9b2013-11-18 19:43:38 +00001011 return NumMatch + handleJumpintoIf(MBB, TrueMBB, FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001012 }
1013
1014 // improveSimpleJumpinfoIf can handle the case where landBlk == NULL but the
1015 // new BB created for landBlk==NULL may introduce new challenge to the
1016 // reduction process.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001017 if (LandBlk &&
1018 ((TrueMBB && TrueMBB->pred_size() > 1)
1019 || (FalseMBB && FalseMBB->pred_size() > 1))) {
1020 Cloned += improveSimpleJumpintoIf(MBB, TrueMBB, FalseMBB, &LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001021 }
1022
Vincent Lejeune960a6222013-07-19 21:45:06 +00001023 if (TrueMBB && TrueMBB->pred_size() > 1) {
1024 TrueMBB = cloneBlockForPredecessor(TrueMBB, MBB);
1025 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001026 }
1027
Vincent Lejeune960a6222013-07-19 21:45:06 +00001028 if (FalseMBB && FalseMBB->pred_size() > 1) {
1029 FalseMBB = cloneBlockForPredecessor(FalseMBB, MBB);
1030 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001031 }
1032
Vincent Lejeune960a6222013-07-19 21:45:06 +00001033 mergeIfthenelseBlock(BranchMI, MBB, TrueMBB, FalseMBB, LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001034
1035 ++numIfPatternMatch;
1036
Vincent Lejeune960a6222013-07-19 21:45:06 +00001037 numClonedBlock += Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001038
Tom Stellard827ec9b2013-11-18 19:43:38 +00001039 return 1 + Cloned + NumMatch;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001040}
Tom Stellard75aadc22012-12-11 21:25:42 +00001041
Vincent Lejeune960a6222013-07-19 21:45:06 +00001042int AMDGPUCFGStructurizer::loopendPatternMatch() {
Jan Vesely18b289f2015-03-13 17:32:43 +00001043 std::deque<MachineLoop *> NestedLoops;
1044 for (auto &It: *MLI)
1045 for (MachineLoop *ML : depth_first(It))
1046 NestedLoops.push_front(ML);
David Blaikieceec2bd2014-04-11 01:50:01 +00001047
Eugene Zelenko66203762017-01-21 00:53:49 +00001048 if (NestedLoops.empty())
Tom Stellard75aadc22012-12-11 21:25:42 +00001049 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001050
Jan Vesely18b289f2015-03-13 17:32:43 +00001051 // Process nested loop outside->inside (we did push_front),
1052 // so "continue" to a outside loop won't be mistaken as "break"
1053 // of the current loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001054 int Num = 0;
Jan Vesely18b289f2015-03-13 17:32:43 +00001055 for (MachineLoop *ExaminedLoop : NestedLoops) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001056 if (ExaminedLoop->getNumBlocks() == 0 || Visited[ExaminedLoop])
Tom Stellard75aadc22012-12-11 21:25:42 +00001057 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001058 DEBUG(dbgs() << "Processing:\n"; ExaminedLoop->dump(););
1059 int NumBreak = mergeLoop(ExaminedLoop);
1060 if (NumBreak == -1)
Tom Stellard75aadc22012-12-11 21:25:42 +00001061 break;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001062 Num += NumBreak;
1063 }
1064 return Num;
1065}
Tom Stellard75aadc22012-12-11 21:25:42 +00001066
Vincent Lejeune960a6222013-07-19 21:45:06 +00001067int AMDGPUCFGStructurizer::mergeLoop(MachineLoop *LoopRep) {
1068 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1069 MBBVector ExitingMBBs;
1070 LoopRep->getExitingBlocks(ExitingMBBs);
1071 assert(!ExitingMBBs.empty() && "Infinite Loop not supported");
1072 DEBUG(dbgs() << "Loop has " << ExitingMBBs.size() << " exiting blocks\n";);
1073 // We assume a single ExitBlk
1074 MBBVector ExitBlks;
1075 LoopRep->getExitBlocks(ExitBlks);
1076 SmallPtrSet<MachineBasicBlock *, 2> ExitBlkSet;
1077 for (unsigned i = 0, e = ExitBlks.size(); i < e; ++i)
1078 ExitBlkSet.insert(ExitBlks[i]);
1079 assert(ExitBlkSet.size() == 1);
1080 MachineBasicBlock *ExitBlk = *ExitBlks.begin();
1081 assert(ExitBlk && "Loop has several exit block");
1082 MBBVector LatchBlks;
Eugene Zelenko66203762017-01-21 00:53:49 +00001083 typedef GraphTraits<Inverse<MachineBasicBlock*>> InvMBBTraits;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001084 InvMBBTraits::ChildIteratorType PI = InvMBBTraits::child_begin(LoopHeader),
1085 PE = InvMBBTraits::child_end(LoopHeader);
1086 for (; PI != PE; PI++) {
1087 if (LoopRep->contains(*PI))
1088 LatchBlks.push_back(*PI);
Tom Stellard75aadc22012-12-11 21:25:42 +00001089 }
1090
Vincent Lejeune960a6222013-07-19 21:45:06 +00001091 for (unsigned i = 0, e = ExitingMBBs.size(); i < e; ++i)
1092 mergeLoopbreakBlock(ExitingMBBs[i], ExitBlk);
1093 for (unsigned i = 0, e = LatchBlks.size(); i < e; ++i)
1094 settleLoopcontBlock(LatchBlks[i], LoopHeader);
1095 int Match = 0;
1096 do {
1097 Match = 0;
1098 Match += serialPatternMatch(LoopHeader);
1099 Match += ifPatternMatch(LoopHeader);
1100 } while (Match > 0);
1101 mergeLooplandBlock(LoopHeader, ExitBlk);
1102 MachineLoop *ParentLoop = LoopRep->getParentLoop();
1103 if (ParentLoop)
1104 MLI->changeLoopFor(LoopHeader, ParentLoop);
1105 else
1106 MLI->removeBlock(LoopHeader);
1107 Visited[LoopRep] = true;
1108 return 1;
1109}
Tom Stellard75aadc22012-12-11 21:25:42 +00001110
Vincent Lejeune960a6222013-07-19 21:45:06 +00001111bool AMDGPUCFGStructurizer::isSameloopDetachedContbreak(
1112 MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB) {
1113 if (Src1MBB->succ_size() == 0) {
1114 MachineLoop *LoopRep = MLI->getLoopFor(Src1MBB);
1115 if (LoopRep&& LoopRep == MLI->getLoopFor(Src2MBB)) {
1116 MachineBasicBlock *&TheEntry = LLInfoMap[LoopRep];
1117 if (TheEntry) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001118 DEBUG(
1119 dbgs() << "isLoopContBreakBlock yes src1 = BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001120 << Src1MBB->getNumber()
1121 << " src2 = BB" << Src2MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001122 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001123 return true;
1124 }
1125 }
1126 }
1127 return false;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001128}
Tom Stellard75aadc22012-12-11 21:25:42 +00001129
Vincent Lejeune960a6222013-07-19 21:45:06 +00001130int AMDGPUCFGStructurizer::handleJumpintoIf(MachineBasicBlock *HeadMBB,
1131 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1132 int Num = handleJumpintoIfImp(HeadMBB, TrueMBB, FalseMBB);
1133 if (Num == 0) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001134 DEBUG(
1135 dbgs() << "handleJumpintoIf swap trueBlk and FalseBlk" << "\n";
1136 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001137 Num = handleJumpintoIfImp(HeadMBB, FalseMBB, TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001138 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001139 return Num;
Tom Stellard75aadc22012-12-11 21:25:42 +00001140}
1141
Vincent Lejeune960a6222013-07-19 21:45:06 +00001142int AMDGPUCFGStructurizer::handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
1143 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1144 int Num = 0;
1145 MachineBasicBlock *DownBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001146
1147 //trueBlk could be the common post dominator
Vincent Lejeune960a6222013-07-19 21:45:06 +00001148 DownBlk = TrueMBB;
Tom Stellard75aadc22012-12-11 21:25:42 +00001149
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001150 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001151 dbgs() << "handleJumpintoIfImp head = BB" << HeadMBB->getNumber()
1152 << " true = BB" << TrueMBB->getNumber()
1153 << ", numSucc=" << TrueMBB->succ_size()
1154 << " false = BB" << FalseMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001155 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001156
Vincent Lejeune960a6222013-07-19 21:45:06 +00001157 while (DownBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001158 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001159 dbgs() << "check down = BB" << DownBlk->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001160 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001161
Vincent Lejeune960a6222013-07-19 21:45:06 +00001162 if (singlePathTo(FalseMBB, DownBlk) == SinglePath_InPath) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001163 DEBUG(
1164 dbgs() << " working\n";
1165 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001166
Vincent Lejeune960a6222013-07-19 21:45:06 +00001167 Num += cloneOnSideEntryTo(HeadMBB, TrueMBB, DownBlk);
1168 Num += cloneOnSideEntryTo(HeadMBB, FalseMBB, DownBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001169
Vincent Lejeune960a6222013-07-19 21:45:06 +00001170 numClonedBlock += Num;
1171 Num += serialPatternMatch(*HeadMBB->succ_begin());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001172 Num += serialPatternMatch(*std::next(HeadMBB->succ_begin()));
Vincent Lejeune960a6222013-07-19 21:45:06 +00001173 Num += ifPatternMatch(HeadMBB);
1174 assert(Num > 0);
Tom Stellard75aadc22012-12-11 21:25:42 +00001175
1176 break;
1177 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001178 DEBUG(
1179 dbgs() << " not working\n";
1180 );
Craig Topper062a2ba2014-04-25 05:30:21 +00001181 DownBlk = (DownBlk->succ_size() == 1) ? (*DownBlk->succ_begin()) : nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001182 } // walk down the postDomTree
1183
Vincent Lejeune960a6222013-07-19 21:45:06 +00001184 return Num;
1185}
Tom Stellard75aadc22012-12-11 21:25:42 +00001186
Vincent Lejeune960a6222013-07-19 21:45:06 +00001187void AMDGPUCFGStructurizer::showImproveSimpleJumpintoIf(
1188 MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB,
1189 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail) {
1190 dbgs() << "head = BB" << HeadMBB->getNumber()
1191 << " size = " << HeadMBB->size();
1192 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001193 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001194 HeadMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001195 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001196 }
1197
Vincent Lejeune960a6222013-07-19 21:45:06 +00001198 if (TrueMBB) {
1199 dbgs() << ", true = BB" << TrueMBB->getNumber() << " size = "
1200 << TrueMBB->size() << " numPred = " << TrueMBB->pred_size();
1201 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001202 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001203 TrueMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001204 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001205 }
1206 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001207 if (FalseMBB) {
1208 dbgs() << ", false = BB" << FalseMBB->getNumber() << " size = "
1209 << FalseMBB->size() << " numPred = " << FalseMBB->pred_size();
1210 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001211 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001212 FalseMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001213 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001214 }
1215 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001216 if (LandMBB) {
1217 dbgs() << ", land = BB" << LandMBB->getNumber() << " size = "
1218 << LandMBB->size() << " numPred = " << LandMBB->pred_size();
1219 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001220 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001221 LandMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001222 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001223 }
1224 }
1225
Eugene Zelenko66203762017-01-21 00:53:49 +00001226 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001227}
Tom Stellard75aadc22012-12-11 21:25:42 +00001228
Vincent Lejeune960a6222013-07-19 21:45:06 +00001229int AMDGPUCFGStructurizer::improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
1230 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
1231 MachineBasicBlock **LandMBBPtr) {
1232 bool MigrateTrue = false;
1233 bool MigrateFalse = false;
Tom Stellard75aadc22012-12-11 21:25:42 +00001234
Vincent Lejeune960a6222013-07-19 21:45:06 +00001235 MachineBasicBlock *LandBlk = *LandMBBPtr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001236
Vincent Lejeune960a6222013-07-19 21:45:06 +00001237 assert((!TrueMBB || TrueMBB->succ_size() <= 1)
1238 && (!FalseMBB || FalseMBB->succ_size() <= 1));
Tom Stellard75aadc22012-12-11 21:25:42 +00001239
Vincent Lejeune960a6222013-07-19 21:45:06 +00001240 if (TrueMBB == FalseMBB)
Tom Stellard75aadc22012-12-11 21:25:42 +00001241 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001242
Vincent Lejeune960a6222013-07-19 21:45:06 +00001243 MigrateTrue = needMigrateBlock(TrueMBB);
1244 MigrateFalse = needMigrateBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001245
Vincent Lejeune960a6222013-07-19 21:45:06 +00001246 if (!MigrateTrue && !MigrateFalse)
Tom Stellard75aadc22012-12-11 21:25:42 +00001247 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001248
1249 // If we need to migrate either trueBlk and falseBlk, migrate the rest that
1250 // have more than one predecessors. without doing this, its predecessor
1251 // rather than headBlk will have undefined value in initReg.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001252 if (!MigrateTrue && TrueMBB && TrueMBB->pred_size() > 1)
1253 MigrateTrue = true;
1254 if (!MigrateFalse && FalseMBB && FalseMBB->pred_size() > 1)
1255 MigrateFalse = true;
Tom Stellard75aadc22012-12-11 21:25:42 +00001256
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001257 DEBUG(
1258 dbgs() << "before improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001259 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001260 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001261
1262 // org: headBlk => if () {trueBlk} else {falseBlk} => landBlk
1263 //
1264 // new: headBlk => if () {initReg = 1; org trueBlk branch} else
1265 // {initReg = 0; org falseBlk branch }
1266 // => landBlk => if (initReg) {org trueBlk} else {org falseBlk}
1267 // => org landBlk
1268 // if landBlk->pred_size() > 2, put the about if-else inside
1269 // if (initReg !=2) {...}
1270 //
1271 // add initReg = initVal to headBlk
1272
1273 const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32);
Tom Stellardb34186a2013-10-16 17:06:02 +00001274 if (!MigrateTrue || !MigrateFalse) {
1275 // XXX: We have an opportunity here to optimize the "branch into if" case
1276 // here. Branch into if looks like this:
1277 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001278 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001279 // diamond_head branch_from
1280 // / \ |
1281 // diamond_false diamond_true
1282 // \ /
1283 // done
1284 //
1285 // The diamond_head block begins the "if" and the diamond_true block
1286 // is the block being "branched into".
1287 //
1288 // If MigrateTrue is true, then TrueBB is the block being "branched into"
1289 // and if MigrateFalse is true, then FalseBB is the block being
1290 // "branched into"
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001291 //
Tom Stellardb34186a2013-10-16 17:06:02 +00001292 // Here is the pseudo code for how I think the optimization should work:
1293 // 1. Insert MOV GPR0, 0 before the branch instruction in diamond_head.
1294 // 2. Insert MOV GPR0, 1 before the branch instruction in branch_from.
1295 // 3. Move the branch instruction from diamond_head into its own basic
1296 // block (new_block).
1297 // 4. Add an unconditional branch from diamond_head to new_block
1298 // 5. Replace the branch instruction in branch_from with an unconditional
1299 // branch to new_block. If branch_from has multiple predecessors, then
1300 // we need to replace the True/False block in the branch
1301 // instruction instead of replacing it.
1302 // 6. Change the condition of the branch instruction in new_block from
1303 // COND to (COND || GPR0)
1304 //
1305 // In order insert these MOV instruction, we will need to use the
1306 // RegisterScavenger. Usually liveness stops being tracked during
1307 // the late machine optimization passes, however if we implement
1308 // bool TargetRegisterInfo::requiresRegisterScavenging(
1309 // const MachineFunction &MF)
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001310 // and have it return true, liveness will be tracked correctly
Tom Stellardb34186a2013-10-16 17:06:02 +00001311 // by generic optimization passes. We will also need to make sure that
1312 // all of our target-specific passes that run after regalloc and before
1313 // the CFGStructurizer track liveness and we will need to modify this pass
1314 // to correctly track liveness.
1315 //
1316 // After the above changes, the new CFG should look like this:
1317 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001318 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001319 // diamond_head branch_from
1320 // \ /
1321 // new_block
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001322 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001323 // diamond_false diamond_true
1324 // \ /
1325 // done
1326 //
1327 // Without this optimization, we are forced to duplicate the diamond_true
1328 // block and we will end up with a CFG like this:
1329 //
1330 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001331 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001332 // diamond_head branch_from
1333 // / \ |
1334 // diamond_false diamond_true diamond_true (duplicate)
1335 // \ / |
1336 // done --------------------|
1337 //
1338 // Duplicating diamond_true can be very costly especially if it has a
1339 // lot of instructions.
1340 return 0;
1341 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001342
Vincent Lejeune960a6222013-07-19 21:45:06 +00001343 int NumNewBlk = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001344
Vincent Lejeune960a6222013-07-19 21:45:06 +00001345 bool LandBlkHasOtherPred = (LandBlk->pred_size() > 2);
Tom Stellard75aadc22012-12-11 21:25:42 +00001346
1347 //insert AMDGPU::ENDIF to avoid special case "input landBlk == NULL"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001348 MachineBasicBlock::iterator I = insertInstrBefore(LandBlk, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001349
Vincent Lejeune960a6222013-07-19 21:45:06 +00001350 if (LandBlkHasOtherPred) {
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001351 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001352 unsigned CmpResReg =
1353 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001354 report_fatal_error("Extra compare instruction needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001355 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET,
1356 CmpResReg, DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001357 }
1358
Tom Stellard69f86d12013-10-16 17:05:56 +00001359 // XXX: We are running this after RA, so creating virtual registers will
1360 // cause an assertion failure in the PostRA scheduling pass.
1361 unsigned InitReg =
1362 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001363 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET, InitReg,
1364 DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001365
Vincent Lejeune960a6222013-07-19 21:45:06 +00001366 if (MigrateTrue) {
1367 migrateInstruction(TrueMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001368 // need to uncondionally insert the assignment to ensure a path from its
1369 // predecessor rather than headBlk has valid value in initReg if
1370 // (initVal != 1).
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001371 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001372 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001373 insertInstrBefore(I, AMDGPU::ELSE);
Tom Stellard75aadc22012-12-11 21:25:42 +00001374
Vincent Lejeune960a6222013-07-19 21:45:06 +00001375 if (MigrateFalse) {
1376 migrateInstruction(FalseMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001377 // need to uncondionally insert the assignment to ensure a path from its
1378 // predecessor rather than headBlk has valid value in initReg if
1379 // (initVal != 0)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001380 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001381 }
1382
Vincent Lejeune960a6222013-07-19 21:45:06 +00001383 if (LandBlkHasOtherPred) {
Tom Stellard75aadc22012-12-11 21:25:42 +00001384 // add endif
Vincent Lejeune960a6222013-07-19 21:45:06 +00001385 insertInstrBefore(I, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001386
1387 // put initReg = 2 to other predecessors of landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001388 for (MachineBasicBlock::pred_iterator PI = LandBlk->pred_begin(),
1389 PE = LandBlk->pred_end(); PI != PE; ++PI) {
1390 MachineBasicBlock *MBB = *PI;
1391 if (MBB != TrueMBB && MBB != FalseMBB)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001392 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001393 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001394 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001395 DEBUG(
1396 dbgs() << "result from improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001397 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001398 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001399
1400 // update landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001401 *LandMBBPtr = LandBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001402
Vincent Lejeune960a6222013-07-19 21:45:06 +00001403 return NumNewBlk;
1404}
Tom Stellard75aadc22012-12-11 21:25:42 +00001405
Vincent Lejeune960a6222013-07-19 21:45:06 +00001406void AMDGPUCFGStructurizer::mergeSerialBlock(MachineBasicBlock *DstMBB,
1407 MachineBasicBlock *SrcMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001408 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001409 dbgs() << "serialPattern BB" << DstMBB->getNumber()
1410 << " <= BB" << SrcMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001411 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001412 DstMBB->splice(DstMBB->end(), SrcMBB, SrcMBB->begin(), SrcMBB->end());
Tom Stellard75aadc22012-12-11 21:25:42 +00001413
Cong Houc1069892015-12-13 09:26:17 +00001414 DstMBB->removeSuccessor(SrcMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001415 cloneSuccessorList(DstMBB, SrcMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001416
Vincent Lejeune960a6222013-07-19 21:45:06 +00001417 removeSuccessor(SrcMBB);
1418 MLI->removeBlock(SrcMBB);
1419 retireBlock(SrcMBB);
1420}
Tom Stellard75aadc22012-12-11 21:25:42 +00001421
Vincent Lejeune960a6222013-07-19 21:45:06 +00001422void AMDGPUCFGStructurizer::mergeIfthenelseBlock(MachineInstr *BranchMI,
1423 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
1424 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB) {
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001425 assert (TrueMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001426 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001427 dbgs() << "ifPattern BB" << MBB->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001428 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001429 if (TrueMBB) {
1430 dbgs() << "BB" << TrueMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001431 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001432 dbgs() << " } else ";
1433 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001434 if (FalseMBB) {
1435 dbgs() << "BB" << FalseMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001436 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001437 dbgs() << " }\n ";
1438 dbgs() << "landBlock: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001439 if (!LandMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001440 dbgs() << "NULL";
Tom Stellard75aadc22012-12-11 21:25:42 +00001441 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001442 dbgs() << "BB" << LandMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001443 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001444 dbgs() << "\n";
1445 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001446
Vincent Lejeune960a6222013-07-19 21:45:06 +00001447 int OldOpcode = BranchMI->getOpcode();
1448 DebugLoc BranchDL = BranchMI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001449
1450// transform to
1451// if cond
1452// trueBlk
1453// else
1454// falseBlk
1455// endif
1456// landBlk
1457
Vincent Lejeune960a6222013-07-19 21:45:06 +00001458 MachineBasicBlock::iterator I = BranchMI;
1459 insertCondBranchBefore(I, getBranchNzeroOpcode(OldOpcode),
1460 BranchDL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001461
Vincent Lejeune960a6222013-07-19 21:45:06 +00001462 if (TrueMBB) {
1463 MBB->splice(I, TrueMBB, TrueMBB->begin(), TrueMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001464 MBB->removeSuccessor(TrueMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001465 if (LandMBB && TrueMBB->succ_size()!=0)
Cong Houc1069892015-12-13 09:26:17 +00001466 TrueMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001467 retireBlock(TrueMBB);
1468 MLI->removeBlock(TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001469 }
1470
Vincent Lejeune960a6222013-07-19 21:45:06 +00001471 if (FalseMBB) {
1472 insertInstrBefore(I, AMDGPU::ELSE);
1473 MBB->splice(I, FalseMBB, FalseMBB->begin(),
1474 FalseMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001475 MBB->removeSuccessor(FalseMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001476 if (LandMBB && FalseMBB->succ_size() != 0)
Cong Houc1069892015-12-13 09:26:17 +00001477 FalseMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001478 retireBlock(FalseMBB);
1479 MLI->removeBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001480 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001481 insertInstrBefore(I, AMDGPU::ENDIF);
1482
1483 BranchMI->eraseFromParent();
1484
1485 if (LandMBB && TrueMBB && FalseMBB)
1486 MBB->addSuccessor(LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001487}
1488
1489void AMDGPUCFGStructurizer::mergeLooplandBlock(MachineBasicBlock *DstBlk,
1490 MachineBasicBlock *LandMBB) {
1491 DEBUG(dbgs() << "loopPattern header = BB" << DstBlk->getNumber()
1492 << " land = BB" << LandMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001493
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001494 insertInstrBefore(DstBlk, AMDGPU::WHILELOOP, DebugLoc());
1495 insertInstrEnd(DstBlk, AMDGPU::ENDLOOP, DebugLoc());
Cong Houd97c1002015-12-01 05:29:22 +00001496 DstBlk->replaceSuccessor(DstBlk, LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001497}
Tom Stellard75aadc22012-12-11 21:25:42 +00001498
Vincent Lejeune960a6222013-07-19 21:45:06 +00001499void AMDGPUCFGStructurizer::mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
1500 MachineBasicBlock *LandMBB) {
1501 DEBUG(dbgs() << "loopbreakPattern exiting = BB" << ExitingMBB->getNumber()
1502 << " land = BB" << LandMBB->getNumber() << "\n";);
1503 MachineInstr *BranchMI = getLoopendBlockBranchInstr(ExitingMBB);
1504 assert(BranchMI && isCondBranch(BranchMI));
1505 DebugLoc DL = BranchMI->getDebugLoc();
1506 MachineBasicBlock *TrueBranch = getTrueBranch(BranchMI);
1507 MachineBasicBlock::iterator I = BranchMI;
1508 if (TrueBranch != LandMBB)
Hans Wennborg0dd9ed12016-08-13 01:12:49 +00001509 reversePredicateSetter(I, *I->getParent());
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001510 insertCondBranchBefore(ExitingMBB, I, AMDGPU::IF_PREDICATE_SET, AMDGPU::PREDICATE_BIT, DL);
1511 insertInstrBefore(I, AMDGPU::BREAK);
1512 insertInstrBefore(I, AMDGPU::ENDIF);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001513 //now branchInst can be erase safely
1514 BranchMI->eraseFromParent();
1515 //now take care of successors, retire blocks
Cong Houc1069892015-12-13 09:26:17 +00001516 ExitingMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001517}
Tom Stellard75aadc22012-12-11 21:25:42 +00001518
Vincent Lejeune960a6222013-07-19 21:45:06 +00001519void AMDGPUCFGStructurizer::settleLoopcontBlock(MachineBasicBlock *ContingMBB,
1520 MachineBasicBlock *ContMBB) {
1521 DEBUG(dbgs() << "settleLoopcontBlock conting = BB"
1522 << ContingMBB->getNumber()
1523 << ", cont = BB" << ContMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001524
Vincent Lejeune960a6222013-07-19 21:45:06 +00001525 MachineInstr *MI = getLoopendBlockBranchInstr(ContingMBB);
1526 if (MI) {
1527 assert(isCondBranch(MI));
1528 MachineBasicBlock::iterator I = MI;
1529 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
1530 int OldOpcode = MI->getOpcode();
1531 DebugLoc DL = MI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001532
Vincent Lejeune960a6222013-07-19 21:45:06 +00001533 bool UseContinueLogical = ((&*ContingMBB->rbegin()) == MI);
1534
David Blaikie4eaa79c2015-03-23 20:56:44 +00001535 if (!UseContinueLogical) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001536 int BranchOpcode =
1537 TrueBranch == ContMBB ? getBranchNzeroOpcode(OldOpcode) :
1538 getBranchZeroOpcode(OldOpcode);
1539 insertCondBranchBefore(I, BranchOpcode, DL);
1540 // insertEnd to ensure phi-moves, if exist, go before the continue-instr.
1541 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE, DL);
1542 insertInstrEnd(ContingMBB, AMDGPU::ENDIF, DL);
1543 } else {
1544 int BranchOpcode =
1545 TrueBranch == ContMBB ? getContinueNzeroOpcode(OldOpcode) :
1546 getContinueZeroOpcode(OldOpcode);
1547 insertCondBranchBefore(I, BranchOpcode, DL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001548 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001549
1550 MI->eraseFromParent();
1551 } else {
1552 // if we've arrived here then we've already erased the branch instruction
1553 // travel back up the basic block to see the last reference of our debug
1554 // location we've just inserted that reference here so it should be
1555 // representative insertEnd to ensure phi-moves, if exist, go before the
1556 // continue-instr.
1557 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE,
1558 getLastDebugLocInBB(ContingMBB));
Tom Stellard75aadc22012-12-11 21:25:42 +00001559 }
1560}
1561
Vincent Lejeune960a6222013-07-19 21:45:06 +00001562int AMDGPUCFGStructurizer::cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
1563 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB) {
1564 int Cloned = 0;
1565 assert(PreMBB->isSuccessor(SrcMBB));
1566 while (SrcMBB && SrcMBB != DstMBB) {
1567 assert(SrcMBB->succ_size() == 1);
1568 if (SrcMBB->pred_size() > 1) {
1569 SrcMBB = cloneBlockForPredecessor(SrcMBB, PreMBB);
1570 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001571 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001572
Vincent Lejeune960a6222013-07-19 21:45:06 +00001573 PreMBB = SrcMBB;
1574 SrcMBB = *SrcMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001575 }
1576
Vincent Lejeune960a6222013-07-19 21:45:06 +00001577 return Cloned;
1578}
Tom Stellard75aadc22012-12-11 21:25:42 +00001579
Vincent Lejeune960a6222013-07-19 21:45:06 +00001580MachineBasicBlock *
1581AMDGPUCFGStructurizer::cloneBlockForPredecessor(MachineBasicBlock *MBB,
1582 MachineBasicBlock *PredMBB) {
1583 assert(PredMBB->isSuccessor(MBB) &&
Tom Stellard75aadc22012-12-11 21:25:42 +00001584 "succBlk is not a prececessor of curBlk");
1585
Vincent Lejeune960a6222013-07-19 21:45:06 +00001586 MachineBasicBlock *CloneMBB = clone(MBB); //clone instructions
1587 replaceInstrUseOfBlockWith(PredMBB, MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001588 //srcBlk, oldBlk, newBlk
1589
Cong Houd97c1002015-12-01 05:29:22 +00001590 PredMBB->replaceSuccessor(MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001591
1592 // add all successor to cloneBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001593 cloneSuccessorList(CloneMBB, MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001594
Vincent Lejeune960a6222013-07-19 21:45:06 +00001595 numClonedInstr += MBB->size();
Tom Stellard75aadc22012-12-11 21:25:42 +00001596
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001597 DEBUG(
1598 dbgs() << "Cloned block: " << "BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001599 << MBB->getNumber() << "size " << MBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001600 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001601
Vincent Lejeune960a6222013-07-19 21:45:06 +00001602 SHOWNEWBLK(CloneMBB, "result of Cloned block: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001603
Vincent Lejeune960a6222013-07-19 21:45:06 +00001604 return CloneMBB;
1605}
Tom Stellard75aadc22012-12-11 21:25:42 +00001606
Vincent Lejeune960a6222013-07-19 21:45:06 +00001607void AMDGPUCFGStructurizer::migrateInstruction(MachineBasicBlock *SrcMBB,
1608 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I) {
1609 MachineBasicBlock::iterator SpliceEnd;
Tom Stellard75aadc22012-12-11 21:25:42 +00001610 //look for the input branchinstr, not the AMDGPU branchinstr
Vincent Lejeune960a6222013-07-19 21:45:06 +00001611 MachineInstr *BranchMI = getNormalBlockBranchInstr(SrcMBB);
1612 if (!BranchMI) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001613 DEBUG(
1614 dbgs() << "migrateInstruction don't see branch instr\n" ;
1615 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001616 SpliceEnd = SrcMBB->end();
Tom Stellard75aadc22012-12-11 21:25:42 +00001617 } else {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001618 DEBUG(dbgs() << "migrateInstruction see branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001619 SpliceEnd = BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001620 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001621 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001622 dbgs() << "migrateInstruction before splice dstSize = " << DstMBB->size()
1623 << "srcSize = " << SrcMBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001624 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001625
1626 //splice insert before insertPos
Vincent Lejeune960a6222013-07-19 21:45:06 +00001627 DstMBB->splice(I, SrcMBB, SrcMBB->begin(), SpliceEnd);
Tom Stellard75aadc22012-12-11 21:25:42 +00001628
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001629 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001630 dbgs() << "migrateInstruction after splice dstSize = " << DstMBB->size()
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001631 << "srcSize = " << SrcMBB->size() << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001632 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001633}
Tom Stellard75aadc22012-12-11 21:25:42 +00001634
Vincent Lejeune960a6222013-07-19 21:45:06 +00001635MachineBasicBlock *
1636AMDGPUCFGStructurizer::normalizeInfiniteLoopExit(MachineLoop* LoopRep) {
1637 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1638 MachineBasicBlock *LoopLatch = LoopRep->getLoopLatch();
Tom Stellard75aadc22012-12-11 21:25:42 +00001639
Vincent Lejeune960a6222013-07-19 21:45:06 +00001640 if (!LoopHeader || !LoopLatch)
Craig Topper062a2ba2014-04-25 05:30:21 +00001641 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001642 MachineInstr *BranchMI = getLoopendBlockBranchInstr(LoopLatch);
1643 // Is LoopRep an infinite loop ?
1644 if (!BranchMI || !isUncondBranch(BranchMI))
Craig Topper062a2ba2014-04-25 05:30:21 +00001645 return nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001646
Vincent Lejeune960a6222013-07-19 21:45:06 +00001647 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1648 FuncRep->push_back(DummyExitBlk); //insert to function
1649 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock to normalize infiniteLoop: ");
1650 DEBUG(dbgs() << "Old branch instr: " << *BranchMI << "\n";);
Tom Stellard1d46fb22015-07-16 15:38:29 +00001651 LLVMContext &Ctx = LoopHeader->getParent()->getFunction()->getContext();
1652 Ctx.emitError("Extra register needed to handle CFG");
1653 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001654}
Tom Stellard75aadc22012-12-11 21:25:42 +00001655
Vincent Lejeune960a6222013-07-19 21:45:06 +00001656void AMDGPUCFGStructurizer::removeUnconditionalBranch(MachineBasicBlock *MBB) {
1657 MachineInstr *BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001658
1659 // I saw two unconditional branch in one basic block in example
1660 // test_fc_do_while_or.c need to fix the upstream on this to remove the loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001661 while ((BranchMI = getLoopendBlockBranchInstr(MBB))
1662 && isUncondBranch(BranchMI)) {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001663 DEBUG(dbgs() << "Removing uncond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001664 BranchMI->eraseFromParent();
Tom Stellard75aadc22012-12-11 21:25:42 +00001665 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001666}
Tom Stellard75aadc22012-12-11 21:25:42 +00001667
Vincent Lejeune960a6222013-07-19 21:45:06 +00001668void AMDGPUCFGStructurizer::removeRedundantConditionalBranch(
1669 MachineBasicBlock *MBB) {
1670 if (MBB->succ_size() != 2)
1671 return;
1672 MachineBasicBlock *MBB1 = *MBB->succ_begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001673 MachineBasicBlock *MBB2 = *std::next(MBB->succ_begin());
Vincent Lejeune960a6222013-07-19 21:45:06 +00001674 if (MBB1 != MBB2)
1675 return;
Tom Stellard75aadc22012-12-11 21:25:42 +00001676
Vincent Lejeune960a6222013-07-19 21:45:06 +00001677 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
1678 assert(BranchMI && isCondBranch(BranchMI));
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001679 DEBUG(dbgs() << "Removing unneeded cond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001680 BranchMI->eraseFromParent();
1681 SHOWNEWBLK(MBB1, "Removing redundant successor");
Cong Houc1069892015-12-13 09:26:17 +00001682 MBB->removeSuccessor(MBB1, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001683}
Tom Stellard75aadc22012-12-11 21:25:42 +00001684
Vincent Lejeune960a6222013-07-19 21:45:06 +00001685void AMDGPUCFGStructurizer::addDummyExitBlock(
1686 SmallVectorImpl<MachineBasicBlock*> &RetMBB) {
1687 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1688 FuncRep->push_back(DummyExitBlk); //insert to function
1689 insertInstrEnd(DummyExitBlk, AMDGPU::RETURN);
Tom Stellard75aadc22012-12-11 21:25:42 +00001690
Vincent Lejeune960a6222013-07-19 21:45:06 +00001691 for (SmallVectorImpl<MachineBasicBlock *>::iterator It = RetMBB.begin(),
1692 E = RetMBB.end(); It != E; ++It) {
1693 MachineBasicBlock *MBB = *It;
1694 MachineInstr *MI = getReturnInstr(MBB);
1695 if (MI)
1696 MI->eraseFromParent();
1697 MBB->addSuccessor(DummyExitBlk);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001698 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001699 dbgs() << "Add dummyExitBlock to BB" << MBB->getNumber()
Tom Stellard75aadc22012-12-11 21:25:42 +00001700 << " successors\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001701 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001702 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001703 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001704}
1705
Vincent Lejeune960a6222013-07-19 21:45:06 +00001706void AMDGPUCFGStructurizer::removeSuccessor(MachineBasicBlock *MBB) {
1707 while (MBB->succ_size())
1708 MBB->removeSuccessor(*MBB->succ_begin());
Tom Stellard75aadc22012-12-11 21:25:42 +00001709}
1710
Vincent Lejeune960a6222013-07-19 21:45:06 +00001711void AMDGPUCFGStructurizer::recordSccnum(MachineBasicBlock *MBB,
1712 int SccNum) {
1713 BlockInformation *&srcBlkInfo = BlockInfoMap[MBB];
1714 if (!srcBlkInfo)
1715 srcBlkInfo = new BlockInformation();
1716 srcBlkInfo->SccNum = SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +00001717}
1718
Vincent Lejeune960a6222013-07-19 21:45:06 +00001719void AMDGPUCFGStructurizer::retireBlock(MachineBasicBlock *MBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001720 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001721 dbgs() << "Retiring BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001722 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001723
Vincent Lejeune960a6222013-07-19 21:45:06 +00001724 BlockInformation *&SrcBlkInfo = BlockInfoMap[MBB];
Tom Stellard75aadc22012-12-11 21:25:42 +00001725
Vincent Lejeune960a6222013-07-19 21:45:06 +00001726 if (!SrcBlkInfo)
1727 SrcBlkInfo = new BlockInformation();
Tom Stellard75aadc22012-12-11 21:25:42 +00001728
Vincent Lejeune960a6222013-07-19 21:45:06 +00001729 SrcBlkInfo->IsRetired = true;
1730 assert(MBB->succ_size() == 0 && MBB->pred_size() == 0
Tom Stellard75aadc22012-12-11 21:25:42 +00001731 && "can't retire block yet");
1732}
1733
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}