blob: 659353e912fe04377181cffb77d34fa5b3006951 [file] [log] [blame]
Matt Arsenaultd46fce12013-06-19 20:18:24 +00001//===-- StructurizeCFG.cpp ------------------------------------------------===//
Tom Stellardf8794352012-12-19 22:10:31 +00002//
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//===----------------------------------------------------------------------===//
Tom Stellardf8794352012-12-19 22:10:31 +00009
Matt Arsenaultd46fce12013-06-19 20:18:24 +000010#include "llvm/Transforms/Scalar.h"
Christian Konig90b45122013-03-26 10:24:20 +000011#include "llvm/ADT/MapVector.h"
Tom Stellard071ec902015-02-04 20:49:44 +000012#include "llvm/ADT/PostOrderIterator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000013#include "llvm/ADT/SCCIterator.h"
Tom Stellard755a4e62016-02-10 00:39:37 +000014#include "llvm/Analysis/DivergenceAnalysis.h"
Tom Stellard1f0dded2014-12-03 04:28:32 +000015#include "llvm/Analysis/LoopInfo.h"
Tom Stellardf8794352012-12-19 22:10:31 +000016#include "llvm/Analysis/RegionInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000017#include "llvm/Analysis/RegionIterator.h"
Tom Stellardf8794352012-12-19 22:10:31 +000018#include "llvm/Analysis/RegionPass.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Module.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000020#include "llvm/IR/PatternMatch.h"
Tom Stellard071ec902015-02-04 20:49:44 +000021#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000022#include "llvm/Support/raw_ostream.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000023#include "llvm/Transforms/Utils/SSAUpdater.h"
Tom Stellardf8794352012-12-19 22:10:31 +000024
25using namespace llvm;
Christian Konigd8860992013-02-16 11:27:50 +000026using namespace llvm::PatternMatch;
Tom Stellardf8794352012-12-19 22:10:31 +000027
Chandler Carruth964daaa2014-04-22 02:55:47 +000028#define DEBUG_TYPE "structurizecfg"
29
Tom Stellardf8794352012-12-19 22:10:31 +000030namespace {
31
32// Definition of the complex types used in this pass.
33
34typedef std::pair<BasicBlock *, Value *> BBValuePair;
Tom Stellardf8794352012-12-19 22:10:31 +000035
36typedef SmallVector<RegionNode*, 8> RNVector;
37typedef SmallVector<BasicBlock*, 8> BBVector;
Tom Stellard048f14f2013-02-08 22:24:37 +000038typedef SmallVector<BranchInst*, 8> BranchVector;
Tom Stellardf8794352012-12-19 22:10:31 +000039typedef SmallVector<BBValuePair, 2> BBValueVector;
40
Tom Stellard048f14f2013-02-08 22:24:37 +000041typedef SmallPtrSet<BasicBlock *, 8> BBSet;
42
Christian Konig90b45122013-03-26 10:24:20 +000043typedef MapVector<PHINode *, BBValueVector> PhiMap;
44typedef MapVector<BasicBlock *, BBVector> BB2BBVecMap;
45
Tom Stellardf8794352012-12-19 22:10:31 +000046typedef DenseMap<BasicBlock *, PhiMap> BBPhiMap;
47typedef DenseMap<BasicBlock *, Value *> BBPredicates;
48typedef DenseMap<BasicBlock *, BBPredicates> PredMap;
Christian Konigfc6a9852013-02-16 11:27:45 +000049typedef DenseMap<BasicBlock *, BasicBlock*> BB2BBMap;
Tom Stellardf8794352012-12-19 22:10:31 +000050
51// The name for newly created blocks.
Craig Topperd3a34f82013-07-16 01:17:10 +000052static const char *const FlowBlockName = "Flow";
Tom Stellardf8794352012-12-19 22:10:31 +000053
Justin Lebar62c20d82016-11-28 18:49:59 +000054/// Finds the nearest common dominator of a set of BasicBlocks.
Christian Konigd08e3d72013-02-16 11:27:29 +000055///
Justin Lebar62c20d82016-11-28 18:49:59 +000056/// For every BB you add to the set, you can specify whether we "remember" the
57/// block. When you get the common dominator, you can also ask whether it's one
58/// of the blocks we remembered.
Christian Konigd08e3d72013-02-16 11:27:29 +000059class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000060 DominatorTree *DT;
Justin Lebar62c20d82016-11-28 18:49:59 +000061 BasicBlock *Result = nullptr;
62 bool ResultIsRemembered = false;
Christian Konigd08e3d72013-02-16 11:27:29 +000063
Justin Lebar62c20d82016-11-28 18:49:59 +000064 /// Add BB to the resulting dominator.
65 void addBlock(BasicBlock *BB, bool Remember) {
Craig Topperf40110f2014-04-25 05:29:35 +000066 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000067 Result = BB;
Justin Lebar62c20d82016-11-28 18:49:59 +000068 ResultIsRemembered = Remember;
Christian Konigd08e3d72013-02-16 11:27:29 +000069 return;
70 }
71
Justin Lebar62c20d82016-11-28 18:49:59 +000072 BasicBlock *NewResult = DT->findNearestCommonDominator(Result, BB);
73 if (NewResult != Result)
74 ResultIsRemembered = false;
75 if (NewResult == BB)
76 ResultIsRemembered |= Remember;
77 Result = NewResult;
Christian Konigd08e3d72013-02-16 11:27:29 +000078 }
79
Justin Lebar62c20d82016-11-28 18:49:59 +000080public:
81 explicit NearestCommonDominator(DominatorTree *DomTree) : DT(DomTree) {}
82
83 void addBlock(BasicBlock *BB) {
84 addBlock(BB, /* Remember = */ false);
Christian Konigd08e3d72013-02-16 11:27:29 +000085 }
86
Justin Lebar62c20d82016-11-28 18:49:59 +000087 void addAndRememberBlock(BasicBlock *BB) {
88 addBlock(BB, /* Remember = */ true);
Christian Konigd08e3d72013-02-16 11:27:29 +000089 }
Justin Lebar62c20d82016-11-28 18:49:59 +000090
91 /// Get the nearest common dominator of all the BBs added via addBlock() and
92 /// addAndRememberBlock().
93 BasicBlock *result() { return Result; }
94
95 /// Is the BB returned by getResult() one of the blocks we added to the set
96 /// with addAndRememberBlock()?
97 bool resultIsRememberedBlock() { return ResultIsRemembered; }
Christian Konigd08e3d72013-02-16 11:27:29 +000098};
99
Tom Stellardf8794352012-12-19 22:10:31 +0000100/// @brief Transforms the control flow graph on one single entry/exit region
101/// at a time.
102///
103/// After the transform all "If"/"Then"/"Else" style control flow looks like
104/// this:
105///
106/// \verbatim
107/// 1
108/// ||
109/// | |
110/// 2 |
111/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000112/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000113/// 3
114/// || Where:
115/// | | 1 = "If" block, calculates the condition
116/// 4 | 2 = "Then" subregion, runs if the condition is true
117/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
118/// |/ 4 = "Else" optional subregion, runs if the condition is false
119/// 5 5 = "End" block, also rejoins the control flow
120/// \endverbatim
121///
122/// Control flow is expressed as a branch where the true exit goes into the
123/// "Then"/"Else" region, while the false exit skips the region
124/// The condition for the optional "Else" region is expressed as a PHI node.
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000125/// The incoming values of the PHI node are true for the "If" edge and false
Tom Stellardf8794352012-12-19 22:10:31 +0000126/// for the "Then" edge.
127///
128/// Additionally to that even complicated loops look like this:
129///
130/// \verbatim
131/// 1
132/// ||
133/// | |
134/// 2 ^ Where:
135/// | / 1 = "Entry" block
136/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
137/// 3 3 = "Flow" block, with back edge to entry block
138/// |
139/// \endverbatim
140///
141/// The back edge of the "Flow" block is always on the false side of the branch
142/// while the true side continues the general flow. So the loop condition
143/// consist of a network of PHI nodes where the true incoming values expresses
144/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000145class StructurizeCFG : public RegionPass {
Tom Stellard755a4e62016-02-10 00:39:37 +0000146 bool SkipUniformRegions;
Tom Stellard755a4e62016-02-10 00:39:37 +0000147
Tom Stellardf8794352012-12-19 22:10:31 +0000148 Type *Boolean;
149 ConstantInt *BoolTrue;
150 ConstantInt *BoolFalse;
151 UndefValue *BoolUndef;
152
153 Function *Func;
154 Region *ParentRegion;
155
156 DominatorTree *DT;
Tom Stellard1f0dded2014-12-03 04:28:32 +0000157 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000158
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000159 SmallVector<RegionNode *, 8> Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000160 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000161
Tom Stellardf8794352012-12-19 22:10:31 +0000162 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000163 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000164
165 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000166 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000167
Christian Konigfc6a9852013-02-16 11:27:45 +0000168 BB2BBMap Loops;
169 PredMap LoopPreds;
170 BranchVector LoopConds;
171
172 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000173
174 void orderNodes();
175
Christian Konigfc6a9852013-02-16 11:27:45 +0000176 void analyzeLoops(RegionNode *N);
177
Christian Konigd8860992013-02-16 11:27:50 +0000178 Value *invert(Value *Condition);
179
Tom Stellard048f14f2013-02-08 22:24:37 +0000180 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000181
Christian Konigfc6a9852013-02-16 11:27:45 +0000182 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000183
184 void collectInfos();
185
Christian Konigfc6a9852013-02-16 11:27:45 +0000186 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000187
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000188 void delPhiValues(BasicBlock *From, BasicBlock *To);
189
190 void addPhiValues(BasicBlock *From, BasicBlock *To);
191
192 void setPhiValues();
193
Tom Stellardf8794352012-12-19 22:10:31 +0000194 void killTerminator(BasicBlock *BB);
195
Tom Stellard7370ede2013-02-08 22:24:38 +0000196 void changeExit(RegionNode *Node, BasicBlock *NewExit,
197 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000198
Tom Stellard7370ede2013-02-08 22:24:38 +0000199 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000200
Christian Konigfc6a9852013-02-16 11:27:45 +0000201 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000202
Tom Stellard7370ede2013-02-08 22:24:38 +0000203 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
204
Christian Konigfc6a9852013-02-16 11:27:45 +0000205 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000206
207 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
208
Christian Konigfc6a9852013-02-16 11:27:45 +0000209 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000210
Christian Konigfc6a9852013-02-16 11:27:45 +0000211 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
212
213 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000214
215 void createFlow();
216
Tom Stellardf8794352012-12-19 22:10:31 +0000217 void rebuildSSA();
218
219public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000220 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000221
Justin Lebar73c4baf2016-11-22 23:13:44 +0000222 explicit StructurizeCFG(bool SkipUniformRegions = false)
223 : RegionPass(ID), SkipUniformRegions(SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000224 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
225 }
226
Craig Topper3e4c6972014-03-05 09:10:37 +0000227 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000228
Craig Topper3e4c6972014-03-05 09:10:37 +0000229 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000230
Mehdi Amini117296c2016-10-01 02:56:57 +0000231 StringRef getPassName() const override { return "Structurize control flow"; }
Tom Stellardf8794352012-12-19 22:10:31 +0000232
Craig Topper3e4c6972014-03-05 09:10:37 +0000233 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard755a4e62016-02-10 00:39:37 +0000234 if (SkipUniformRegions)
235 AU.addRequired<DivergenceAnalysis>();
Tom Stellardd3e916e2013-10-02 17:04:59 +0000236 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000237 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000238 AU.addRequired<LoopInfoWrapperPass>();
Justin Lebar23aaf602016-11-22 23:14:07 +0000239
Chandler Carruth73523022014-01-13 13:07:17 +0000240 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000241 RegionPass::getAnalysisUsage(AU);
242 }
Tom Stellardf8794352012-12-19 22:10:31 +0000243};
244
245} // end anonymous namespace
246
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000247char StructurizeCFG::ID = 0;
248
249INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
250 false, false)
Tom Stellard755a4e62016-02-10 00:39:37 +0000251INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000252INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000253INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000254INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000255INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
256 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000257
258/// \brief Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000259bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000260 LLVMContext &Context = R->getEntry()->getContext();
261
262 Boolean = Type::getInt1Ty(Context);
263 BoolTrue = ConstantInt::getTrue(Context);
264 BoolFalse = ConstantInt::getFalse(Context);
265 BoolUndef = UndefValue::get(Boolean);
266
267 return false;
268}
269
270/// \brief Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000271void StructurizeCFG::orderNodes() {
Tom Stellard071ec902015-02-04 20:49:44 +0000272 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000273 SmallDenseMap<Loop*, unsigned, 8> LoopBlocks;
Tom Stellard071ec902015-02-04 20:49:44 +0000274
275 // The reverse post-order traversal of the list gives us an ordering close
276 // to what we want. The only problem with it is that sometimes backedges
277 // for outer loops will be visited before backedges for inner loops.
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000278 for (RegionNode *RN : RPOT) {
Tom Stellard071ec902015-02-04 20:49:44 +0000279 BasicBlock *BB = RN->getEntry();
280 Loop *Loop = LI->getLoopFor(BB);
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000281 ++LoopBlocks[Loop];
Tom Stellardf8794352012-12-19 22:10:31 +0000282 }
Tom Stellard071ec902015-02-04 20:49:44 +0000283
284 unsigned CurrentLoopDepth = 0;
285 Loop *CurrentLoop = nullptr;
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000286 for (auto I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
Tom Stellard071ec902015-02-04 20:49:44 +0000287 BasicBlock *BB = (*I)->getEntry();
288 unsigned LoopDepth = LI->getLoopDepth(BB);
289
David Majnemer0d955d02016-08-11 22:21:41 +0000290 if (is_contained(Order, *I))
Tom Stellard071ec902015-02-04 20:49:44 +0000291 continue;
292
293 if (LoopDepth < CurrentLoopDepth) {
294 // Make sure we have visited all blocks in this loop before moving back to
295 // the outer loop.
296
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000297 auto LoopI = I;
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000298 while (unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
Tom Stellard071ec902015-02-04 20:49:44 +0000299 LoopI++;
300 BasicBlock *LoopBB = (*LoopI)->getEntry();
301 if (LI->getLoopFor(LoopBB) == CurrentLoop) {
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000302 --BlockCount;
Tom Stellard071ec902015-02-04 20:49:44 +0000303 Order.push_back(*LoopI);
304 }
305 }
306 }
307
308 CurrentLoop = LI->getLoopFor(BB);
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000309 if (CurrentLoop)
Tom Stellard071ec902015-02-04 20:49:44 +0000310 LoopBlocks[CurrentLoop]--;
Tom Stellard071ec902015-02-04 20:49:44 +0000311
312 CurrentLoopDepth = LoopDepth;
313 Order.push_back(*I);
314 }
315
316 // This pass originally used a post-order traversal and then operated on
317 // the list in reverse. Now that we are using a reverse post-order traversal
318 // rather than re-working the whole pass to operate on the list in order,
319 // we just reverse the list and continue to operate on it in reverse.
320 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000321}
322
Christian Konigfc6a9852013-02-16 11:27:45 +0000323/// \brief Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000324void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000325 if (N->isSubRegion()) {
326 // Test for exit as back edge
327 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
328 if (Visited.count(Exit))
329 Loops[Exit] = N->getEntry();
330
331 } else {
332 // Test for sucessors as back edge
333 BasicBlock *BB = N->getNodeAs<BasicBlock>();
334 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
335
Pete Cooperebcd7482015-08-06 20:22:46 +0000336 for (BasicBlock *Succ : Term->successors())
337 if (Visited.count(Succ))
Christian Konigfc6a9852013-02-16 11:27:45 +0000338 Loops[Succ] = BB;
Christian Konigfc6a9852013-02-16 11:27:45 +0000339 }
340}
341
Christian Konigd8860992013-02-16 11:27:50 +0000342/// \brief Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000343Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000344 // First: Check if it's a constant
Matt Arsenault93be6e82016-07-15 22:13:16 +0000345 if (Constant *C = dyn_cast<Constant>(Condition))
346 return ConstantExpr::getNot(C);
Christian Konigd8860992013-02-16 11:27:50 +0000347
348 // Second: If the condition is already inverted, return the original value
349 if (match(Condition, m_Not(m_Value(Condition))))
350 return Condition;
351
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000352 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
353 // Third: Check all the users for an invert
354 BasicBlock *Parent = Inst->getParent();
Matt Arsenaultd3406bc2017-04-19 18:29:07 +0000355 for (User *U : Condition->users()) {
356 if (Instruction *I = dyn_cast<Instruction>(U)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000357 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
358 return I;
Matt Arsenaultd3406bc2017-04-19 18:29:07 +0000359 }
360 }
361
362 // Avoid creating a new instruction in the common case of a compare.
363 if (CmpInst *Cmp = dyn_cast<CmpInst>(Inst)) {
364 if (Cmp->hasOneUse()) {
365 Cmp->setPredicate(Cmp->getInversePredicate());
366 return Cmp;
367 }
368 }
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000369
370 // Last option: Create a new instruction
371 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000372 }
373
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000374 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
375 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
376 return BinaryOperator::CreateNot(Condition,
377 Arg->getName() + ".inv",
378 EntryBlock.getTerminator());
379 }
380
381 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000382}
383
Tom Stellard048f14f2013-02-08 22:24:37 +0000384/// \brief Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000385Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
386 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000387 Value *Cond = Invert ? BoolFalse : BoolTrue;
388 if (Term->isConditional()) {
389 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000390
Aaron Ballman19978552013-06-04 01:03:03 +0000391 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000392 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000393 }
394 return Cond;
395}
396
Tom Stellard048f14f2013-02-08 22:24:37 +0000397/// \brief Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000398void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000399 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000400 BasicBlock *BB = N->getEntry();
401 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000402 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000403
Justin Lebar3aec10c2016-11-28 18:50:03 +0000404 for (BasicBlock *P : predecessors(BB)) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000405 // Ignore it if it's a branch from outside into our region entry
Justin Lebar3aec10c2016-11-28 18:50:03 +0000406 if (!ParentRegion->contains(P))
Tom Stellard048f14f2013-02-08 22:24:37 +0000407 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000408
Justin Lebar3aec10c2016-11-28 18:50:03 +0000409 Region *R = RI->getRegionFor(P);
Tom Stellard048f14f2013-02-08 22:24:37 +0000410 if (R == ParentRegion) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000411 // It's a top level block in our region
Justin Lebar3aec10c2016-11-28 18:50:03 +0000412 BranchInst *Term = cast<BranchInst>(P->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000413 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
414 BasicBlock *Succ = Term->getSuccessor(i);
415 if (Succ != BB)
416 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000417
Justin Lebar3aec10c2016-11-28 18:50:03 +0000418 if (Visited.count(P)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000419 // Normal forward edge
420 if (Term->isConditional()) {
421 // Try to treat it like an ELSE block
422 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000423 if (Visited.count(Other) && !Loops.count(Other) &&
Justin Lebar3aec10c2016-11-28 18:50:03 +0000424 !Pred.count(Other) && !Pred.count(P)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000425
Tom Stellard048f14f2013-02-08 22:24:37 +0000426 Pred[Other] = BoolFalse;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000427 Pred[P] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000428 continue;
429 }
430 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000431 Pred[P] = buildCondition(Term, i, false);
Tom Stellard048f14f2013-02-08 22:24:37 +0000432 } else {
433 // Back edge
Justin Lebar3aec10c2016-11-28 18:50:03 +0000434 LPred[P] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000435 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000436 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000437 } else {
Tom Stellard048f14f2013-02-08 22:24:37 +0000438 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000439 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000440 R = R->getParent();
441
442 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000443 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000444 continue;
445
446 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000447 if (Visited.count(Entry))
448 Pred[Entry] = BoolTrue;
449 else
450 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000451 }
452 }
453}
454
455/// \brief Collect various loop and predicate infos
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000456void StructurizeCFG::collectInfos() {
Tom Stellardf8794352012-12-19 22:10:31 +0000457 // Reset predicate
458 Predicates.clear();
459
460 // and loop infos
Christian Konigfc6a9852013-02-16 11:27:45 +0000461 Loops.clear();
462 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000463
Tom Stellard048f14f2013-02-08 22:24:37 +0000464 // Reset the visited nodes
465 Visited.clear();
466
David Majnemerd7708772016-06-24 04:05:21 +0000467 for (RegionNode *RN : reverse(Order)) {
David Majnemerd7708772016-06-24 04:05:21 +0000468 DEBUG(dbgs() << "Visiting: "
469 << (RN->isSubRegion() ? "SubRegion with entry: " : "")
470 << RN->getEntry()->getName() << " Loop Depth: "
471 << LI->getLoopDepth(RN->getEntry()) << "\n");
Tom Stellard071ec902015-02-04 20:49:44 +0000472
Tom Stellardf8794352012-12-19 22:10:31 +0000473 // Analyze all the conditions leading to a node
David Majnemerd7708772016-06-24 04:05:21 +0000474 gatherPredicates(RN);
Tom Stellardf8794352012-12-19 22:10:31 +0000475
Tom Stellard048f14f2013-02-08 22:24:37 +0000476 // Remember that we've seen this node
David Majnemerd7708772016-06-24 04:05:21 +0000477 Visited.insert(RN->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000478
Christian Konigfc6a9852013-02-16 11:27:45 +0000479 // Find the last back edges
David Majnemerd7708772016-06-24 04:05:21 +0000480 analyzeLoops(RN);
Tom Stellard048f14f2013-02-08 22:24:37 +0000481 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000482}
483
484/// \brief Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000485void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000486 BranchVector &Conds = Loops ? LoopConds : Conditions;
487 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000488 SSAUpdater PhiInserter;
489
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000490 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000491 assert(Term->isConditional());
492
Christian Konigfc6a9852013-02-16 11:27:45 +0000493 BasicBlock *Parent = Term->getParent();
494 BasicBlock *SuccTrue = Term->getSuccessor(0);
495 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000496
Christian Konigb5d88662013-02-16 11:27:40 +0000497 PhiInserter.Initialize(Boolean, "");
498 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000499 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000500
Christian Konigfc6a9852013-02-16 11:27:45 +0000501 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000502
503 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000504 Dominator.addBlock(Parent);
Christian Konigb5d88662013-02-16 11:27:40 +0000505
Craig Topperf40110f2014-04-25 05:29:35 +0000506 Value *ParentValue = nullptr;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000507 for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
508 BasicBlock *BB = BBAndPred.first;
509 Value *Pred = BBAndPred.second;
Tom Stellard048f14f2013-02-08 22:24:37 +0000510
Justin Lebar3aec10c2016-11-28 18:50:03 +0000511 if (BB == Parent) {
512 ParentValue = Pred;
Christian Konigb5d88662013-02-16 11:27:40 +0000513 break;
514 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000515 PhiInserter.AddAvailableValue(BB, Pred);
516 Dominator.addAndRememberBlock(BB);
Tom Stellard048f14f2013-02-08 22:24:37 +0000517 }
518
Christian Konigb5d88662013-02-16 11:27:40 +0000519 if (ParentValue) {
520 Term->setCondition(ParentValue);
521 } else {
Justin Lebar62c20d82016-11-28 18:49:59 +0000522 if (!Dominator.resultIsRememberedBlock())
523 PhiInserter.AddAvailableValue(Dominator.result(), Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000524
Tom Stellard048f14f2013-02-08 22:24:37 +0000525 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000526 }
Tom Stellardf8794352012-12-19 22:10:31 +0000527 }
528}
529
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000530/// \brief Remove all PHI values coming from "From" into "To" and remember
531/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000532void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000533 PhiMap &Map = DeletedPhis[To];
Justin Lebar3aec10c2016-11-28 18:50:03 +0000534 for (Instruction &I : *To) {
535 if (!isa<PHINode>(I))
536 break;
537 PHINode &Phi = cast<PHINode>(I);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000538 while (Phi.getBasicBlockIndex(From) != -1) {
539 Value *Deleted = Phi.removeIncomingValue(From, false);
540 Map[&Phi].push_back(std::make_pair(From, Deleted));
541 }
542 }
543}
544
545/// \brief Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000546void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000547 for (Instruction &I : *To) {
548 if (!isa<PHINode>(I))
549 break;
550 PHINode &Phi = cast<PHINode>(I);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000551 Value *Undef = UndefValue::get(Phi.getType());
552 Phi.addIncoming(Undef, From);
553 }
554 AddedPhis[To].push_back(From);
555}
556
557/// \brief Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000558void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000559 SSAUpdater Updater;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000560 for (const auto &AddedPhi : AddedPhis) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000561 BasicBlock *To = AddedPhi.first;
562 const BBVector &From = AddedPhi.second;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000563
564 if (!DeletedPhis.count(To))
565 continue;
566
567 PhiMap &Map = DeletedPhis[To];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000568 for (const auto &PI : Map) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000569 PHINode *Phi = PI.first;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000570 Value *Undef = UndefValue::get(Phi->getType());
571 Updater.Initialize(Phi->getType(), "");
572 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
573 Updater.AddAvailableValue(To, Undef);
574
Christian Konig0bccf9d2013-02-16 11:27:35 +0000575 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000576 Dominator.addBlock(To);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000577 for (const auto &VI : PI.second) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000578 Updater.AddAvailableValue(VI.first, VI.second);
Justin Lebar62c20d82016-11-28 18:49:59 +0000579 Dominator.addAndRememberBlock(VI.first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000580 }
581
Justin Lebar62c20d82016-11-28 18:49:59 +0000582 if (!Dominator.resultIsRememberedBlock())
583 Updater.AddAvailableValue(Dominator.result(), Undef);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000584
Benjamin Kramer135f7352016-06-26 12:28:59 +0000585 for (BasicBlock *FI : From) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000586 int Idx = Phi->getBasicBlockIndex(FI);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000587 assert(Idx != -1);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000588 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(FI));
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000589 }
590 }
591
592 DeletedPhis.erase(To);
593 }
594 assert(DeletedPhis.empty());
595}
596
Tom Stellard7370ede2013-02-08 22:24:38 +0000597/// \brief Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000598void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000599 TerminatorInst *Term = BB->getTerminator();
600 if (!Term)
601 return;
602
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000603 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000604 SI != SE; ++SI)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000605 delPhiValues(BB, *SI);
Tom Stellardf8794352012-12-19 22:10:31 +0000606
607 Term->eraseFromParent();
608}
609
Tom Stellard7370ede2013-02-08 22:24:38 +0000610/// \brief Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000611void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
612 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000613 if (Node->isSubRegion()) {
614 Region *SubRegion = Node->getNodeAs<Region>();
615 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000616 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000617
Tom Stellard7370ede2013-02-08 22:24:38 +0000618 // Find all the edges from the sub region to the exit
Justin Lebar3aec10c2016-11-28 18:50:03 +0000619 for (auto BBI = pred_begin(OldExit), E = pred_end(OldExit); BBI != E;) {
620 // Incrememt BBI before mucking with BB's terminator.
621 BasicBlock *BB = *BBI++;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000622
Tom Stellard7370ede2013-02-08 22:24:38 +0000623 if (!SubRegion->contains(BB))
624 continue;
625
626 // Modify the edges to point to the new exit
627 delPhiValues(BB, OldExit);
628 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
629 addPhiValues(BB, NewExit);
630
631 // Find the new dominator (if requested)
632 if (IncludeDominator) {
633 if (!Dominator)
634 Dominator = BB;
635 else
636 Dominator = DT->findNearestCommonDominator(Dominator, BB);
637 }
Tom Stellardf8794352012-12-19 22:10:31 +0000638 }
639
Tom Stellard7370ede2013-02-08 22:24:38 +0000640 // Change the dominator (if requested)
641 if (Dominator)
642 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000643
Tom Stellard7370ede2013-02-08 22:24:38 +0000644 // Update the region info
645 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000646 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000647 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
648 killTerminator(BB);
649 BranchInst::Create(NewExit, BB);
650 addPhiValues(BB, NewExit);
651 if (IncludeDominator)
652 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000653 }
Tom Stellardf8794352012-12-19 22:10:31 +0000654}
655
Tom Stellardf8794352012-12-19 22:10:31 +0000656/// \brief Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000657BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000658 LLVMContext &Context = Func->getContext();
659 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
660 Order.back()->getEntry();
661 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
662 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000663 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000664 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000665 return Flow;
666}
667
Tom Stellard7370ede2013-02-08 22:24:38 +0000668/// \brief Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000669BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000670 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000671
Christian Konigfc6a9852013-02-16 11:27:45 +0000672 if (!PrevNode->isSubRegion()) {
673 killTerminator(Entry);
674 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
675 return Entry;
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000676 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000677
Christian Konigfc6a9852013-02-16 11:27:45 +0000678 // create a new flow node
679 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000680
Christian Konigfc6a9852013-02-16 11:27:45 +0000681 // and wire it up
682 changeExit(PrevNode, Flow, true);
683 PrevNode = ParentRegion->getBBNode(Flow);
684 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000685}
686
687/// \brief Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000688BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
689 bool ExitUseAllowed) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000690 if (!Order.empty() || !ExitUseAllowed)
691 return getNextFlow(Flow);
692
693 BasicBlock *Exit = ParentRegion->getExit();
694 DT->changeImmediateDominator(Exit, Flow);
695 addPhiValues(Flow, Exit);
696 return Exit;
Tom Stellard7370ede2013-02-08 22:24:38 +0000697}
698
Christian Konigfc6a9852013-02-16 11:27:45 +0000699/// \brief Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000700void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000701 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
702 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000703}
704
Justin Lebar3aec10c2016-11-28 18:50:03 +0000705/// \brief Does BB dominate all the predicates of Node?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000706bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000707 BBPredicates &Preds = Predicates[Node->getEntry()];
Justin Lebar3aec10c2016-11-28 18:50:03 +0000708 return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
709 return DT->dominates(BB, Pred.first);
710 });
Tom Stellard7370ede2013-02-08 22:24:38 +0000711}
712
Tom Stellardf8794352012-12-19 22:10:31 +0000713/// \brief Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000714bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000715 BBPredicates &Preds = Predicates[Node->getEntry()];
716 bool Dominated = false;
717
718 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000719 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000720 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000721
Justin Lebar3aec10c2016-11-28 18:50:03 +0000722 for (std::pair<BasicBlock*, Value*> Pred : Preds) {
723 BasicBlock *BB = Pred.first;
724 Value *V = Pred.second;
Tom Stellardf8794352012-12-19 22:10:31 +0000725
Justin Lebar3aec10c2016-11-28 18:50:03 +0000726 if (V != BoolTrue)
Tom Stellardf8794352012-12-19 22:10:31 +0000727 return false;
728
Justin Lebar3aec10c2016-11-28 18:50:03 +0000729 if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000730 Dominated = true;
731 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000732
733 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000734 return Dominated;
735}
736
Tom Stellard7370ede2013-02-08 22:24:38 +0000737/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000738void StructurizeCFG::wireFlow(bool ExitUseAllowed,
739 BasicBlock *LoopEnd) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000740 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000741 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000742
Christian Konigfc6a9852013-02-16 11:27:45 +0000743 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000744 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000745 if (PrevNode) {
746 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000747 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000748 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000749
750 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000751 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000752 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000753
Tom Stellard7370ede2013-02-08 22:24:38 +0000754 // Insert extra postfix node (or use exit instead)
755 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000756 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000757
758 // let it point to entry and next block
759 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
760 addPhiValues(Flow, Entry);
761 DT->changeImmediateDominator(Entry, Flow);
762
Christian Konigfc6a9852013-02-16 11:27:45 +0000763 PrevNode = Node;
764 while (!Order.empty() && !Visited.count(LoopEnd) &&
Tom Stellard7370ede2013-02-08 22:24:38 +0000765 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000766 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000767 }
768
Christian Konigfc6a9852013-02-16 11:27:45 +0000769 changeExit(PrevNode, Next, false);
770 setPrevNode(Next);
771 }
772}
773
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000774void StructurizeCFG::handleLoops(bool ExitUseAllowed,
775 BasicBlock *LoopEnd) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000776 RegionNode *Node = Order.back();
777 BasicBlock *LoopStart = Node->getEntry();
778
779 if (!Loops.count(LoopStart)) {
780 wireFlow(ExitUseAllowed, LoopEnd);
781 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000782 }
783
Christian Konigfc6a9852013-02-16 11:27:45 +0000784 if (!isPredictableTrue(Node))
785 LoopStart = needPrefix(true);
786
787 LoopEnd = Loops[Node->getEntry()];
788 wireFlow(false, LoopEnd);
789 while (!Visited.count(LoopEnd)) {
790 handleLoops(false, LoopEnd);
791 }
792
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000793 // If the start of the loop is the entry block, we can't branch to it so
794 // insert a new dummy entry block.
795 Function *LoopFunc = LoopStart->getParent();
796 if (LoopStart == &LoopFunc->getEntryBlock()) {
797 LoopStart->setName("entry.orig");
798
799 BasicBlock *NewEntry =
800 BasicBlock::Create(LoopStart->getContext(),
801 "entry",
802 LoopFunc,
803 LoopStart);
804 BranchInst::Create(LoopStart, NewEntry);
Serge Pavlov0668cd22017-01-10 02:50:47 +0000805 DT->setNewRoot(NewEntry);
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000806 }
807
Christian Konigfc6a9852013-02-16 11:27:45 +0000808 // Create an extra loop end node
809 LoopEnd = needPrefix(false);
810 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
811 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
812 BoolUndef, LoopEnd));
813 addPhiValues(LoopEnd, LoopStart);
814 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000815}
816
Tom Stellardf8794352012-12-19 22:10:31 +0000817/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000818/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000819void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000820 BasicBlock *Exit = ParentRegion->getExit();
821 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
822
Tom Stellardf8794352012-12-19 22:10:31 +0000823 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000824 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000825 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000826 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000827
Craig Topperf40110f2014-04-25 05:29:35 +0000828 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000829 Visited.clear();
830
Tom Stellardf8794352012-12-19 22:10:31 +0000831 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000832 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000833 }
834
Christian Konigfc6a9852013-02-16 11:27:45 +0000835 if (PrevNode)
836 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000837 else
838 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000839}
840
Tom Stellardf8794352012-12-19 22:10:31 +0000841/// Handle a rare case where the disintegrated nodes instructions
842/// no longer dominate all their uses. Not sure if this is really nessasary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000843void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000844 SSAUpdater Updater;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000845 for (BasicBlock *BB : ParentRegion->blocks())
846 for (Instruction &I : *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000847 bool Initialized = false;
Justin Lebar96e29152016-11-29 21:49:02 +0000848 // We may modify the use list as we iterate over it, so be careful to
849 // compute the next element in the use list at the top of the loop.
850 for (auto UI = I.use_begin(), E = I.use_end(); UI != E;) {
851 Use &U = *UI++;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000852 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000853 if (User->getParent() == BB) {
854 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000855 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000856 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000857 continue;
858 }
859
Justin Lebar3aec10c2016-11-28 18:50:03 +0000860 if (DT->dominates(&I, User))
Tom Stellardf8794352012-12-19 22:10:31 +0000861 continue;
862
863 if (!Initialized) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000864 Value *Undef = UndefValue::get(I.getType());
865 Updater.Initialize(I.getType(), "");
Tom Stellardf8794352012-12-19 22:10:31 +0000866 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000867 Updater.AddAvailableValue(BB, &I);
Tom Stellardf8794352012-12-19 22:10:31 +0000868 Initialized = true;
869 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000870 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000871 }
872 }
Tom Stellardf8794352012-12-19 22:10:31 +0000873}
874
Justin Lebarc7445d52016-11-22 23:13:33 +0000875static bool hasOnlyUniformBranches(const Region *R,
876 const DivergenceAnalysis &DA) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000877 for (const BasicBlock *BB : R->blocks()) {
878 const BranchInst *Br = dyn_cast<BranchInst>(BB->getTerminator());
879 if (!Br || !Br->isConditional())
880 continue;
881
Justin Lebarc7445d52016-11-22 23:13:33 +0000882 if (!DA.isUniform(Br->getCondition()))
Tom Stellard755a4e62016-02-10 00:39:37 +0000883 return false;
884 DEBUG(dbgs() << "BB: " << BB->getName() << " has uniform terminator\n");
885 }
886 return true;
887}
888
Tom Stellardf8794352012-12-19 22:10:31 +0000889/// \brief Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000890bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000891 if (R->isTopLevelRegion())
892 return false;
893
Tom Stellard755a4e62016-02-10 00:39:37 +0000894 if (SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000895 // TODO: We could probably be smarter here with how we handle sub-regions.
Justin Lebarc7445d52016-11-22 23:13:33 +0000896 auto &DA = getAnalysis<DivergenceAnalysis>();
897 if (hasOnlyUniformBranches(R, DA)) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000898 DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R << '\n');
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000899
900 // Mark all direct child block terminators as having been treated as
901 // uniform. To account for a possible future in which non-uniform
902 // sub-regions are treated more cleverly, indirect children are not
903 // marked as uniform.
904 MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
Justin Lebar1b60d702016-11-22 23:13:37 +0000905 for (RegionNode *E : R->elements()) {
906 if (E->isSubRegion())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000907 continue;
908
Justin Lebar1b60d702016-11-22 23:13:37 +0000909 if (Instruction *Term = E->getEntry()->getTerminator())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000910 Term->setMetadata("structurizecfg.uniform", MD);
911 }
912
Tom Stellard755a4e62016-02-10 00:39:37 +0000913 return false;
914 }
915 }
916
Tom Stellardf8794352012-12-19 22:10:31 +0000917 Func = R->getEntry()->getParent();
918 ParentRegion = R;
919
Chandler Carruth73523022014-01-13 13:07:17 +0000920 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000921 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +0000922
923 orderNodes();
924 collectInfos();
925 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000926 insertConditions(false);
927 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000928 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +0000929 rebuildSSA();
930
Tom Stellard048f14f2013-02-08 22:24:37 +0000931 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +0000932 Order.clear();
933 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000934 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000935 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000936 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000937 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000938 Loops.clear();
939 LoopPreds.clear();
940 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000941
942 return true;
943}
944
Tom Stellard755a4e62016-02-10 00:39:37 +0000945Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
946 return new StructurizeCFG(SkipUniformRegions);
Tom Stellardf8794352012-12-19 22:10:31 +0000947}