blob: d150984f882a33aa6dab42a6c0e93c8795c64ab2 [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"
Eugene Zelenko06f90ef2017-01-21 01:34:25 +000027#include "llvm/CodeGen/MachineJumpTableInfo.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000028#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000029#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000030#include "llvm/CodeGen/MachinePostDominators.h"
Tom Stellard75aadc22012-12-11 21:25:42 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000032#include "llvm/CodeGen/MachineValueType.h"
33#include "llvm/IR/DebugLoc.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/Pass.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000036#include "llvm/Support/Debug.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000037#include "llvm/Support/ErrorHandling.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000038#include "llvm/Support/raw_ostream.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000039#include <cassert>
40#include <cstddef>
Benjamin Kramer799003b2015-03-23 19:32:43 +000041#include <deque>
Eugene Zelenko66203762017-01-21 00:53:49 +000042#include <iterator>
43#include <map>
44#include <utility>
45#include <vector>
Tom Stellard75aadc22012-12-11 21:25:42 +000046
47using namespace llvm;
48
Chandler Carruth84e68b22014-04-22 02:41:26 +000049#define DEBUG_TYPE "structcfg"
50
Tom Stellarda6c6e1b2013-06-07 20:37:48 +000051#define DEFAULT_VEC_SLOTS 8
52
Tom Stellard75aadc22012-12-11 21:25:42 +000053// TODO: move-begin.
54
55//===----------------------------------------------------------------------===//
56//
57// Statistics for CFGStructurizer.
58//
59//===----------------------------------------------------------------------===//
60
61STATISTIC(numSerialPatternMatch, "CFGStructurizer number of serial pattern "
62 "matched");
63STATISTIC(numIfPatternMatch, "CFGStructurizer number of if pattern "
64 "matched");
Tom Stellard75aadc22012-12-11 21:25:42 +000065STATISTIC(numClonedBlock, "CFGStructurizer cloned blocks");
66STATISTIC(numClonedInstr, "CFGStructurizer cloned instructions");
67
Tom Stellardf2ba9722013-12-11 17:51:47 +000068namespace llvm {
Eugene Zelenko66203762017-01-21 00:53:49 +000069
Tom Stellardf2ba9722013-12-11 17:51:47 +000070 void initializeAMDGPUCFGStructurizerPass(PassRegistry&);
Eugene Zelenko66203762017-01-21 00:53:49 +000071
72} // end namespace llvm
73
74namespace {
Tom Stellardf2ba9722013-12-11 17:51:47 +000075
Tom Stellard75aadc22012-12-11 21:25:42 +000076//===----------------------------------------------------------------------===//
77//
78// Miscellaneous utility for CFGStructurizer.
79//
80//===----------------------------------------------------------------------===//
Eugene Zelenko66203762017-01-21 00:53:49 +000081
Tom Stellard75aadc22012-12-11 21:25:42 +000082#define SHOWNEWINSTR(i) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000083 DEBUG(dbgs() << "New instr: " << *i << "\n");
Tom Stellard75aadc22012-12-11 21:25:42 +000084
85#define SHOWNEWBLK(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000086DEBUG( \
87 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
88 dbgs() << "\n"; \
89);
Tom Stellard75aadc22012-12-11 21:25:42 +000090
91#define SHOWBLK_DETAIL(b, msg) \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000092DEBUG( \
Tom Stellard75aadc22012-12-11 21:25:42 +000093 if (b) { \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000094 dbgs() << msg << "BB" << b->getNumber() << "size " << b->size(); \
95 b->print(dbgs()); \
96 dbgs() << "\n"; \
Tom Stellard75aadc22012-12-11 21:25:42 +000097 } \
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +000098);
Tom Stellard75aadc22012-12-11 21:25:42 +000099
100#define INVALIDSCCNUM -1
Tom Stellard75aadc22012-12-11 21:25:42 +0000101
102template<class NodeT>
Craig Topperb94011f2013-07-14 04:42:23 +0000103void ReverseVector(SmallVectorImpl<NodeT *> &Src) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000104 size_t sz = Src.size();
105 for (size_t i = 0; i < sz/2; ++i) {
106 NodeT *t = Src[i];
107 Src[i] = Src[sz - i - 1];
108 Src[sz - i - 1] = t;
109 }
110}
111
Tom Stellard75aadc22012-12-11 21:25:42 +0000112//===----------------------------------------------------------------------===//
113//
114// supporting data structure for CFGStructurizer
115//
116//===----------------------------------------------------------------------===//
117
Tom Stellard75aadc22012-12-11 21:25:42 +0000118class BlockInformation {
119public:
Eugene Zelenko66203762017-01-21 00:53:49 +0000120 bool IsRetired = false;
121 int SccNum = INVALIDSCCNUM;
Tom Stellard75aadc22012-12-11 21:25:42 +0000122
Eugene Zelenko66203762017-01-21 00:53:49 +0000123 BlockInformation() = default;
124};
Tom Stellard75aadc22012-12-11 21:25:42 +0000125
126//===----------------------------------------------------------------------===//
127//
128// CFGStructurizer
129//
130//===----------------------------------------------------------------------===//
131
Vincent Lejeune960a6222013-07-19 21:45:06 +0000132class AMDGPUCFGStructurizer : public MachineFunctionPass {
Tom Stellard75aadc22012-12-11 21:25:42 +0000133public:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000134 typedef SmallVector<MachineBasicBlock *, 32> MBBVector;
135 typedef std::map<MachineBasicBlock *, BlockInformation *> MBBInfoMap;
136 typedef std::map<MachineLoop *, MachineBasicBlock *> LoopLandInfoMap;
137
138 enum PathToKind {
Tom Stellard75aadc22012-12-11 21:25:42 +0000139 Not_SinglePath = 0,
140 SinglePath_InPath = 1,
141 SinglePath_NotInPath = 2
Vincent Lejeune960a6222013-07-19 21:45:06 +0000142 };
Tom Stellard75aadc22012-12-11 21:25:42 +0000143
Vincent Lejeune960a6222013-07-19 21:45:06 +0000144 static char ID;
Tom Stellard75aadc22012-12-11 21:25:42 +0000145
Eugene Zelenko66203762017-01-21 00:53:49 +0000146 AMDGPUCFGStructurizer() : MachineFunctionPass(ID) {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000147 initializeAMDGPUCFGStructurizerPass(*PassRegistry::getPassRegistry());
148 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000149
Mehdi Amini117296c2016-10-01 02:56:57 +0000150 StringRef getPassName() const override {
Tom Stellardf2ba9722013-12-11 17:51:47 +0000151 return "AMDGPU Control Flow Graph structurizer Pass";
Vincent Lejeune960a6222013-07-19 21:45:06 +0000152 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000153
Craig Topper5656db42014-04-29 07:57:24 +0000154 void getAnalysisUsage(AnalysisUsage &AU) const override {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000155 AU.addRequired<MachineDominatorTree>();
156 AU.addRequired<MachinePostDominatorTree>();
157 AU.addRequired<MachineLoopInfo>();
Matthias Braun733fe362016-08-24 01:52:46 +0000158 MachineFunctionPass::getAnalysisUsage(AU);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000159 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000160
161 /// Perform the CFG structurization
Vincent Lejeune960a6222013-07-19 21:45:06 +0000162 bool run();
Tom Stellard75aadc22012-12-11 21:25:42 +0000163
164 /// Perform the CFG preparation
Vincent Lejeune960a6222013-07-19 21:45:06 +0000165 /// This step will remove every unconditionnal/dead jump instructions and make
166 /// sure all loops have an exit block
167 bool prepare();
Tom Stellard75aadc22012-12-11 21:25:42 +0000168
Craig Topper5656db42014-04-29 07:57:24 +0000169 bool runOnMachineFunction(MachineFunction &MF) override {
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000170 TII = MF.getSubtarget<R600Subtarget>().getInstrInfo();
Tom Stellardf2ba9722013-12-11 17:51:47 +0000171 TRI = &TII->getRegisterInfo();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000172 DEBUG(MF.dump(););
173 OrderedBlks.clear();
Jan Vesely7a9cca92015-03-13 17:32:46 +0000174 Visited.clear();
Vincent Lejeune960a6222013-07-19 21:45:06 +0000175 FuncRep = &MF;
176 MLI = &getAnalysis<MachineLoopInfo>();
177 DEBUG(dbgs() << "LoopInfo:\n"; PrintLoopinfo(*MLI););
178 MDT = &getAnalysis<MachineDominatorTree>();
Eugene Zelenko66203762017-01-21 00:53:49 +0000179 DEBUG(MDT->print(dbgs(), (const Module*)nullptr););
Vincent Lejeune960a6222013-07-19 21:45:06 +0000180 PDT = &getAnalysis<MachinePostDominatorTree>();
181 DEBUG(PDT->print(dbgs()););
182 prepare();
183 run();
184 DEBUG(MF.dump(););
185 return true;
186 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000187
Vincent Lejeune960a6222013-07-19 21:45:06 +0000188protected:
Vincent Lejeune960a6222013-07-19 21:45:06 +0000189 MachineDominatorTree *MDT;
190 MachinePostDominatorTree *PDT;
191 MachineLoopInfo *MLI;
Eugene Zelenko66203762017-01-21 00:53:49 +0000192 const R600InstrInfo *TII = nullptr;
193 const R600RegisterInfo *TRI = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000194
Vincent Lejeune960a6222013-07-19 21:45:06 +0000195 // PRINT FUNCTIONS
196 /// Print the ordered Blocks.
197 void printOrderedBlocks() const {
198 size_t i = 0;
199 for (MBBVector::const_iterator iterBlk = OrderedBlks.begin(),
200 iterBlkEnd = OrderedBlks.end(); iterBlk != iterBlkEnd; ++iterBlk, ++i) {
201 dbgs() << "BB" << (*iterBlk)->getNumber();
202 dbgs() << "(" << getSCCNum(*iterBlk) << "," << (*iterBlk)->size() << ")";
203 if (i != 0 && i % 10 == 0) {
204 dbgs() << "\n";
205 } else {
206 dbgs() << " ";
207 }
208 }
209 }
Eugene Zelenko66203762017-01-21 00:53:49 +0000210
Vincent Lejeune960a6222013-07-19 21:45:06 +0000211 static void PrintLoopinfo(const MachineLoopInfo &LoopInfo) {
212 for (MachineLoop::iterator iter = LoopInfo.begin(),
213 iterEnd = LoopInfo.end(); iter != iterEnd; ++iter) {
214 (*iter)->print(dbgs(), 0);
215 }
216 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000217
Vincent Lejeune960a6222013-07-19 21:45:06 +0000218 // UTILITY FUNCTIONS
219 int getSCCNum(MachineBasicBlock *MBB) const;
220 MachineBasicBlock *getLoopLandInfo(MachineLoop *LoopRep) const;
221 bool hasBackEdge(MachineBasicBlock *MBB) const;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000222 bool isRetiredBlock(MachineBasicBlock *MBB) const;
223 bool isActiveLoophead(MachineBasicBlock *MBB) const;
224 PathToKind singlePathTo(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
225 bool AllowSideEntry = true) const;
226 int countActiveBlock(MBBVector::const_iterator It,
227 MBBVector::const_iterator E) const;
228 bool needMigrateBlock(MachineBasicBlock *MBB) const;
229
230 // Utility Functions
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000231 void reversePredicateSetter(MachineBasicBlock::iterator I,
232 MachineBasicBlock &MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000233 /// Compute the reversed DFS post order of Blocks
234 void orderBlocks(MachineFunction *MF);
235
Alp Tokercb402912014-01-24 17:20:08 +0000236 // Function originally from CFGStructTraits
Vincent Lejeune960a6222013-07-19 21:45:06 +0000237 void insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000238 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000239 MachineInstr *insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000240 const DebugLoc &DL = DebugLoc());
Vincent Lejeune960a6222013-07-19 21:45:06 +0000241 MachineInstr *insertInstrBefore(MachineBasicBlock::iterator I, int NewOpcode);
242 void insertCondBranchBefore(MachineBasicBlock::iterator I, int NewOpcode,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000243 const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000244 void insertCondBranchBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000245 MachineBasicBlock::iterator I, int NewOpcode,
246 int RegNum, const DebugLoc &DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000247 static int getBranchNzeroOpcode(int OldOpcode);
248 static int getBranchZeroOpcode(int OldOpcode);
249 static int getContinueNzeroOpcode(int OldOpcode);
250 static int getContinueZeroOpcode(int OldOpcode);
251 static MachineBasicBlock *getTrueBranch(MachineInstr *MI);
252 static void setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB);
253 static MachineBasicBlock *getFalseBranch(MachineBasicBlock *MBB,
254 MachineInstr *MI);
255 static bool isCondBranch(MachineInstr *MI);
256 static bool isUncondBranch(MachineInstr *MI);
257 static DebugLoc getLastDebugLocInBB(MachineBasicBlock *MBB);
258 static MachineInstr *getNormalBlockBranchInstr(MachineBasicBlock *MBB);
259 /// The correct naming for this is getPossibleLoopendBlockBranchInstr.
260 ///
261 /// BB with backward-edge could have move instructions after the branch
262 /// instruction. Such move instruction "belong to" the loop backward-edge.
263 MachineInstr *getLoopendBlockBranchInstr(MachineBasicBlock *MBB);
264 static MachineInstr *getReturnInstr(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000265 static bool isReturnBlock(MachineBasicBlock *MBB);
266 static void cloneSuccessorList(MachineBasicBlock *DstMBB,
267 MachineBasicBlock *SrcMBB) ;
268 static MachineBasicBlock *clone(MachineBasicBlock *MBB);
269 /// MachineBasicBlock::ReplaceUsesOfBlockWith doesn't serve the purpose
270 /// because the AMDGPU instruction is not recognized as terminator fix this
271 /// and retire this routine
272 void replaceInstrUseOfBlockWith(MachineBasicBlock *SrcMBB,
273 MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk);
274 static void wrapup(MachineBasicBlock *MBB);
275
Vincent Lejeune960a6222013-07-19 21:45:06 +0000276 int patternMatch(MachineBasicBlock *MBB);
277 int patternMatchGroup(MachineBasicBlock *MBB);
278 int serialPatternMatch(MachineBasicBlock *MBB);
279 int ifPatternMatch(MachineBasicBlock *MBB);
280 int loopendPatternMatch();
281 int mergeLoop(MachineLoop *LoopRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000282
Vincent Lejeune960a6222013-07-19 21:45:06 +0000283 /// return true iff src1Blk->succ_size() == 0 && src1Blk and src2Blk are in
284 /// the same loop with LoopLandInfo without explicitly keeping track of
285 /// loopContBlks and loopBreakBlks, this is a method to get the information.
286 bool isSameloopDetachedContbreak(MachineBasicBlock *Src1MBB,
287 MachineBasicBlock *Src2MBB);
288 int handleJumpintoIf(MachineBasicBlock *HeadMBB,
289 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
290 int handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
291 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB);
292 int improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
293 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
294 MachineBasicBlock **LandMBBPtr);
295 void showImproveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
296 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
297 MachineBasicBlock *LandMBB, bool Detail = false);
298 int cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
299 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB);
300 void mergeSerialBlock(MachineBasicBlock *DstMBB,
301 MachineBasicBlock *SrcMBB);
302
303 void mergeIfthenelseBlock(MachineInstr *BranchMI,
304 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
305 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB);
306 void mergeLooplandBlock(MachineBasicBlock *DstMBB,
307 MachineBasicBlock *LandMBB);
308 void mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
309 MachineBasicBlock *LandMBB);
310 void settleLoopcontBlock(MachineBasicBlock *ContingMBB,
311 MachineBasicBlock *ContMBB);
312 /// normalizeInfiniteLoopExit change
313 /// B1:
314 /// uncond_br LoopHeader
315 ///
316 /// to
317 /// B1:
318 /// cond_br 1 LoopHeader dummyExit
319 /// and return the newly added dummy exit block
320 MachineBasicBlock *normalizeInfiniteLoopExit(MachineLoop *LoopRep);
321 void removeUnconditionalBranch(MachineBasicBlock *MBB);
322 /// Remove duplicate branches instructions in a block.
323 /// For instance
324 /// B0:
325 /// cond_br X B1 B2
326 /// cond_br X B1 B2
327 /// is transformed to
328 /// B0:
329 /// cond_br X B1 B2
330 void removeRedundantConditionalBranch(MachineBasicBlock *MBB);
331 void addDummyExitBlock(SmallVectorImpl<MachineBasicBlock *> &RetMBB);
332 void removeSuccessor(MachineBasicBlock *MBB);
333 MachineBasicBlock *cloneBlockForPredecessor(MachineBasicBlock *MBB,
334 MachineBasicBlock *PredMBB);
335 void migrateInstruction(MachineBasicBlock *SrcMBB,
336 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I);
337 void recordSccnum(MachineBasicBlock *MBB, int SCCNum);
338 void retireBlock(MachineBasicBlock *MBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000339
Vincent Lejeune960a6222013-07-19 21:45:06 +0000340private:
341 MBBInfoMap BlockInfoMap;
342 LoopLandInfoMap LLInfoMap;
343 std::map<MachineLoop *, bool> Visited;
344 MachineFunction *FuncRep;
345 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> OrderedBlks;
346};
347
Eugene Zelenko66203762017-01-21 00:53:49 +0000348char AMDGPUCFGStructurizer::ID = 0;
349
350} // end anonymous namespace
351
Vincent Lejeune960a6222013-07-19 21:45:06 +0000352int AMDGPUCFGStructurizer::getSCCNum(MachineBasicBlock *MBB) const {
353 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
354 if (It == BlockInfoMap.end())
355 return INVALIDSCCNUM;
356 return (*It).second->SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +0000357}
358
Vincent Lejeune960a6222013-07-19 21:45:06 +0000359MachineBasicBlock *AMDGPUCFGStructurizer::getLoopLandInfo(MachineLoop *LoopRep)
360 const {
361 LoopLandInfoMap::const_iterator It = LLInfoMap.find(LoopRep);
362 if (It == LLInfoMap.end())
Craig Topper062a2ba2014-04-25 05:30:21 +0000363 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000364 return (*It).second;
365}
366
367bool AMDGPUCFGStructurizer::hasBackEdge(MachineBasicBlock *MBB) const {
368 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
369 if (!LoopRep)
370 return false;
371 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
372 return MBB->isSuccessor(LoopHeader);
373}
374
Vincent Lejeune960a6222013-07-19 21:45:06 +0000375bool AMDGPUCFGStructurizer::isRetiredBlock(MachineBasicBlock *MBB) const {
376 MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB);
377 if (It == BlockInfoMap.end())
378 return false;
379 return (*It).second->IsRetired;
380}
381
382bool AMDGPUCFGStructurizer::isActiveLoophead(MachineBasicBlock *MBB) const {
383 MachineLoop *LoopRep = MLI->getLoopFor(MBB);
384 while (LoopRep && LoopRep->getHeader() == MBB) {
385 MachineBasicBlock *LoopLand = getLoopLandInfo(LoopRep);
386 if(!LoopLand)
387 return true;
388 if (!isRetiredBlock(LoopLand))
389 return true;
390 LoopRep = LoopRep->getParentLoop();
391 }
392 return false;
393}
Eugene Zelenko66203762017-01-21 00:53:49 +0000394
Vincent Lejeune960a6222013-07-19 21:45:06 +0000395AMDGPUCFGStructurizer::PathToKind AMDGPUCFGStructurizer::singlePathTo(
396 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB,
397 bool AllowSideEntry) const {
398 assert(DstMBB);
399 if (SrcMBB == DstMBB)
400 return SinglePath_InPath;
401 while (SrcMBB && SrcMBB->succ_size() == 1) {
402 SrcMBB = *SrcMBB->succ_begin();
403 if (SrcMBB == DstMBB)
404 return SinglePath_InPath;
405 if (!AllowSideEntry && SrcMBB->pred_size() > 1)
406 return Not_SinglePath;
407 }
408 if (SrcMBB && SrcMBB->succ_size()==0)
409 return SinglePath_NotInPath;
410 return Not_SinglePath;
411}
412
413int AMDGPUCFGStructurizer::countActiveBlock(MBBVector::const_iterator It,
414 MBBVector::const_iterator E) const {
415 int Count = 0;
416 while (It != E) {
417 if (!isRetiredBlock(*It))
418 ++Count;
419 ++It;
420 }
421 return Count;
422}
423
424bool AMDGPUCFGStructurizer::needMigrateBlock(MachineBasicBlock *MBB) const {
425 unsigned BlockSizeThreshold = 30;
426 unsigned CloneInstrThreshold = 100;
427 bool MultiplePreds = MBB && (MBB->pred_size() > 1);
428
429 if(!MultiplePreds)
430 return false;
431 unsigned BlkSize = MBB->size();
432 return ((BlkSize > BlockSizeThreshold) &&
433 (BlkSize * (MBB->pred_size() - 1) > CloneInstrThreshold));
434}
435
436void AMDGPUCFGStructurizer::reversePredicateSetter(
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000437 MachineBasicBlock::iterator I, MachineBasicBlock &MBB) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000438 assert(I.isValid() && "Expected valid iterator");
Duncan P. N. Exon Smith221847e2016-07-08 19:00:17 +0000439 for (;; --I) {
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000440 if (I == MBB.end())
441 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000442 if (I->getOpcode() == AMDGPU::PRED_X) {
Duncan P. N. Exon Smithf197b1f2016-08-12 05:05:36 +0000443 switch (I->getOperand(2).getImm()) {
Matt Arsenault44f6d692016-08-13 01:43:46 +0000444 case AMDGPU::PRED_SETE_INT:
445 I->getOperand(2).setImm(AMDGPU::PRED_SETNE_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000446 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000447 case AMDGPU::PRED_SETNE_INT:
448 I->getOperand(2).setImm(AMDGPU::PRED_SETE_INT);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000449 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000450 case AMDGPU::PRED_SETE:
451 I->getOperand(2).setImm(AMDGPU::PRED_SETNE);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000452 return;
Matt Arsenault44f6d692016-08-13 01:43:46 +0000453 case AMDGPU::PRED_SETNE:
454 I->getOperand(2).setImm(AMDGPU::PRED_SETE);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000455 return;
456 default:
457 llvm_unreachable("PRED_X Opcode invalid!");
458 }
459 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000460 }
461}
462
Vincent Lejeune960a6222013-07-19 21:45:06 +0000463void AMDGPUCFGStructurizer::insertInstrEnd(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000464 int NewOpcode, const DebugLoc &DL) {
465 MachineInstr *MI =
466 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000467 MBB->push_back(MI);
468 //assume the instruction doesn't take any reg operand ...
469 SHOWNEWINSTR(MI);
470}
Tom Stellard75aadc22012-12-11 21:25:42 +0000471
Vincent Lejeune960a6222013-07-19 21:45:06 +0000472MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(MachineBasicBlock *MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000473 int NewOpcode,
474 const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000475 MachineInstr *MI =
476 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL);
477 if (MBB->begin() != MBB->end())
478 MBB->insert(MBB->begin(), MI);
479 else
480 MBB->push_back(MI);
481 SHOWNEWINSTR(MI);
482 return MI;
483}
484
485MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(
486 MachineBasicBlock::iterator I, int NewOpcode) {
487 MachineInstr *OldMI = &(*I);
488 MachineBasicBlock *MBB = OldMI->getParent();
489 MachineInstr *NewMBB =
490 MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DebugLoc());
491 MBB->insert(I, NewMBB);
492 //assume the instruction doesn't take any reg operand ...
493 SHOWNEWINSTR(NewMBB);
494 return NewMBB;
495}
496
497void AMDGPUCFGStructurizer::insertCondBranchBefore(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000498 MachineBasicBlock::iterator I, int NewOpcode, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000499 MachineInstr *OldMI = &(*I);
500 MachineBasicBlock *MBB = OldMI->getParent();
501 MachineFunction *MF = MBB->getParent();
502 MachineInstr *NewMI = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
503 MBB->insert(I, NewMI);
504 MachineInstrBuilder MIB(*MF, NewMI);
505 MIB.addReg(OldMI->getOperand(1).getReg(), false);
506 SHOWNEWINSTR(NewMI);
507 //erase later oldInstr->eraseFromParent();
508}
509
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000510void AMDGPUCFGStructurizer::insertCondBranchBefore(
511 MachineBasicBlock *blk, MachineBasicBlock::iterator I, int NewOpcode,
512 int RegNum, const DebugLoc &DL) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000513 MachineFunction *MF = blk->getParent();
514 MachineInstr *NewInstr = MF->CreateMachineInstr(TII->get(NewOpcode), DL);
515 //insert before
516 blk->insert(I, NewInstr);
517 MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false);
518 SHOWNEWINSTR(NewInstr);
519}
520
Vincent Lejeune960a6222013-07-19 21:45:06 +0000521int AMDGPUCFGStructurizer::getBranchNzeroOpcode(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_LOGICALNZ_f32;
527 default: llvm_unreachable("internal error");
528 }
529 return -1;
530}
531
532int AMDGPUCFGStructurizer::getBranchZeroOpcode(int OldOpcode) {
533 switch(OldOpcode) {
534 case AMDGPU::JUMP_COND:
535 case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET;
536 case AMDGPU::BRANCH_COND_i32:
537 case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALZ_f32;
538 default: llvm_unreachable("internal error");
539 }
540 return -1;
541}
542
543int AMDGPUCFGStructurizer::getContinueNzeroOpcode(int OldOpcode) {
544 switch(OldOpcode) {
545 case AMDGPU::JUMP_COND:
546 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALNZ_i32;
547 default: llvm_unreachable("internal error");
548 };
549 return -1;
550}
551
552int AMDGPUCFGStructurizer::getContinueZeroOpcode(int OldOpcode) {
553 switch(OldOpcode) {
554 case AMDGPU::JUMP_COND:
555 case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALZ_i32;
556 default: llvm_unreachable("internal error");
557 }
558 return -1;
559}
560
561MachineBasicBlock *AMDGPUCFGStructurizer::getTrueBranch(MachineInstr *MI) {
562 return MI->getOperand(0).getMBB();
563}
564
565void AMDGPUCFGStructurizer::setTrueBranch(MachineInstr *MI,
566 MachineBasicBlock *MBB) {
567 MI->getOperand(0).setMBB(MBB);
568}
569
570MachineBasicBlock *
571AMDGPUCFGStructurizer::getFalseBranch(MachineBasicBlock *MBB,
572 MachineInstr *MI) {
573 assert(MBB->succ_size() == 2);
574 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
575 MachineBasicBlock::succ_iterator It = MBB->succ_begin();
576 MachineBasicBlock::succ_iterator Next = It;
577 ++Next;
578 return (*It == TrueBranch) ? *Next : *It;
579}
580
581bool AMDGPUCFGStructurizer::isCondBranch(MachineInstr *MI) {
582 switch (MI->getOpcode()) {
583 case AMDGPU::JUMP_COND:
584 case AMDGPU::BRANCH_COND_i32:
585 case AMDGPU::BRANCH_COND_f32: return true;
586 default:
587 return false;
588 }
589 return false;
590}
591
592bool AMDGPUCFGStructurizer::isUncondBranch(MachineInstr *MI) {
593 switch (MI->getOpcode()) {
594 case AMDGPU::JUMP:
595 case AMDGPU::BRANCH:
596 return true;
597 default:
598 return false;
599 }
600 return false;
601}
602
603DebugLoc AMDGPUCFGStructurizer::getLastDebugLocInBB(MachineBasicBlock *MBB) {
604 //get DebugLoc from the first MachineBasicBlock instruction with debug info
605 DebugLoc DL;
606 for (MachineBasicBlock::iterator It = MBB->begin(); It != MBB->end();
607 ++It) {
608 MachineInstr *instr = &(*It);
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000609 if (instr->getDebugLoc())
Vincent Lejeune960a6222013-07-19 21:45:06 +0000610 DL = instr->getDebugLoc();
611 }
612 return DL;
613}
614
615MachineInstr *AMDGPUCFGStructurizer::getNormalBlockBranchInstr(
616 MachineBasicBlock *MBB) {
617 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
618 MachineInstr *MI = &*It;
619 if (MI && (isCondBranch(MI) || isUncondBranch(MI)))
620 return MI;
Craig Topper062a2ba2014-04-25 05:30:21 +0000621 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000622}
623
624MachineInstr *AMDGPUCFGStructurizer::getLoopendBlockBranchInstr(
625 MachineBasicBlock *MBB) {
626 for (MachineBasicBlock::reverse_iterator It = MBB->rbegin(), E = MBB->rend();
627 It != E; ++It) {
628 // FIXME: Simplify
629 MachineInstr *MI = &*It;
630 if (MI) {
631 if (isCondBranch(MI) || isUncondBranch(MI))
632 return MI;
633 else if (!TII->isMov(MI->getOpcode()))
634 break;
635 }
636 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000637 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000638}
639
640MachineInstr *AMDGPUCFGStructurizer::getReturnInstr(MachineBasicBlock *MBB) {
641 MachineBasicBlock::reverse_iterator It = MBB->rbegin();
642 if (It != MBB->rend()) {
643 MachineInstr *instr = &(*It);
644 if (instr->getOpcode() == AMDGPU::RETURN)
645 return instr;
646 }
Craig Topper062a2ba2014-04-25 05:30:21 +0000647 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000648}
649
Vincent Lejeune960a6222013-07-19 21:45:06 +0000650bool AMDGPUCFGStructurizer::isReturnBlock(MachineBasicBlock *MBB) {
651 MachineInstr *MI = getReturnInstr(MBB);
652 bool IsReturn = (MBB->succ_size() == 0);
653 if (MI)
654 assert(IsReturn);
655 else if (IsReturn)
656 DEBUG(
657 dbgs() << "BB" << MBB->getNumber()
658 <<" is return block without RETURN instr\n";);
659 return IsReturn;
660}
661
662void AMDGPUCFGStructurizer::cloneSuccessorList(MachineBasicBlock *DstMBB,
663 MachineBasicBlock *SrcMBB) {
664 for (MachineBasicBlock::succ_iterator It = SrcMBB->succ_begin(),
665 iterEnd = SrcMBB->succ_end(); It != iterEnd; ++It)
666 DstMBB->addSuccessor(*It); // *iter's predecessor is also taken care of
667}
668
669MachineBasicBlock *AMDGPUCFGStructurizer::clone(MachineBasicBlock *MBB) {
670 MachineFunction *Func = MBB->getParent();
671 MachineBasicBlock *NewMBB = Func->CreateMachineBasicBlock();
672 Func->push_back(NewMBB); //insert to function
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000673 for (const MachineInstr &It : *MBB)
674 NewMBB->push_back(Func->CloneMachineInstr(&It));
Vincent Lejeune960a6222013-07-19 21:45:06 +0000675 return NewMBB;
676}
677
678void AMDGPUCFGStructurizer::replaceInstrUseOfBlockWith(
679 MachineBasicBlock *SrcMBB, MachineBasicBlock *OldMBB,
680 MachineBasicBlock *NewBlk) {
681 MachineInstr *BranchMI = getLoopendBlockBranchInstr(SrcMBB);
682 if (BranchMI && isCondBranch(BranchMI) &&
683 getTrueBranch(BranchMI) == OldMBB)
684 setTrueBranch(BranchMI, NewBlk);
685}
686
687void AMDGPUCFGStructurizer::wrapup(MachineBasicBlock *MBB) {
688 assert((!MBB->getParent()->getJumpTableInfo()
689 || MBB->getParent()->getJumpTableInfo()->isEmpty())
690 && "found a jump table");
691
692 //collect continue right before endloop
693 SmallVector<MachineInstr *, DEFAULT_VEC_SLOTS> ContInstr;
694 MachineBasicBlock::iterator Pre = MBB->begin();
695 MachineBasicBlock::iterator E = MBB->end();
696 MachineBasicBlock::iterator It = Pre;
697 while (It != E) {
698 if (Pre->getOpcode() == AMDGPU::CONTINUE
699 && It->getOpcode() == AMDGPU::ENDLOOP)
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000700 ContInstr.push_back(&*Pre);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000701 Pre = It;
702 ++It;
703 }
704
705 //delete continue right before endloop
706 for (unsigned i = 0; i < ContInstr.size(); ++i)
707 ContInstr[i]->eraseFromParent();
708
709 // TODO to fix up jump table so later phase won't be confused. if
710 // (jumpTableInfo->isEmpty() == false) { need to clean the jump table, but
711 // there isn't such an interface yet. alternatively, replace all the other
712 // blocks in the jump table with the entryBlk //}
Vincent Lejeune960a6222013-07-19 21:45:06 +0000713}
714
Vincent Lejeune960a6222013-07-19 21:45:06 +0000715bool AMDGPUCFGStructurizer::prepare() {
716 bool Changed = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000717
718 //FIXME: if not reducible flow graph, make it so ???
719
Vincent Lejeune960a6222013-07-19 21:45:06 +0000720 DEBUG(dbgs() << "AMDGPUCFGStructurizer::prepare\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +0000721
Vincent Lejeune960a6222013-07-19 21:45:06 +0000722 orderBlocks(FuncRep);
Tom Stellard75aadc22012-12-11 21:25:42 +0000723
Vincent Lejeune960a6222013-07-19 21:45:06 +0000724 SmallVector<MachineBasicBlock *, DEFAULT_VEC_SLOTS> RetBlks;
Tom Stellard75aadc22012-12-11 21:25:42 +0000725
Vincent Lejeune960a6222013-07-19 21:45:06 +0000726 // Add an ExitBlk to loop that don't have one
727 for (MachineLoopInfo::iterator It = MLI->begin(),
728 E = MLI->end(); It != E; ++It) {
729 MachineLoop *LoopRep = (*It);
730 MBBVector ExitingMBBs;
731 LoopRep->getExitingBlocks(ExitingMBBs);
Tom Stellard75aadc22012-12-11 21:25:42 +0000732
Vincent Lejeune960a6222013-07-19 21:45:06 +0000733 if (ExitingMBBs.size() == 0) {
734 MachineBasicBlock* DummyExitBlk = normalizeInfiniteLoopExit(LoopRep);
735 if (DummyExitBlk)
736 RetBlks.push_back(DummyExitBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000737 }
738 }
739
740 // Remove unconditional branch instr.
741 // Add dummy exit block iff there are multiple returns.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000742 for (SmallVectorImpl<MachineBasicBlock *>::const_iterator
743 It = OrderedBlks.begin(), E = OrderedBlks.end(); It != E; ++It) {
744 MachineBasicBlock *MBB = *It;
745 removeUnconditionalBranch(MBB);
746 removeRedundantConditionalBranch(MBB);
747 if (isReturnBlock(MBB)) {
748 RetBlks.push_back(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000749 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000750 assert(MBB->succ_size() <= 2);
Tom Stellard75aadc22012-12-11 21:25:42 +0000751 }
752
Vincent Lejeune960a6222013-07-19 21:45:06 +0000753 if (RetBlks.size() >= 2) {
754 addDummyExitBlock(RetBlks);
755 Changed = true;
756 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000757
Vincent Lejeune960a6222013-07-19 21:45:06 +0000758 return Changed;
759}
760
761bool AMDGPUCFGStructurizer::run() {
Tom Stellard75aadc22012-12-11 21:25:42 +0000762 //Assume reducible CFG...
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000763 DEBUG(dbgs() << "AMDGPUCFGStructurizer::run\n");
Tom Stellard75aadc22012-12-11 21:25:42 +0000764
Tom Stellard75aadc22012-12-11 21:25:42 +0000765#ifdef STRESSTEST
766 //Use the worse block ordering to test the algorithm.
767 ReverseVector(orderedBlks);
768#endif
769
Vincent Lejeune960a6222013-07-19 21:45:06 +0000770 DEBUG(dbgs() << "Ordered blocks:\n"; printOrderedBlocks(););
771 int NumIter = 0;
772 bool Finish = false;
773 MachineBasicBlock *MBB;
774 bool MakeProgress = false;
775 int NumRemainedBlk = countActiveBlock(OrderedBlks.begin(),
776 OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000777
778 do {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000779 ++NumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000780 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000781 dbgs() << "numIter = " << NumIter
782 << ", numRemaintedBlk = " << NumRemainedBlk << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000783 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000784
Vincent Lejeune960a6222013-07-19 21:45:06 +0000785 SmallVectorImpl<MachineBasicBlock *>::const_iterator It =
786 OrderedBlks.begin();
787 SmallVectorImpl<MachineBasicBlock *>::const_iterator E =
788 OrderedBlks.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000789
Vincent Lejeune960a6222013-07-19 21:45:06 +0000790 SmallVectorImpl<MachineBasicBlock *>::const_iterator SccBeginIter =
791 It;
Craig Topper062a2ba2014-04-25 05:30:21 +0000792 MachineBasicBlock *SccBeginMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000793 int SccNumBlk = 0; // The number of active blocks, init to a
Tom Stellard75aadc22012-12-11 21:25:42 +0000794 // maximum possible number.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000795 int SccNumIter; // Number of iteration in this SCC.
Tom Stellard75aadc22012-12-11 21:25:42 +0000796
Vincent Lejeune960a6222013-07-19 21:45:06 +0000797 while (It != E) {
798 MBB = *It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000799
Vincent Lejeune960a6222013-07-19 21:45:06 +0000800 if (!SccBeginMBB) {
801 SccBeginIter = It;
802 SccBeginMBB = MBB;
803 SccNumIter = 0;
804 SccNumBlk = NumRemainedBlk; // Init to maximum possible number.
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000805 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000806 dbgs() << "start processing SCC" << getSCCNum(SccBeginMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000807 dbgs() << "\n";
808 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000809 }
810
Vincent Lejeune960a6222013-07-19 21:45:06 +0000811 if (!isRetiredBlock(MBB))
812 patternMatch(MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +0000813
Vincent Lejeune960a6222013-07-19 21:45:06 +0000814 ++It;
Tom Stellard75aadc22012-12-11 21:25:42 +0000815
Vincent Lejeune960a6222013-07-19 21:45:06 +0000816 bool ContNextScc = true;
817 if (It == E
818 || getSCCNum(SccBeginMBB) != getSCCNum(*It)) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000819 // Just finish one scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000820 ++SccNumIter;
821 int sccRemainedNumBlk = countActiveBlock(SccBeginIter, It);
822 if (sccRemainedNumBlk != 1 && sccRemainedNumBlk >= SccNumBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000823 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000824 dbgs() << "Can't reduce SCC " << getSCCNum(MBB)
825 << ", sccNumIter = " << SccNumIter;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000826 dbgs() << "doesn't make any progress\n";
827 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000828 ContNextScc = true;
829 } else if (sccRemainedNumBlk != 1 && sccRemainedNumBlk < SccNumBlk) {
830 SccNumBlk = sccRemainedNumBlk;
831 It = SccBeginIter;
832 ContNextScc = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000833 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000834 dbgs() << "repeat processing SCC" << getSCCNum(MBB)
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000835 << "sccNumIter = " << SccNumIter << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000836 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000837 } else {
838 // Finish the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000839 ContNextScc = true;
Tom Stellard75aadc22012-12-11 21:25:42 +0000840 }
841 } else {
842 // Continue on next component in the current scc.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000843 ContNextScc = false;
Tom Stellard75aadc22012-12-11 21:25:42 +0000844 }
845
Vincent Lejeune960a6222013-07-19 21:45:06 +0000846 if (ContNextScc)
Craig Topper062a2ba2014-04-25 05:30:21 +0000847 SccBeginMBB = nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +0000848 } //while, "one iteration" over the function.
849
Vincent Lejeune960a6222013-07-19 21:45:06 +0000850 MachineBasicBlock *EntryMBB =
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000851 *GraphTraits<MachineFunction *>::nodes_begin(FuncRep);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000852 if (EntryMBB->succ_size() == 0) {
853 Finish = true;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000854 DEBUG(
855 dbgs() << "Reduce to one block\n";
856 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000857 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000858 int NewnumRemainedBlk
859 = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end());
Tom Stellard75aadc22012-12-11 21:25:42 +0000860 // consider cloned blocks ??
Vincent Lejeune960a6222013-07-19 21:45:06 +0000861 if (NewnumRemainedBlk == 1 || NewnumRemainedBlk < NumRemainedBlk) {
862 MakeProgress = true;
863 NumRemainedBlk = NewnumRemainedBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +0000864 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000865 MakeProgress = false;
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000866 DEBUG(
867 dbgs() << "No progress\n";
868 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000869 }
870 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000871 } while (!Finish && MakeProgress);
Tom Stellard75aadc22012-12-11 21:25:42 +0000872
873 // Misc wrap up to maintain the consistency of the Function representation.
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000874 wrapup(*GraphTraits<MachineFunction *>::nodes_begin(FuncRep));
Tom Stellard75aadc22012-12-11 21:25:42 +0000875
876 // Detach retired Block, release memory.
Vincent Lejeune960a6222013-07-19 21:45:06 +0000877 for (MBBInfoMap::iterator It = BlockInfoMap.begin(), E = BlockInfoMap.end();
878 It != E; ++It) {
879 if ((*It).second && (*It).second->IsRetired) {
880 assert(((*It).first)->getNumber() != -1);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000881 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000882 dbgs() << "Erase BB" << ((*It).first)->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000883 );
Vincent Lejeune960a6222013-07-19 21:45:06 +0000884 (*It).first->eraseFromParent(); //Remove from the parent Function.
Tom Stellard75aadc22012-12-11 21:25:42 +0000885 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000886 delete (*It).second;
Tom Stellard75aadc22012-12-11 21:25:42 +0000887 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000888 BlockInfoMap.clear();
889 LLInfoMap.clear();
Tom Stellard75aadc22012-12-11 21:25:42 +0000890
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000891 if (!Finish) {
892 DEBUG(FuncRep->viewCFG());
Matt Arsenault5de68cb2016-03-02 03:33:55 +0000893 report_fatal_error("IRREDUCIBLE_CFG");
Matt Arsenaultdb8b1d52014-03-24 20:29:02 +0000894 }
Tom Stellard75aadc22012-12-11 21:25:42 +0000895
896 return true;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000897}
Tom Stellard75aadc22012-12-11 21:25:42 +0000898
Vincent Lejeune960a6222013-07-19 21:45:06 +0000899void AMDGPUCFGStructurizer::orderBlocks(MachineFunction *MF) {
900 int SccNum = 0;
901 MachineBasicBlock *MBB;
Duncan P. N. Exon Smith8e661ef2014-02-04 19:19:07 +0000902 for (scc_iterator<MachineFunction *> It = scc_begin(MF); !It.isAtEnd();
903 ++It, ++SccNum) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000904 const std::vector<MachineBasicBlock *> &SccNext = *It;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000905 for (std::vector<MachineBasicBlock *>::const_iterator
906 blockIter = SccNext.begin(), blockEnd = SccNext.end();
Tom Stellard75aadc22012-12-11 21:25:42 +0000907 blockIter != blockEnd; ++blockIter) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000908 MBB = *blockIter;
909 OrderedBlks.push_back(MBB);
910 recordSccnum(MBB, SccNum);
Tom Stellard75aadc22012-12-11 21:25:42 +0000911 }
912 }
913
Daniel Berlin58a6e572017-02-09 20:37:24 +0000914 // walk through all the block in func to check for unreachable
Daniel Berlin73ad5cb2017-02-09 20:37:46 +0000915 for (auto *MBB : nodes(MF)) {
Vincent Lejeune960a6222013-07-19 21:45:06 +0000916 SccNum = getSCCNum(MBB);
917 if (SccNum == INVALIDSCCNUM)
918 dbgs() << "unreachable block BB" << MBB->getNumber() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +0000919 }
Vincent Lejeune960a6222013-07-19 21:45:06 +0000920}
Tom Stellard75aadc22012-12-11 21:25:42 +0000921
Vincent Lejeune960a6222013-07-19 21:45:06 +0000922int AMDGPUCFGStructurizer::patternMatch(MachineBasicBlock *MBB) {
923 int NumMatch = 0;
924 int CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000925
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000926 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000927 dbgs() << "Begin patternMatch BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000928 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000929
Vincent Lejeune960a6222013-07-19 21:45:06 +0000930 while ((CurMatch = patternMatchGroup(MBB)) > 0)
931 NumMatch += CurMatch;
Tom Stellard75aadc22012-12-11 21:25:42 +0000932
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000933 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +0000934 dbgs() << "End patternMatch BB" << MBB->getNumber()
935 << ", numMatch = " << NumMatch << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +0000936 );
Tom Stellard75aadc22012-12-11 21:25:42 +0000937
Vincent Lejeune960a6222013-07-19 21:45:06 +0000938 return NumMatch;
939}
Tom Stellard75aadc22012-12-11 21:25:42 +0000940
Vincent Lejeune960a6222013-07-19 21:45:06 +0000941int AMDGPUCFGStructurizer::patternMatchGroup(MachineBasicBlock *MBB) {
942 int NumMatch = 0;
943 NumMatch += loopendPatternMatch();
944 NumMatch += serialPatternMatch(MBB);
945 NumMatch += ifPatternMatch(MBB);
946 return NumMatch;
947}
Tom Stellard75aadc22012-12-11 21:25:42 +0000948
Vincent Lejeune960a6222013-07-19 21:45:06 +0000949int AMDGPUCFGStructurizer::serialPatternMatch(MachineBasicBlock *MBB) {
950 if (MBB->succ_size() != 1)
Tom Stellard75aadc22012-12-11 21:25:42 +0000951 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000952
Vincent Lejeune960a6222013-07-19 21:45:06 +0000953 MachineBasicBlock *childBlk = *MBB->succ_begin();
954 if (childBlk->pred_size() != 1 || isActiveLoophead(childBlk))
Tom Stellard75aadc22012-12-11 21:25:42 +0000955 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000956
Vincent Lejeune960a6222013-07-19 21:45:06 +0000957 mergeSerialBlock(MBB, childBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +0000958 ++numSerialPatternMatch;
959 return 1;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000960}
Tom Stellard75aadc22012-12-11 21:25:42 +0000961
Vincent Lejeune960a6222013-07-19 21:45:06 +0000962int AMDGPUCFGStructurizer::ifPatternMatch(MachineBasicBlock *MBB) {
Tom Stellard75aadc22012-12-11 21:25:42 +0000963 //two edges
Vincent Lejeune960a6222013-07-19 21:45:06 +0000964 if (MBB->succ_size() != 2)
Tom Stellard75aadc22012-12-11 21:25:42 +0000965 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000966 if (hasBackEdge(MBB))
Tom Stellard75aadc22012-12-11 21:25:42 +0000967 return 0;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000968 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
969 if (!BranchMI)
Tom Stellard75aadc22012-12-11 21:25:42 +0000970 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000971
Vincent Lejeune960a6222013-07-19 21:45:06 +0000972 assert(isCondBranch(BranchMI));
Tom Stellard827ec9b2013-11-18 19:43:38 +0000973 int NumMatch = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000974
Vincent Lejeune960a6222013-07-19 21:45:06 +0000975 MachineBasicBlock *TrueMBB = getTrueBranch(BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000976 NumMatch += serialPatternMatch(TrueMBB);
977 NumMatch += ifPatternMatch(TrueMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000978 MachineBasicBlock *FalseMBB = getFalseBranch(MBB, BranchMI);
Tom Stellard827ec9b2013-11-18 19:43:38 +0000979 NumMatch += serialPatternMatch(FalseMBB);
980 NumMatch += ifPatternMatch(FalseMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +0000981 MachineBasicBlock *LandBlk;
982 int Cloned = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +0000983
Vincent Lejeune960a6222013-07-19 21:45:06 +0000984 assert (!TrueMBB->succ_empty() || !FalseMBB->succ_empty());
Tom Stellard75aadc22012-12-11 21:25:42 +0000985 // TODO: Simplify
Vincent Lejeune960a6222013-07-19 21:45:06 +0000986 if (TrueMBB->succ_size() == 1 && FalseMBB->succ_size() == 1
987 && *TrueMBB->succ_begin() == *FalseMBB->succ_begin()) {
988 // Diamond pattern
989 LandBlk = *TrueMBB->succ_begin();
990 } else if (TrueMBB->succ_size() == 1 && *TrueMBB->succ_begin() == FalseMBB) {
991 // Triangle pattern, false is empty
992 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +0000993 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +0000994 } else if (FalseMBB->succ_size() == 1
995 && *FalseMBB->succ_begin() == TrueMBB) {
996 // Triangle pattern, true is empty
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +0000997 // We reverse the predicate to make a triangle, empty false pattern;
998 std::swap(TrueMBB, FalseMBB);
Hans Wennborg0dd9ed12016-08-13 01:12:49 +0000999 reversePredicateSetter(MBB->end(), *MBB);
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001000 LandBlk = FalseMBB;
Craig Topper062a2ba2014-04-25 05:30:21 +00001001 FalseMBB = nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001002 } else if (FalseMBB->succ_size() == 1
1003 && isSameloopDetachedContbreak(TrueMBB, FalseMBB)) {
1004 LandBlk = *FalseMBB->succ_begin();
1005 } else if (TrueMBB->succ_size() == 1
1006 && isSameloopDetachedContbreak(FalseMBB, TrueMBB)) {
1007 LandBlk = *TrueMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001008 } else {
Tom Stellard827ec9b2013-11-18 19:43:38 +00001009 return NumMatch + handleJumpintoIf(MBB, TrueMBB, FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001010 }
1011
1012 // improveSimpleJumpinfoIf can handle the case where landBlk == NULL but the
1013 // new BB created for landBlk==NULL may introduce new challenge to the
1014 // reduction process.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001015 if (LandBlk &&
1016 ((TrueMBB && TrueMBB->pred_size() > 1)
1017 || (FalseMBB && FalseMBB->pred_size() > 1))) {
1018 Cloned += improveSimpleJumpintoIf(MBB, TrueMBB, FalseMBB, &LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001019 }
1020
Vincent Lejeune960a6222013-07-19 21:45:06 +00001021 if (TrueMBB && TrueMBB->pred_size() > 1) {
1022 TrueMBB = cloneBlockForPredecessor(TrueMBB, MBB);
1023 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001024 }
1025
Vincent Lejeune960a6222013-07-19 21:45:06 +00001026 if (FalseMBB && FalseMBB->pred_size() > 1) {
1027 FalseMBB = cloneBlockForPredecessor(FalseMBB, MBB);
1028 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001029 }
1030
Vincent Lejeune960a6222013-07-19 21:45:06 +00001031 mergeIfthenelseBlock(BranchMI, MBB, TrueMBB, FalseMBB, LandBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001032
1033 ++numIfPatternMatch;
1034
Vincent Lejeune960a6222013-07-19 21:45:06 +00001035 numClonedBlock += Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001036
Tom Stellard827ec9b2013-11-18 19:43:38 +00001037 return 1 + Cloned + NumMatch;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001038}
Tom Stellard75aadc22012-12-11 21:25:42 +00001039
Vincent Lejeune960a6222013-07-19 21:45:06 +00001040int AMDGPUCFGStructurizer::loopendPatternMatch() {
Jan Vesely18b289f2015-03-13 17:32:43 +00001041 std::deque<MachineLoop *> NestedLoops;
1042 for (auto &It: *MLI)
1043 for (MachineLoop *ML : depth_first(It))
1044 NestedLoops.push_front(ML);
David Blaikieceec2bd2014-04-11 01:50:01 +00001045
Eugene Zelenko66203762017-01-21 00:53:49 +00001046 if (NestedLoops.empty())
Tom Stellard75aadc22012-12-11 21:25:42 +00001047 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001048
Jan Vesely18b289f2015-03-13 17:32:43 +00001049 // Process nested loop outside->inside (we did push_front),
1050 // so "continue" to a outside loop won't be mistaken as "break"
1051 // of the current loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001052 int Num = 0;
Jan Vesely18b289f2015-03-13 17:32:43 +00001053 for (MachineLoop *ExaminedLoop : NestedLoops) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001054 if (ExaminedLoop->getNumBlocks() == 0 || Visited[ExaminedLoop])
Tom Stellard75aadc22012-12-11 21:25:42 +00001055 continue;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001056 DEBUG(dbgs() << "Processing:\n"; ExaminedLoop->dump(););
1057 int NumBreak = mergeLoop(ExaminedLoop);
1058 if (NumBreak == -1)
Tom Stellard75aadc22012-12-11 21:25:42 +00001059 break;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001060 Num += NumBreak;
1061 }
1062 return Num;
1063}
Tom Stellard75aadc22012-12-11 21:25:42 +00001064
Vincent Lejeune960a6222013-07-19 21:45:06 +00001065int AMDGPUCFGStructurizer::mergeLoop(MachineLoop *LoopRep) {
1066 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1067 MBBVector ExitingMBBs;
1068 LoopRep->getExitingBlocks(ExitingMBBs);
1069 assert(!ExitingMBBs.empty() && "Infinite Loop not supported");
1070 DEBUG(dbgs() << "Loop has " << ExitingMBBs.size() << " exiting blocks\n";);
1071 // We assume a single ExitBlk
1072 MBBVector ExitBlks;
1073 LoopRep->getExitBlocks(ExitBlks);
1074 SmallPtrSet<MachineBasicBlock *, 2> ExitBlkSet;
1075 for (unsigned i = 0, e = ExitBlks.size(); i < e; ++i)
1076 ExitBlkSet.insert(ExitBlks[i]);
1077 assert(ExitBlkSet.size() == 1);
1078 MachineBasicBlock *ExitBlk = *ExitBlks.begin();
1079 assert(ExitBlk && "Loop has several exit block");
1080 MBBVector LatchBlks;
Daniel Berlin73ad5cb2017-02-09 20:37:46 +00001081 for (auto *LB : inverse_children<MachineBasicBlock*>(LoopHeader))
Daniel Berlin58a6e572017-02-09 20:37:24 +00001082 if (LoopRep->contains(LB))
1083 LatchBlks.push_back(LB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001084
Vincent Lejeune960a6222013-07-19 21:45:06 +00001085 for (unsigned i = 0, e = ExitingMBBs.size(); i < e; ++i)
1086 mergeLoopbreakBlock(ExitingMBBs[i], ExitBlk);
1087 for (unsigned i = 0, e = LatchBlks.size(); i < e; ++i)
1088 settleLoopcontBlock(LatchBlks[i], LoopHeader);
1089 int Match = 0;
1090 do {
1091 Match = 0;
1092 Match += serialPatternMatch(LoopHeader);
1093 Match += ifPatternMatch(LoopHeader);
1094 } while (Match > 0);
1095 mergeLooplandBlock(LoopHeader, ExitBlk);
1096 MachineLoop *ParentLoop = LoopRep->getParentLoop();
1097 if (ParentLoop)
1098 MLI->changeLoopFor(LoopHeader, ParentLoop);
1099 else
1100 MLI->removeBlock(LoopHeader);
1101 Visited[LoopRep] = true;
1102 return 1;
1103}
Tom Stellard75aadc22012-12-11 21:25:42 +00001104
Vincent Lejeune960a6222013-07-19 21:45:06 +00001105bool AMDGPUCFGStructurizer::isSameloopDetachedContbreak(
1106 MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB) {
1107 if (Src1MBB->succ_size() == 0) {
1108 MachineLoop *LoopRep = MLI->getLoopFor(Src1MBB);
1109 if (LoopRep&& LoopRep == MLI->getLoopFor(Src2MBB)) {
1110 MachineBasicBlock *&TheEntry = LLInfoMap[LoopRep];
1111 if (TheEntry) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001112 DEBUG(
1113 dbgs() << "isLoopContBreakBlock yes src1 = BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001114 << Src1MBB->getNumber()
1115 << " src2 = BB" << Src2MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001116 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001117 return true;
1118 }
1119 }
1120 }
1121 return false;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001122}
Tom Stellard75aadc22012-12-11 21:25:42 +00001123
Vincent Lejeune960a6222013-07-19 21:45:06 +00001124int AMDGPUCFGStructurizer::handleJumpintoIf(MachineBasicBlock *HeadMBB,
1125 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1126 int Num = handleJumpintoIfImp(HeadMBB, TrueMBB, FalseMBB);
1127 if (Num == 0) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001128 DEBUG(
1129 dbgs() << "handleJumpintoIf swap trueBlk and FalseBlk" << "\n";
1130 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001131 Num = handleJumpintoIfImp(HeadMBB, FalseMBB, TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001132 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001133 return Num;
Tom Stellard75aadc22012-12-11 21:25:42 +00001134}
1135
Vincent Lejeune960a6222013-07-19 21:45:06 +00001136int AMDGPUCFGStructurizer::handleJumpintoIfImp(MachineBasicBlock *HeadMBB,
1137 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) {
1138 int Num = 0;
1139 MachineBasicBlock *DownBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001140
1141 //trueBlk could be the common post dominator
Vincent Lejeune960a6222013-07-19 21:45:06 +00001142 DownBlk = TrueMBB;
Tom Stellard75aadc22012-12-11 21:25:42 +00001143
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001144 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001145 dbgs() << "handleJumpintoIfImp head = BB" << HeadMBB->getNumber()
1146 << " true = BB" << TrueMBB->getNumber()
1147 << ", numSucc=" << TrueMBB->succ_size()
1148 << " false = BB" << FalseMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001149 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001150
Vincent Lejeune960a6222013-07-19 21:45:06 +00001151 while (DownBlk) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001152 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001153 dbgs() << "check down = BB" << DownBlk->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001154 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001155
Vincent Lejeune960a6222013-07-19 21:45:06 +00001156 if (singlePathTo(FalseMBB, DownBlk) == SinglePath_InPath) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001157 DEBUG(
1158 dbgs() << " working\n";
1159 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001160
Vincent Lejeune960a6222013-07-19 21:45:06 +00001161 Num += cloneOnSideEntryTo(HeadMBB, TrueMBB, DownBlk);
1162 Num += cloneOnSideEntryTo(HeadMBB, FalseMBB, DownBlk);
Tom Stellard75aadc22012-12-11 21:25:42 +00001163
Vincent Lejeune960a6222013-07-19 21:45:06 +00001164 numClonedBlock += Num;
1165 Num += serialPatternMatch(*HeadMBB->succ_begin());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001166 Num += serialPatternMatch(*std::next(HeadMBB->succ_begin()));
Vincent Lejeune960a6222013-07-19 21:45:06 +00001167 Num += ifPatternMatch(HeadMBB);
1168 assert(Num > 0);
Tom Stellard75aadc22012-12-11 21:25:42 +00001169
1170 break;
1171 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001172 DEBUG(
1173 dbgs() << " not working\n";
1174 );
Craig Topper062a2ba2014-04-25 05:30:21 +00001175 DownBlk = (DownBlk->succ_size() == 1) ? (*DownBlk->succ_begin()) : nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001176 } // walk down the postDomTree
1177
Vincent Lejeune960a6222013-07-19 21:45:06 +00001178 return Num;
1179}
Tom Stellard75aadc22012-12-11 21:25:42 +00001180
Vincent Lejeune960a6222013-07-19 21:45:06 +00001181void AMDGPUCFGStructurizer::showImproveSimpleJumpintoIf(
1182 MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB,
1183 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail) {
1184 dbgs() << "head = BB" << HeadMBB->getNumber()
1185 << " size = " << HeadMBB->size();
1186 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001187 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001188 HeadMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001189 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001190 }
1191
Vincent Lejeune960a6222013-07-19 21:45:06 +00001192 if (TrueMBB) {
1193 dbgs() << ", true = BB" << TrueMBB->getNumber() << " size = "
1194 << TrueMBB->size() << " numPred = " << TrueMBB->pred_size();
1195 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001196 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001197 TrueMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001198 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001199 }
1200 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001201 if (FalseMBB) {
1202 dbgs() << ", false = BB" << FalseMBB->getNumber() << " size = "
1203 << FalseMBB->size() << " numPred = " << FalseMBB->pred_size();
1204 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001205 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001206 FalseMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001207 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001208 }
1209 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001210 if (LandMBB) {
1211 dbgs() << ", land = BB" << LandMBB->getNumber() << " size = "
1212 << LandMBB->size() << " numPred = " << LandMBB->pred_size();
1213 if (Detail) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001214 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001215 LandMBB->print(dbgs());
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001216 dbgs() << "\n";
Tom Stellard75aadc22012-12-11 21:25:42 +00001217 }
1218 }
1219
Eugene Zelenko66203762017-01-21 00:53:49 +00001220 dbgs() << "\n";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001221}
Tom Stellard75aadc22012-12-11 21:25:42 +00001222
Vincent Lejeune960a6222013-07-19 21:45:06 +00001223int AMDGPUCFGStructurizer::improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB,
1224 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
1225 MachineBasicBlock **LandMBBPtr) {
1226 bool MigrateTrue = false;
1227 bool MigrateFalse = false;
Tom Stellard75aadc22012-12-11 21:25:42 +00001228
Vincent Lejeune960a6222013-07-19 21:45:06 +00001229 MachineBasicBlock *LandBlk = *LandMBBPtr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001230
Vincent Lejeune960a6222013-07-19 21:45:06 +00001231 assert((!TrueMBB || TrueMBB->succ_size() <= 1)
1232 && (!FalseMBB || FalseMBB->succ_size() <= 1));
Tom Stellard75aadc22012-12-11 21:25:42 +00001233
Vincent Lejeune960a6222013-07-19 21:45:06 +00001234 if (TrueMBB == FalseMBB)
Tom Stellard75aadc22012-12-11 21:25:42 +00001235 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001236
Vincent Lejeune960a6222013-07-19 21:45:06 +00001237 MigrateTrue = needMigrateBlock(TrueMBB);
1238 MigrateFalse = needMigrateBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001239
Vincent Lejeune960a6222013-07-19 21:45:06 +00001240 if (!MigrateTrue && !MigrateFalse)
Tom Stellard75aadc22012-12-11 21:25:42 +00001241 return 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001242
1243 // If we need to migrate either trueBlk and falseBlk, migrate the rest that
1244 // have more than one predecessors. without doing this, its predecessor
1245 // rather than headBlk will have undefined value in initReg.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001246 if (!MigrateTrue && TrueMBB && TrueMBB->pred_size() > 1)
1247 MigrateTrue = true;
1248 if (!MigrateFalse && FalseMBB && FalseMBB->pred_size() > 1)
1249 MigrateFalse = true;
Tom Stellard75aadc22012-12-11 21:25:42 +00001250
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001251 DEBUG(
1252 dbgs() << "before improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001253 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001254 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001255
1256 // org: headBlk => if () {trueBlk} else {falseBlk} => landBlk
1257 //
1258 // new: headBlk => if () {initReg = 1; org trueBlk branch} else
1259 // {initReg = 0; org falseBlk branch }
1260 // => landBlk => if (initReg) {org trueBlk} else {org falseBlk}
1261 // => org landBlk
1262 // if landBlk->pred_size() > 2, put the about if-else inside
1263 // if (initReg !=2) {...}
1264 //
1265 // add initReg = initVal to headBlk
1266
1267 const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32);
Tom Stellardb34186a2013-10-16 17:06:02 +00001268 if (!MigrateTrue || !MigrateFalse) {
1269 // XXX: We have an opportunity here to optimize the "branch into if" case
1270 // here. Branch into if looks like this:
1271 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001272 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001273 // diamond_head branch_from
1274 // / \ |
1275 // diamond_false diamond_true
1276 // \ /
1277 // done
1278 //
1279 // The diamond_head block begins the "if" and the diamond_true block
1280 // is the block being "branched into".
1281 //
1282 // If MigrateTrue is true, then TrueBB is the block being "branched into"
1283 // and if MigrateFalse is true, then FalseBB is the block being
1284 // "branched into"
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001285 //
Tom Stellardb34186a2013-10-16 17:06:02 +00001286 // Here is the pseudo code for how I think the optimization should work:
1287 // 1. Insert MOV GPR0, 0 before the branch instruction in diamond_head.
1288 // 2. Insert MOV GPR0, 1 before the branch instruction in branch_from.
1289 // 3. Move the branch instruction from diamond_head into its own basic
1290 // block (new_block).
1291 // 4. Add an unconditional branch from diamond_head to new_block
1292 // 5. Replace the branch instruction in branch_from with an unconditional
1293 // branch to new_block. If branch_from has multiple predecessors, then
1294 // we need to replace the True/False block in the branch
1295 // instruction instead of replacing it.
1296 // 6. Change the condition of the branch instruction in new_block from
1297 // COND to (COND || GPR0)
1298 //
1299 // In order insert these MOV instruction, we will need to use the
1300 // RegisterScavenger. Usually liveness stops being tracked during
1301 // the late machine optimization passes, however if we implement
1302 // bool TargetRegisterInfo::requiresRegisterScavenging(
1303 // const MachineFunction &MF)
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001304 // and have it return true, liveness will be tracked correctly
Tom Stellardb34186a2013-10-16 17:06:02 +00001305 // by generic optimization passes. We will also need to make sure that
1306 // all of our target-specific passes that run after regalloc and before
1307 // the CFGStructurizer track liveness and we will need to modify this pass
1308 // to correctly track liveness.
1309 //
1310 // After the above changes, the new CFG should look like this:
1311 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001312 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001313 // diamond_head branch_from
1314 // \ /
1315 // new_block
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001316 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001317 // diamond_false diamond_true
1318 // \ /
1319 // done
1320 //
1321 // Without this optimization, we are forced to duplicate the diamond_true
1322 // block and we will end up with a CFG like this:
1323 //
1324 // entry
Benjamin Kramera9fe95b2013-10-18 14:12:50 +00001325 // / |
Tom Stellardb34186a2013-10-16 17:06:02 +00001326 // diamond_head branch_from
1327 // / \ |
1328 // diamond_false diamond_true diamond_true (duplicate)
1329 // \ / |
1330 // done --------------------|
1331 //
1332 // Duplicating diamond_true can be very costly especially if it has a
1333 // lot of instructions.
1334 return 0;
1335 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001336
Vincent Lejeune960a6222013-07-19 21:45:06 +00001337 int NumNewBlk = 0;
Tom Stellard75aadc22012-12-11 21:25:42 +00001338
Vincent Lejeune960a6222013-07-19 21:45:06 +00001339 bool LandBlkHasOtherPred = (LandBlk->pred_size() > 2);
Tom Stellard75aadc22012-12-11 21:25:42 +00001340
1341 //insert AMDGPU::ENDIF to avoid special case "input landBlk == NULL"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001342 MachineBasicBlock::iterator I = insertInstrBefore(LandBlk, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001343
Vincent Lejeune960a6222013-07-19 21:45:06 +00001344 if (LandBlkHasOtherPred) {
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001345 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001346 unsigned CmpResReg =
1347 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001348 report_fatal_error("Extra compare instruction needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001349 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET,
1350 CmpResReg, DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001351 }
1352
Tom Stellard69f86d12013-10-16 17:05:56 +00001353 // XXX: We are running this after RA, so creating virtual registers will
1354 // cause an assertion failure in the PostRA scheduling pass.
1355 unsigned InitReg =
1356 HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001357 insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET, InitReg,
1358 DebugLoc());
Tom Stellard75aadc22012-12-11 21:25:42 +00001359
Vincent Lejeune960a6222013-07-19 21:45:06 +00001360 if (MigrateTrue) {
1361 migrateInstruction(TrueMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001362 // need to uncondionally insert the assignment to ensure a path from its
1363 // predecessor rather than headBlk has valid value in initReg if
1364 // (initVal != 1).
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001365 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001366 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001367 insertInstrBefore(I, AMDGPU::ELSE);
Tom Stellard75aadc22012-12-11 21:25:42 +00001368
Vincent Lejeune960a6222013-07-19 21:45:06 +00001369 if (MigrateFalse) {
1370 migrateInstruction(FalseMBB, LandBlk, I);
Tom Stellard75aadc22012-12-11 21:25:42 +00001371 // need to uncondionally insert the assignment to ensure a path from its
1372 // predecessor rather than headBlk has valid value in initReg if
1373 // (initVal != 0)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001374 report_fatal_error("Extra register needed to handle CFG");
Tom Stellard75aadc22012-12-11 21:25:42 +00001375 }
1376
Vincent Lejeune960a6222013-07-19 21:45:06 +00001377 if (LandBlkHasOtherPred) {
Tom Stellard75aadc22012-12-11 21:25:42 +00001378 // add endif
Vincent Lejeune960a6222013-07-19 21:45:06 +00001379 insertInstrBefore(I, AMDGPU::ENDIF);
Tom Stellard75aadc22012-12-11 21:25:42 +00001380
1381 // put initReg = 2 to other predecessors of landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001382 for (MachineBasicBlock::pred_iterator PI = LandBlk->pred_begin(),
1383 PE = LandBlk->pred_end(); PI != PE; ++PI) {
1384 MachineBasicBlock *MBB = *PI;
1385 if (MBB != TrueMBB && MBB != FalseMBB)
Matt Arsenault5de68cb2016-03-02 03:33:55 +00001386 report_fatal_error("Extra register needed to handle CFG");
Vincent Lejeune960a6222013-07-19 21:45:06 +00001387 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001388 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001389 DEBUG(
1390 dbgs() << "result from improveSimpleJumpintoIf: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001391 showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001392 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001393
1394 // update landBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001395 *LandMBBPtr = LandBlk;
Tom Stellard75aadc22012-12-11 21:25:42 +00001396
Vincent Lejeune960a6222013-07-19 21:45:06 +00001397 return NumNewBlk;
1398}
Tom Stellard75aadc22012-12-11 21:25:42 +00001399
Vincent Lejeune960a6222013-07-19 21:45:06 +00001400void AMDGPUCFGStructurizer::mergeSerialBlock(MachineBasicBlock *DstMBB,
1401 MachineBasicBlock *SrcMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001402 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001403 dbgs() << "serialPattern BB" << DstMBB->getNumber()
1404 << " <= BB" << SrcMBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001405 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001406 DstMBB->splice(DstMBB->end(), SrcMBB, SrcMBB->begin(), SrcMBB->end());
Tom Stellard75aadc22012-12-11 21:25:42 +00001407
Cong Houc1069892015-12-13 09:26:17 +00001408 DstMBB->removeSuccessor(SrcMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001409 cloneSuccessorList(DstMBB, SrcMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001410
Vincent Lejeune960a6222013-07-19 21:45:06 +00001411 removeSuccessor(SrcMBB);
1412 MLI->removeBlock(SrcMBB);
1413 retireBlock(SrcMBB);
1414}
Tom Stellard75aadc22012-12-11 21:25:42 +00001415
Vincent Lejeune960a6222013-07-19 21:45:06 +00001416void AMDGPUCFGStructurizer::mergeIfthenelseBlock(MachineInstr *BranchMI,
1417 MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB,
1418 MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB) {
Vincent Lejeune8b8a7b52013-07-19 21:45:15 +00001419 assert (TrueMBB);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001420 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001421 dbgs() << "ifPattern BB" << MBB->getNumber();
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001422 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001423 if (TrueMBB) {
1424 dbgs() << "BB" << TrueMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001425 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001426 dbgs() << " } else ";
1427 dbgs() << "{ ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001428 if (FalseMBB) {
1429 dbgs() << "BB" << FalseMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001430 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001431 dbgs() << " }\n ";
1432 dbgs() << "landBlock: ";
Vincent Lejeune960a6222013-07-19 21:45:06 +00001433 if (!LandMBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001434 dbgs() << "NULL";
Tom Stellard75aadc22012-12-11 21:25:42 +00001435 } else {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001436 dbgs() << "BB" << LandMBB->getNumber();
Tom Stellard75aadc22012-12-11 21:25:42 +00001437 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001438 dbgs() << "\n";
1439 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001440
Vincent Lejeune960a6222013-07-19 21:45:06 +00001441 int OldOpcode = BranchMI->getOpcode();
1442 DebugLoc BranchDL = BranchMI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001443
1444// transform to
1445// if cond
1446// trueBlk
1447// else
1448// falseBlk
1449// endif
1450// landBlk
1451
Vincent Lejeune960a6222013-07-19 21:45:06 +00001452 MachineBasicBlock::iterator I = BranchMI;
1453 insertCondBranchBefore(I, getBranchNzeroOpcode(OldOpcode),
1454 BranchDL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001455
Vincent Lejeune960a6222013-07-19 21:45:06 +00001456 if (TrueMBB) {
1457 MBB->splice(I, TrueMBB, TrueMBB->begin(), TrueMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001458 MBB->removeSuccessor(TrueMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001459 if (LandMBB && TrueMBB->succ_size()!=0)
Cong Houc1069892015-12-13 09:26:17 +00001460 TrueMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001461 retireBlock(TrueMBB);
1462 MLI->removeBlock(TrueMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001463 }
1464
Vincent Lejeune960a6222013-07-19 21:45:06 +00001465 if (FalseMBB) {
1466 insertInstrBefore(I, AMDGPU::ELSE);
1467 MBB->splice(I, FalseMBB, FalseMBB->begin(),
1468 FalseMBB->end());
Cong Houc1069892015-12-13 09:26:17 +00001469 MBB->removeSuccessor(FalseMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001470 if (LandMBB && FalseMBB->succ_size() != 0)
Cong Houc1069892015-12-13 09:26:17 +00001471 FalseMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001472 retireBlock(FalseMBB);
1473 MLI->removeBlock(FalseMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001474 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001475 insertInstrBefore(I, AMDGPU::ENDIF);
1476
1477 BranchMI->eraseFromParent();
1478
1479 if (LandMBB && TrueMBB && FalseMBB)
1480 MBB->addSuccessor(LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001481}
1482
1483void AMDGPUCFGStructurizer::mergeLooplandBlock(MachineBasicBlock *DstBlk,
1484 MachineBasicBlock *LandMBB) {
1485 DEBUG(dbgs() << "loopPattern header = BB" << DstBlk->getNumber()
1486 << " land = BB" << LandMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001487
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001488 insertInstrBefore(DstBlk, AMDGPU::WHILELOOP, DebugLoc());
1489 insertInstrEnd(DstBlk, AMDGPU::ENDLOOP, DebugLoc());
Cong Houd97c1002015-12-01 05:29:22 +00001490 DstBlk->replaceSuccessor(DstBlk, LandMBB);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001491}
Tom Stellard75aadc22012-12-11 21:25:42 +00001492
Vincent Lejeune960a6222013-07-19 21:45:06 +00001493void AMDGPUCFGStructurizer::mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB,
1494 MachineBasicBlock *LandMBB) {
1495 DEBUG(dbgs() << "loopbreakPattern exiting = BB" << ExitingMBB->getNumber()
1496 << " land = BB" << LandMBB->getNumber() << "\n";);
1497 MachineInstr *BranchMI = getLoopendBlockBranchInstr(ExitingMBB);
1498 assert(BranchMI && isCondBranch(BranchMI));
1499 DebugLoc DL = BranchMI->getDebugLoc();
1500 MachineBasicBlock *TrueBranch = getTrueBranch(BranchMI);
1501 MachineBasicBlock::iterator I = BranchMI;
1502 if (TrueBranch != LandMBB)
Hans Wennborg0dd9ed12016-08-13 01:12:49 +00001503 reversePredicateSetter(I, *I->getParent());
Vincent Lejeune0c5ed2b2013-07-31 19:31:14 +00001504 insertCondBranchBefore(ExitingMBB, I, AMDGPU::IF_PREDICATE_SET, AMDGPU::PREDICATE_BIT, DL);
1505 insertInstrBefore(I, AMDGPU::BREAK);
1506 insertInstrBefore(I, AMDGPU::ENDIF);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001507 //now branchInst can be erase safely
1508 BranchMI->eraseFromParent();
1509 //now take care of successors, retire blocks
Cong Houc1069892015-12-13 09:26:17 +00001510 ExitingMBB->removeSuccessor(LandMBB, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001511}
Tom Stellard75aadc22012-12-11 21:25:42 +00001512
Vincent Lejeune960a6222013-07-19 21:45:06 +00001513void AMDGPUCFGStructurizer::settleLoopcontBlock(MachineBasicBlock *ContingMBB,
1514 MachineBasicBlock *ContMBB) {
1515 DEBUG(dbgs() << "settleLoopcontBlock conting = BB"
1516 << ContingMBB->getNumber()
1517 << ", cont = BB" << ContMBB->getNumber() << "\n";);
Tom Stellard75aadc22012-12-11 21:25:42 +00001518
Vincent Lejeune960a6222013-07-19 21:45:06 +00001519 MachineInstr *MI = getLoopendBlockBranchInstr(ContingMBB);
1520 if (MI) {
1521 assert(isCondBranch(MI));
1522 MachineBasicBlock::iterator I = MI;
1523 MachineBasicBlock *TrueBranch = getTrueBranch(MI);
1524 int OldOpcode = MI->getOpcode();
1525 DebugLoc DL = MI->getDebugLoc();
Tom Stellard75aadc22012-12-11 21:25:42 +00001526
Vincent Lejeune960a6222013-07-19 21:45:06 +00001527 bool UseContinueLogical = ((&*ContingMBB->rbegin()) == MI);
1528
David Blaikie4eaa79c2015-03-23 20:56:44 +00001529 if (!UseContinueLogical) {
Vincent Lejeune960a6222013-07-19 21:45:06 +00001530 int BranchOpcode =
1531 TrueBranch == ContMBB ? getBranchNzeroOpcode(OldOpcode) :
1532 getBranchZeroOpcode(OldOpcode);
1533 insertCondBranchBefore(I, BranchOpcode, DL);
1534 // insertEnd to ensure phi-moves, if exist, go before the continue-instr.
1535 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE, DL);
1536 insertInstrEnd(ContingMBB, AMDGPU::ENDIF, DL);
1537 } else {
1538 int BranchOpcode =
1539 TrueBranch == ContMBB ? getContinueNzeroOpcode(OldOpcode) :
1540 getContinueZeroOpcode(OldOpcode);
1541 insertCondBranchBefore(I, BranchOpcode, DL);
Tom Stellard75aadc22012-12-11 21:25:42 +00001542 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001543
1544 MI->eraseFromParent();
1545 } else {
1546 // if we've arrived here then we've already erased the branch instruction
1547 // travel back up the basic block to see the last reference of our debug
1548 // location we've just inserted that reference here so it should be
1549 // representative insertEnd to ensure phi-moves, if exist, go before the
1550 // continue-instr.
1551 insertInstrEnd(ContingMBB, AMDGPU::CONTINUE,
1552 getLastDebugLocInBB(ContingMBB));
Tom Stellard75aadc22012-12-11 21:25:42 +00001553 }
1554}
1555
Vincent Lejeune960a6222013-07-19 21:45:06 +00001556int AMDGPUCFGStructurizer::cloneOnSideEntryTo(MachineBasicBlock *PreMBB,
1557 MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB) {
1558 int Cloned = 0;
1559 assert(PreMBB->isSuccessor(SrcMBB));
1560 while (SrcMBB && SrcMBB != DstMBB) {
1561 assert(SrcMBB->succ_size() == 1);
1562 if (SrcMBB->pred_size() > 1) {
1563 SrcMBB = cloneBlockForPredecessor(SrcMBB, PreMBB);
1564 ++Cloned;
Tom Stellard75aadc22012-12-11 21:25:42 +00001565 }
Tom Stellard75aadc22012-12-11 21:25:42 +00001566
Vincent Lejeune960a6222013-07-19 21:45:06 +00001567 PreMBB = SrcMBB;
1568 SrcMBB = *SrcMBB->succ_begin();
Tom Stellard75aadc22012-12-11 21:25:42 +00001569 }
1570
Vincent Lejeune960a6222013-07-19 21:45:06 +00001571 return Cloned;
1572}
Tom Stellard75aadc22012-12-11 21:25:42 +00001573
Vincent Lejeune960a6222013-07-19 21:45:06 +00001574MachineBasicBlock *
1575AMDGPUCFGStructurizer::cloneBlockForPredecessor(MachineBasicBlock *MBB,
1576 MachineBasicBlock *PredMBB) {
1577 assert(PredMBB->isSuccessor(MBB) &&
Tom Stellard75aadc22012-12-11 21:25:42 +00001578 "succBlk is not a prececessor of curBlk");
1579
Vincent Lejeune960a6222013-07-19 21:45:06 +00001580 MachineBasicBlock *CloneMBB = clone(MBB); //clone instructions
1581 replaceInstrUseOfBlockWith(PredMBB, MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001582 //srcBlk, oldBlk, newBlk
1583
Cong Houd97c1002015-12-01 05:29:22 +00001584 PredMBB->replaceSuccessor(MBB, CloneMBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001585
1586 // add all successor to cloneBlk
Vincent Lejeune960a6222013-07-19 21:45:06 +00001587 cloneSuccessorList(CloneMBB, MBB);
Tom Stellard75aadc22012-12-11 21:25:42 +00001588
Vincent Lejeune960a6222013-07-19 21:45:06 +00001589 numClonedInstr += MBB->size();
Tom Stellard75aadc22012-12-11 21:25:42 +00001590
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001591 DEBUG(
1592 dbgs() << "Cloned block: " << "BB"
Vincent Lejeune960a6222013-07-19 21:45:06 +00001593 << MBB->getNumber() << "size " << MBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001594 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001595
Vincent Lejeune960a6222013-07-19 21:45:06 +00001596 SHOWNEWBLK(CloneMBB, "result of Cloned block: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001597
Vincent Lejeune960a6222013-07-19 21:45:06 +00001598 return CloneMBB;
1599}
Tom Stellard75aadc22012-12-11 21:25:42 +00001600
Vincent Lejeune960a6222013-07-19 21:45:06 +00001601void AMDGPUCFGStructurizer::migrateInstruction(MachineBasicBlock *SrcMBB,
1602 MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I) {
1603 MachineBasicBlock::iterator SpliceEnd;
Tom Stellard75aadc22012-12-11 21:25:42 +00001604 //look for the input branchinstr, not the AMDGPU branchinstr
Vincent Lejeune960a6222013-07-19 21:45:06 +00001605 MachineInstr *BranchMI = getNormalBlockBranchInstr(SrcMBB);
1606 if (!BranchMI) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001607 DEBUG(
1608 dbgs() << "migrateInstruction don't see branch instr\n" ;
1609 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001610 SpliceEnd = SrcMBB->end();
Tom Stellard75aadc22012-12-11 21:25:42 +00001611 } else {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001612 DEBUG(dbgs() << "migrateInstruction see branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001613 SpliceEnd = BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001614 }
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001615 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001616 dbgs() << "migrateInstruction before splice dstSize = " << DstMBB->size()
1617 << "srcSize = " << SrcMBB->size() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001618 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001619
1620 //splice insert before insertPos
Vincent Lejeune960a6222013-07-19 21:45:06 +00001621 DstMBB->splice(I, SrcMBB, SrcMBB->begin(), SpliceEnd);
Tom Stellard75aadc22012-12-11 21:25:42 +00001622
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001623 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001624 dbgs() << "migrateInstruction after splice dstSize = " << DstMBB->size()
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001625 << "srcSize = " << SrcMBB->size() << '\n';
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001626 );
Vincent Lejeune960a6222013-07-19 21:45:06 +00001627}
Tom Stellard75aadc22012-12-11 21:25:42 +00001628
Vincent Lejeune960a6222013-07-19 21:45:06 +00001629MachineBasicBlock *
1630AMDGPUCFGStructurizer::normalizeInfiniteLoopExit(MachineLoop* LoopRep) {
1631 MachineBasicBlock *LoopHeader = LoopRep->getHeader();
1632 MachineBasicBlock *LoopLatch = LoopRep->getLoopLatch();
Tom Stellard75aadc22012-12-11 21:25:42 +00001633
Vincent Lejeune960a6222013-07-19 21:45:06 +00001634 if (!LoopHeader || !LoopLatch)
Craig Topper062a2ba2014-04-25 05:30:21 +00001635 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001636 MachineInstr *BranchMI = getLoopendBlockBranchInstr(LoopLatch);
1637 // Is LoopRep an infinite loop ?
1638 if (!BranchMI || !isUncondBranch(BranchMI))
Craig Topper062a2ba2014-04-25 05:30:21 +00001639 return nullptr;
Tom Stellard75aadc22012-12-11 21:25:42 +00001640
Vincent Lejeune960a6222013-07-19 21:45:06 +00001641 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1642 FuncRep->push_back(DummyExitBlk); //insert to function
1643 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock to normalize infiniteLoop: ");
1644 DEBUG(dbgs() << "Old branch instr: " << *BranchMI << "\n";);
Tom Stellard1d46fb22015-07-16 15:38:29 +00001645 LLVMContext &Ctx = LoopHeader->getParent()->getFunction()->getContext();
1646 Ctx.emitError("Extra register needed to handle CFG");
1647 return nullptr;
Vincent Lejeune960a6222013-07-19 21:45:06 +00001648}
Tom Stellard75aadc22012-12-11 21:25:42 +00001649
Vincent Lejeune960a6222013-07-19 21:45:06 +00001650void AMDGPUCFGStructurizer::removeUnconditionalBranch(MachineBasicBlock *MBB) {
1651 MachineInstr *BranchMI;
Tom Stellard75aadc22012-12-11 21:25:42 +00001652
1653 // I saw two unconditional branch in one basic block in example
1654 // test_fc_do_while_or.c need to fix the upstream on this to remove the loop.
Vincent Lejeune960a6222013-07-19 21:45:06 +00001655 while ((BranchMI = getLoopendBlockBranchInstr(MBB))
1656 && isUncondBranch(BranchMI)) {
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001657 DEBUG(dbgs() << "Removing uncond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001658 BranchMI->eraseFromParent();
Tom Stellard75aadc22012-12-11 21:25:42 +00001659 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001660}
Tom Stellard75aadc22012-12-11 21:25:42 +00001661
Vincent Lejeune960a6222013-07-19 21:45:06 +00001662void AMDGPUCFGStructurizer::removeRedundantConditionalBranch(
1663 MachineBasicBlock *MBB) {
1664 if (MBB->succ_size() != 2)
1665 return;
1666 MachineBasicBlock *MBB1 = *MBB->succ_begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001667 MachineBasicBlock *MBB2 = *std::next(MBB->succ_begin());
Vincent Lejeune960a6222013-07-19 21:45:06 +00001668 if (MBB1 != MBB2)
1669 return;
Tom Stellard75aadc22012-12-11 21:25:42 +00001670
Vincent Lejeune960a6222013-07-19 21:45:06 +00001671 MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB);
1672 assert(BranchMI && isCondBranch(BranchMI));
Matt Arsenaulte0b44042015-09-10 21:51:19 +00001673 DEBUG(dbgs() << "Removing unneeded cond branch instr: " << *BranchMI);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001674 BranchMI->eraseFromParent();
1675 SHOWNEWBLK(MBB1, "Removing redundant successor");
Cong Houc1069892015-12-13 09:26:17 +00001676 MBB->removeSuccessor(MBB1, true);
Vincent Lejeune960a6222013-07-19 21:45:06 +00001677}
Tom Stellard75aadc22012-12-11 21:25:42 +00001678
Vincent Lejeune960a6222013-07-19 21:45:06 +00001679void AMDGPUCFGStructurizer::addDummyExitBlock(
1680 SmallVectorImpl<MachineBasicBlock*> &RetMBB) {
1681 MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock();
1682 FuncRep->push_back(DummyExitBlk); //insert to function
1683 insertInstrEnd(DummyExitBlk, AMDGPU::RETURN);
Tom Stellard75aadc22012-12-11 21:25:42 +00001684
Vincent Lejeune960a6222013-07-19 21:45:06 +00001685 for (SmallVectorImpl<MachineBasicBlock *>::iterator It = RetMBB.begin(),
1686 E = RetMBB.end(); It != E; ++It) {
1687 MachineBasicBlock *MBB = *It;
1688 MachineInstr *MI = getReturnInstr(MBB);
1689 if (MI)
1690 MI->eraseFromParent();
1691 MBB->addSuccessor(DummyExitBlk);
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001692 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001693 dbgs() << "Add dummyExitBlock to BB" << MBB->getNumber()
Tom Stellard75aadc22012-12-11 21:25:42 +00001694 << " successors\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001695 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001696 }
Vincent Lejeune960a6222013-07-19 21:45:06 +00001697 SHOWNEWBLK(DummyExitBlk, "DummyExitBlock: ");
Tom Stellard75aadc22012-12-11 21:25:42 +00001698}
1699
Vincent Lejeune960a6222013-07-19 21:45:06 +00001700void AMDGPUCFGStructurizer::removeSuccessor(MachineBasicBlock *MBB) {
1701 while (MBB->succ_size())
1702 MBB->removeSuccessor(*MBB->succ_begin());
Tom Stellard75aadc22012-12-11 21:25:42 +00001703}
1704
Vincent Lejeune960a6222013-07-19 21:45:06 +00001705void AMDGPUCFGStructurizer::recordSccnum(MachineBasicBlock *MBB,
1706 int SccNum) {
1707 BlockInformation *&srcBlkInfo = BlockInfoMap[MBB];
1708 if (!srcBlkInfo)
1709 srcBlkInfo = new BlockInformation();
1710 srcBlkInfo->SccNum = SccNum;
Tom Stellard75aadc22012-12-11 21:25:42 +00001711}
1712
Vincent Lejeune960a6222013-07-19 21:45:06 +00001713void AMDGPUCFGStructurizer::retireBlock(MachineBasicBlock *MBB) {
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001714 DEBUG(
Vincent Lejeune960a6222013-07-19 21:45:06 +00001715 dbgs() << "Retiring BB" << MBB->getNumber() << "\n";
Vincent Lejeunea8c38fe2013-07-19 21:44:56 +00001716 );
Tom Stellard75aadc22012-12-11 21:25:42 +00001717
Vincent Lejeune960a6222013-07-19 21:45:06 +00001718 BlockInformation *&SrcBlkInfo = BlockInfoMap[MBB];
Tom Stellard75aadc22012-12-11 21:25:42 +00001719
Vincent Lejeune960a6222013-07-19 21:45:06 +00001720 if (!SrcBlkInfo)
1721 SrcBlkInfo = new BlockInformation();
Tom Stellard75aadc22012-12-11 21:25:42 +00001722
Vincent Lejeune960a6222013-07-19 21:45:06 +00001723 SrcBlkInfo->IsRetired = true;
1724 assert(MBB->succ_size() == 0 && MBB->pred_size() == 0
Tom Stellard75aadc22012-12-11 21:25:42 +00001725 && "can't retire block yet");
1726}
1727
Tom Stellardf2ba9722013-12-11 17:51:47 +00001728INITIALIZE_PASS_BEGIN(AMDGPUCFGStructurizer, "amdgpustructurizer",
1729 "AMDGPU CFG Structurizer", false, false)
1730INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
1731INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
1732INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
1733INITIALIZE_PASS_END(AMDGPUCFGStructurizer, "amdgpustructurizer",
1734 "AMDGPU CFG Structurizer", false, false)
1735
1736FunctionPass *llvm::createAMDGPUCFGStructurizerPass() {
1737 return new AMDGPUCFGStructurizer();
Tom Stellard75aadc22012-12-11 21:25:42 +00001738}