blob: 4f23e20d251dfccb1cee83903091e0dada2e0e61 [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 Stellard1f0dded2014-12-03 04:28:32 +000014#include "llvm/Analysis/LoopInfo.h"
Tom Stellardf8794352012-12-19 22:10:31 +000015#include "llvm/Analysis/RegionInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000016#include "llvm/Analysis/RegionIterator.h"
Tom Stellardf8794352012-12-19 22:10:31 +000017#include "llvm/Analysis/RegionPass.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Module.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000019#include "llvm/IR/PatternMatch.h"
Tom Stellard071ec902015-02-04 20:49:44 +000020#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000021#include "llvm/Support/raw_ostream.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000022#include "llvm/Transforms/Utils/SSAUpdater.h"
Tom Stellardf8794352012-12-19 22:10:31 +000023
24using namespace llvm;
Christian Konigd8860992013-02-16 11:27:50 +000025using namespace llvm::PatternMatch;
Tom Stellardf8794352012-12-19 22:10:31 +000026
Chandler Carruth964daaa2014-04-22 02:55:47 +000027#define DEBUG_TYPE "structurizecfg"
28
Tom Stellardf8794352012-12-19 22:10:31 +000029namespace {
30
31// Definition of the complex types used in this pass.
32
33typedef std::pair<BasicBlock *, Value *> BBValuePair;
Tom Stellardf8794352012-12-19 22:10:31 +000034
35typedef SmallVector<RegionNode*, 8> RNVector;
36typedef SmallVector<BasicBlock*, 8> BBVector;
Tom Stellard048f14f2013-02-08 22:24:37 +000037typedef SmallVector<BranchInst*, 8> BranchVector;
Tom Stellardf8794352012-12-19 22:10:31 +000038typedef SmallVector<BBValuePair, 2> BBValueVector;
39
Tom Stellard048f14f2013-02-08 22:24:37 +000040typedef SmallPtrSet<BasicBlock *, 8> BBSet;
41
Christian Konig90b45122013-03-26 10:24:20 +000042typedef MapVector<PHINode *, BBValueVector> PhiMap;
43typedef MapVector<BasicBlock *, BBVector> BB2BBVecMap;
44
Christian Konigd08e3d72013-02-16 11:27:29 +000045typedef DenseMap<DomTreeNode *, unsigned> DTN2UnsignedMap;
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.
52
Craig Topperd3a34f82013-07-16 01:17:10 +000053static const char *const FlowBlockName = "Flow";
Tom Stellardf8794352012-12-19 22:10:31 +000054
Christian Konigd08e3d72013-02-16 11:27:29 +000055/// @brief Find the nearest common dominator for multiple BasicBlocks
56///
Matt Arsenaultd46fce12013-06-19 20:18:24 +000057/// Helper class for StructurizeCFG
Christian Konigd08e3d72013-02-16 11:27:29 +000058/// TODO: Maybe move into common code
59class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000060 DominatorTree *DT;
61
62 DTN2UnsignedMap IndexMap;
63
64 BasicBlock *Result;
65 unsigned ResultIndex;
66 bool ExplicitMentioned;
67
68public:
69 /// \brief Start a new query
70 NearestCommonDominator(DominatorTree *DomTree) {
71 DT = DomTree;
Craig Topperf40110f2014-04-25 05:29:35 +000072 Result = nullptr;
Christian Konigd08e3d72013-02-16 11:27:29 +000073 }
74
75 /// \brief Add BB to the resulting dominator
76 void addBlock(BasicBlock *BB, bool Remember = true) {
Christian Konigd08e3d72013-02-16 11:27:29 +000077 DomTreeNode *Node = DT->getNode(BB);
78
Craig Topperf40110f2014-04-25 05:29:35 +000079 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000080 unsigned Numbering = 0;
81 for (;Node;Node = Node->getIDom())
82 IndexMap[Node] = ++Numbering;
83 Result = BB;
84 ResultIndex = 1;
85 ExplicitMentioned = Remember;
86 return;
87 }
88
89 for (;Node;Node = Node->getIDom())
90 if (IndexMap.count(Node))
91 break;
92 else
93 IndexMap[Node] = 0;
94
95 assert(Node && "Dominator tree invalid!");
96
97 unsigned Numbering = IndexMap[Node];
98 if (Numbering > ResultIndex) {
99 Result = Node->getBlock();
100 ResultIndex = Numbering;
101 ExplicitMentioned = Remember && (Result == BB);
102 } else if (Numbering == ResultIndex) {
103 ExplicitMentioned |= Remember;
104 }
105 }
106
107 /// \brief Is "Result" one of the BBs added with "Remember" = True?
108 bool wasResultExplicitMentioned() {
109 return ExplicitMentioned;
110 }
111
112 /// \brief Get the query result
113 BasicBlock *getResult() {
114 return Result;
115 }
116};
117
Tom Stellardf8794352012-12-19 22:10:31 +0000118/// @brief Transforms the control flow graph on one single entry/exit region
119/// at a time.
120///
121/// After the transform all "If"/"Then"/"Else" style control flow looks like
122/// this:
123///
124/// \verbatim
125/// 1
126/// ||
127/// | |
128/// 2 |
129/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000130/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000131/// 3
132/// || Where:
133/// | | 1 = "If" block, calculates the condition
134/// 4 | 2 = "Then" subregion, runs if the condition is true
135/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
136/// |/ 4 = "Else" optional subregion, runs if the condition is false
137/// 5 5 = "End" block, also rejoins the control flow
138/// \endverbatim
139///
140/// Control flow is expressed as a branch where the true exit goes into the
141/// "Then"/"Else" region, while the false exit skips the region
142/// The condition for the optional "Else" region is expressed as a PHI node.
143/// The incomming values of the PHI node are true for the "If" edge and false
144/// for the "Then" edge.
145///
146/// Additionally to that even complicated loops look like this:
147///
148/// \verbatim
149/// 1
150/// ||
151/// | |
152/// 2 ^ Where:
153/// | / 1 = "Entry" block
154/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
155/// 3 3 = "Flow" block, with back edge to entry block
156/// |
157/// \endverbatim
158///
159/// The back edge of the "Flow" block is always on the false side of the branch
160/// while the true side continues the general flow. So the loop condition
161/// consist of a network of PHI nodes where the true incoming values expresses
162/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000163class StructurizeCFG : public RegionPass {
Tom Stellardf8794352012-12-19 22:10:31 +0000164 Type *Boolean;
165 ConstantInt *BoolTrue;
166 ConstantInt *BoolFalse;
167 UndefValue *BoolUndef;
168
169 Function *Func;
170 Region *ParentRegion;
171
172 DominatorTree *DT;
Tom Stellard1f0dded2014-12-03 04:28:32 +0000173 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000174
175 RNVector Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000176 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000177
Tom Stellardf8794352012-12-19 22:10:31 +0000178 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000179 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000180
181 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000182 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000183
Christian Konigfc6a9852013-02-16 11:27:45 +0000184 BB2BBMap Loops;
185 PredMap LoopPreds;
186 BranchVector LoopConds;
187
188 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000189
190 void orderNodes();
191
Christian Konigfc6a9852013-02-16 11:27:45 +0000192 void analyzeLoops(RegionNode *N);
193
Christian Konigd8860992013-02-16 11:27:50 +0000194 Value *invert(Value *Condition);
195
Tom Stellard048f14f2013-02-08 22:24:37 +0000196 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000197
Christian Konigfc6a9852013-02-16 11:27:45 +0000198 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000199
200 void collectInfos();
201
Christian Konigfc6a9852013-02-16 11:27:45 +0000202 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000203
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000204 void delPhiValues(BasicBlock *From, BasicBlock *To);
205
206 void addPhiValues(BasicBlock *From, BasicBlock *To);
207
208 void setPhiValues();
209
Tom Stellardf8794352012-12-19 22:10:31 +0000210 void killTerminator(BasicBlock *BB);
211
Tom Stellard7370ede2013-02-08 22:24:38 +0000212 void changeExit(RegionNode *Node, BasicBlock *NewExit,
213 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000214
Tom Stellard7370ede2013-02-08 22:24:38 +0000215 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000216
Christian Konigfc6a9852013-02-16 11:27:45 +0000217 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000218
Tom Stellard7370ede2013-02-08 22:24:38 +0000219 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
220
Christian Konigfc6a9852013-02-16 11:27:45 +0000221 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000222
223 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
224
Christian Konigfc6a9852013-02-16 11:27:45 +0000225 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000226
Christian Konigfc6a9852013-02-16 11:27:45 +0000227 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
228
229 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000230
231 void createFlow();
232
Tom Stellardf8794352012-12-19 22:10:31 +0000233 void rebuildSSA();
234
235public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000236 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000237
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000238 StructurizeCFG() :
239 RegionPass(ID) {
Tom Stellardd3e916e2013-10-02 17:04:59 +0000240 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
Tom Stellardf8794352012-12-19 22:10:31 +0000241 }
242
Christian Konig01fd1f62013-03-01 09:46:11 +0000243 using Pass::doInitialization;
Craig Topper3e4c6972014-03-05 09:10:37 +0000244 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000245
Craig Topper3e4c6972014-03-05 09:10:37 +0000246 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000247
Craig Topper3e4c6972014-03-05 09:10:37 +0000248 const char *getPassName() const override {
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000249 return "Structurize control flow";
Tom Stellardf8794352012-12-19 22:10:31 +0000250 }
251
Craig Topper3e4c6972014-03-05 09:10:37 +0000252 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellardd3e916e2013-10-02 17:04:59 +0000253 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000254 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000255 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000256 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000257 RegionPass::getAnalysisUsage(AU);
258 }
Tom Stellardf8794352012-12-19 22:10:31 +0000259};
260
261} // end anonymous namespace
262
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000263char StructurizeCFG::ID = 0;
264
265INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
266 false, false)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000267INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000268INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000269INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000270INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
271 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000272
273/// \brief Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000274bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000275 LLVMContext &Context = R->getEntry()->getContext();
276
277 Boolean = Type::getInt1Ty(Context);
278 BoolTrue = ConstantInt::getTrue(Context);
279 BoolFalse = ConstantInt::getFalse(Context);
280 BoolUndef = UndefValue::get(Boolean);
281
282 return false;
283}
284
285/// \brief Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000286void StructurizeCFG::orderNodes() {
Tom Stellard071ec902015-02-04 20:49:44 +0000287 RNVector TempOrder;
288 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
289 TempOrder.append(RPOT.begin(), RPOT.end());
290
291 std::map<Loop*, unsigned> LoopBlocks;
292
293
294 // The reverse post-order traversal of the list gives us an ordering close
295 // to what we want. The only problem with it is that sometimes backedges
296 // for outer loops will be visited before backedges for inner loops.
297 for (RegionNode *RN : TempOrder) {
298 BasicBlock *BB = RN->getEntry();
299 Loop *Loop = LI->getLoopFor(BB);
300 if (!LoopBlocks.count(Loop)) {
301 LoopBlocks[Loop] = 1;
302 continue;
303 }
304 LoopBlocks[Loop]++;
Tom Stellardf8794352012-12-19 22:10:31 +0000305 }
Tom Stellard071ec902015-02-04 20:49:44 +0000306
307 unsigned CurrentLoopDepth = 0;
308 Loop *CurrentLoop = nullptr;
309 BBSet TempVisited;
310 for (RNVector::iterator I = TempOrder.begin(), E = TempOrder.end(); I != E; ++I) {
311 BasicBlock *BB = (*I)->getEntry();
312 unsigned LoopDepth = LI->getLoopDepth(BB);
313
314 if (std::find(Order.begin(), Order.end(), *I) != Order.end())
315 continue;
316
317 if (LoopDepth < CurrentLoopDepth) {
318 // Make sure we have visited all blocks in this loop before moving back to
319 // the outer loop.
320
321 RNVector::iterator LoopI = I;
322 while(LoopBlocks[CurrentLoop]) {
323 LoopI++;
324 BasicBlock *LoopBB = (*LoopI)->getEntry();
325 if (LI->getLoopFor(LoopBB) == CurrentLoop) {
326 LoopBlocks[CurrentLoop]--;
327 Order.push_back(*LoopI);
328 }
329 }
330 }
331
332 CurrentLoop = LI->getLoopFor(BB);
333 if (CurrentLoop) {
334 LoopBlocks[CurrentLoop]--;
335 }
336
337 CurrentLoopDepth = LoopDepth;
338 Order.push_back(*I);
339 }
340
341 // This pass originally used a post-order traversal and then operated on
342 // the list in reverse. Now that we are using a reverse post-order traversal
343 // rather than re-working the whole pass to operate on the list in order,
344 // we just reverse the list and continue to operate on it in reverse.
345 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000346}
347
Christian Konigfc6a9852013-02-16 11:27:45 +0000348/// \brief Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000349void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000350 if (N->isSubRegion()) {
351 // Test for exit as back edge
352 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
353 if (Visited.count(Exit))
354 Loops[Exit] = N->getEntry();
355
356 } else {
357 // Test for sucessors as back edge
358 BasicBlock *BB = N->getNodeAs<BasicBlock>();
359 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
360
361 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
362 BasicBlock *Succ = Term->getSuccessor(i);
363
Tom Stellard080209d2015-02-04 20:49:47 +0000364 if (Visited.count(Succ)) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000365 Loops[Succ] = BB;
Tom Stellard1f0dded2014-12-03 04:28:32 +0000366 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000367 }
368 }
369}
370
Christian Konigd8860992013-02-16 11:27:50 +0000371/// \brief Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000372Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000373 // First: Check if it's a constant
374 if (Condition == BoolTrue)
375 return BoolFalse;
376
377 if (Condition == BoolFalse)
378 return BoolTrue;
379
380 if (Condition == BoolUndef)
381 return BoolUndef;
382
383 // Second: If the condition is already inverted, return the original value
384 if (match(Condition, m_Not(m_Value(Condition))))
385 return Condition;
386
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000387 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
388 // Third: Check all the users for an invert
389 BasicBlock *Parent = Inst->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000390 for (User *U : Condition->users())
391 if (Instruction *I = dyn_cast<Instruction>(U))
392 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
393 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000394
395 // Last option: Create a new instruction
396 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000397 }
398
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000399 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
400 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
401 return BinaryOperator::CreateNot(Condition,
402 Arg->getName() + ".inv",
403 EntryBlock.getTerminator());
404 }
405
406 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000407}
408
Tom Stellard048f14f2013-02-08 22:24:37 +0000409/// \brief Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000410Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
411 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000412 Value *Cond = Invert ? BoolFalse : BoolTrue;
413 if (Term->isConditional()) {
414 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000415
Aaron Ballman19978552013-06-04 01:03:03 +0000416 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000417 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000418 }
419 return Cond;
420}
421
Tom Stellard048f14f2013-02-08 22:24:37 +0000422/// \brief Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000423void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000424 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000425 BasicBlock *BB = N->getEntry();
426 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000427 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000428
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000429 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
430 PI != PE; ++PI) {
431
Christian Konigfc6a9852013-02-16 11:27:45 +0000432 // Ignore it if it's a branch from outside into our region entry
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000433 if (!ParentRegion->contains(*PI))
Tom Stellard048f14f2013-02-08 22:24:37 +0000434 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000435
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000436 Region *R = RI->getRegionFor(*PI);
Tom Stellard048f14f2013-02-08 22:24:37 +0000437 if (R == ParentRegion) {
Tom Stellardf8794352012-12-19 22:10:31 +0000438
Tom Stellard048f14f2013-02-08 22:24:37 +0000439 // It's a top level block in our region
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000440 BranchInst *Term = cast<BranchInst>((*PI)->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000441 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
442 BasicBlock *Succ = Term->getSuccessor(i);
443 if (Succ != BB)
444 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000445
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000446 if (Visited.count(*PI)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000447 // Normal forward edge
448 if (Term->isConditional()) {
449 // Try to treat it like an ELSE block
450 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000451 if (Visited.count(Other) && !Loops.count(Other) &&
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000452 !Pred.count(Other) && !Pred.count(*PI)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000453
Tom Stellard048f14f2013-02-08 22:24:37 +0000454 Pred[Other] = BoolFalse;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000455 Pred[*PI] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000456 continue;
457 }
458 }
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000459 Pred[*PI] = buildCondition(Term, i, false);
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000460
Tom Stellard048f14f2013-02-08 22:24:37 +0000461 } else {
462 // Back edge
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000463 LPred[*PI] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000464 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000465 }
466
467 } else {
468
469 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000470 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000471 R = R->getParent();
472
473 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000474 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000475 continue;
476
477 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000478 if (Visited.count(Entry))
479 Pred[Entry] = BoolTrue;
480 else
481 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000482 }
483 }
484}
485
486/// \brief Collect various loop and predicate infos
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000487void StructurizeCFG::collectInfos() {
Tom Stellardf8794352012-12-19 22:10:31 +0000488 // Reset predicate
489 Predicates.clear();
490
491 // and loop infos
Christian Konigfc6a9852013-02-16 11:27:45 +0000492 Loops.clear();
493 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000494
Tom Stellard048f14f2013-02-08 22:24:37 +0000495 // Reset the visited nodes
496 Visited.clear();
497
498 for (RNVector::reverse_iterator OI = Order.rbegin(), OE = Order.rend();
499 OI != OE; ++OI) {
Tom Stellardf8794352012-12-19 22:10:31 +0000500
Tom Stellard071ec902015-02-04 20:49:44 +0000501 DEBUG(dbgs() << "Visiting: " <<
502 ((*OI)->isSubRegion() ? "SubRegion with entry: " : "") <<
503 (*OI)->getEntry()->getName() << " Loop Depth: " << LI->getLoopDepth((*OI)->getEntry()) << "\n");
504
Tom Stellardf8794352012-12-19 22:10:31 +0000505 // Analyze all the conditions leading to a node
Christian Konigfc6a9852013-02-16 11:27:45 +0000506 gatherPredicates(*OI);
Tom Stellardf8794352012-12-19 22:10:31 +0000507
Tom Stellard048f14f2013-02-08 22:24:37 +0000508 // Remember that we've seen this node
Tom Stellard7370ede2013-02-08 22:24:38 +0000509 Visited.insert((*OI)->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000510
Christian Konigfc6a9852013-02-16 11:27:45 +0000511 // Find the last back edges
512 analyzeLoops(*OI);
Tom Stellard048f14f2013-02-08 22:24:37 +0000513 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000514}
515
516/// \brief Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000517void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000518 BranchVector &Conds = Loops ? LoopConds : Conditions;
519 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000520 SSAUpdater PhiInserter;
521
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000522 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000523 assert(Term->isConditional());
524
Christian Konigfc6a9852013-02-16 11:27:45 +0000525 BasicBlock *Parent = Term->getParent();
526 BasicBlock *SuccTrue = Term->getSuccessor(0);
527 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000528
Christian Konigb5d88662013-02-16 11:27:40 +0000529 PhiInserter.Initialize(Boolean, "");
530 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000531 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000532
Christian Konigfc6a9852013-02-16 11:27:45 +0000533 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000534
535 NearestCommonDominator Dominator(DT);
536 Dominator.addBlock(Parent, false);
537
Craig Topperf40110f2014-04-25 05:29:35 +0000538 Value *ParentValue = nullptr;
Tom Stellard048f14f2013-02-08 22:24:37 +0000539 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
540 PI != PE; ++PI) {
541
Christian Konigb5d88662013-02-16 11:27:40 +0000542 if (PI->first == Parent) {
543 ParentValue = PI->second;
544 break;
545 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000546 PhiInserter.AddAvailableValue(PI->first, PI->second);
Christian Konigb5d88662013-02-16 11:27:40 +0000547 Dominator.addBlock(PI->first);
Tom Stellard048f14f2013-02-08 22:24:37 +0000548 }
549
Christian Konigb5d88662013-02-16 11:27:40 +0000550 if (ParentValue) {
551 Term->setCondition(ParentValue);
552 } else {
553 if (!Dominator.wasResultExplicitMentioned())
554 PhiInserter.AddAvailableValue(Dominator.getResult(), Default);
555
Tom Stellard048f14f2013-02-08 22:24:37 +0000556 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000557 }
Tom Stellardf8794352012-12-19 22:10:31 +0000558 }
559}
560
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000561/// \brief Remove all PHI values coming from "From" into "To" and remember
562/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000563void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000564 PhiMap &Map = DeletedPhis[To];
565 for (BasicBlock::iterator I = To->begin(), E = To->end();
566 I != E && isa<PHINode>(*I);) {
567
568 PHINode &Phi = cast<PHINode>(*I++);
569 while (Phi.getBasicBlockIndex(From) != -1) {
570 Value *Deleted = Phi.removeIncomingValue(From, false);
571 Map[&Phi].push_back(std::make_pair(From, Deleted));
572 }
573 }
574}
575
576/// \brief Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000577void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000578 for (BasicBlock::iterator I = To->begin(), E = To->end();
579 I != E && isa<PHINode>(*I);) {
580
581 PHINode &Phi = cast<PHINode>(*I++);
582 Value *Undef = UndefValue::get(Phi.getType());
583 Phi.addIncoming(Undef, From);
584 }
585 AddedPhis[To].push_back(From);
586}
587
588/// \brief Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000589void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000590 SSAUpdater Updater;
591 for (BB2BBVecMap::iterator AI = AddedPhis.begin(), AE = AddedPhis.end();
592 AI != AE; ++AI) {
593
594 BasicBlock *To = AI->first;
595 BBVector &From = AI->second;
596
597 if (!DeletedPhis.count(To))
598 continue;
599
600 PhiMap &Map = DeletedPhis[To];
601 for (PhiMap::iterator PI = Map.begin(), PE = Map.end();
602 PI != PE; ++PI) {
603
604 PHINode *Phi = PI->first;
605 Value *Undef = UndefValue::get(Phi->getType());
606 Updater.Initialize(Phi->getType(), "");
607 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
608 Updater.AddAvailableValue(To, Undef);
609
Christian Konig0bccf9d2013-02-16 11:27:35 +0000610 NearestCommonDominator Dominator(DT);
611 Dominator.addBlock(To, false);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000612 for (BBValueVector::iterator VI = PI->second.begin(),
613 VE = PI->second.end(); VI != VE; ++VI) {
614
615 Updater.AddAvailableValue(VI->first, VI->second);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000616 Dominator.addBlock(VI->first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000617 }
618
Christian Konig0bccf9d2013-02-16 11:27:35 +0000619 if (!Dominator.wasResultExplicitMentioned())
620 Updater.AddAvailableValue(Dominator.getResult(), Undef);
621
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000622 for (BBVector::iterator FI = From.begin(), FE = From.end();
623 FI != FE; ++FI) {
624
625 int Idx = Phi->getBasicBlockIndex(*FI);
626 assert(Idx != -1);
627 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(*FI));
628 }
629 }
630
631 DeletedPhis.erase(To);
632 }
633 assert(DeletedPhis.empty());
634}
635
Tom Stellard7370ede2013-02-08 22:24:38 +0000636/// \brief Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000637void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000638 TerminatorInst *Term = BB->getTerminator();
639 if (!Term)
640 return;
641
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000642 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
643 SI != SE; ++SI) {
644
645 delPhiValues(BB, *SI);
646 }
Tom Stellardf8794352012-12-19 22:10:31 +0000647
648 Term->eraseFromParent();
649}
650
Tom Stellard7370ede2013-02-08 22:24:38 +0000651/// \brief Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000652void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
653 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000654 if (Node->isSubRegion()) {
655 Region *SubRegion = Node->getNodeAs<Region>();
656 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000657 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000658
Tom Stellard7370ede2013-02-08 22:24:38 +0000659 // Find all the edges from the sub region to the exit
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000660 for (pred_iterator I = pred_begin(OldExit), E = pred_end(OldExit);
661 I != E;) {
662
663 BasicBlock *BB = *I++;
Tom Stellard7370ede2013-02-08 22:24:38 +0000664 if (!SubRegion->contains(BB))
665 continue;
666
667 // Modify the edges to point to the new exit
668 delPhiValues(BB, OldExit);
669 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
670 addPhiValues(BB, NewExit);
671
672 // Find the new dominator (if requested)
673 if (IncludeDominator) {
674 if (!Dominator)
675 Dominator = BB;
676 else
677 Dominator = DT->findNearestCommonDominator(Dominator, BB);
678 }
Tom Stellardf8794352012-12-19 22:10:31 +0000679 }
680
Tom Stellard7370ede2013-02-08 22:24:38 +0000681 // Change the dominator (if requested)
682 if (Dominator)
683 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000684
Tom Stellard7370ede2013-02-08 22:24:38 +0000685 // Update the region info
686 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000687
Tom Stellardf8794352012-12-19 22:10:31 +0000688 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000689 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
690 killTerminator(BB);
691 BranchInst::Create(NewExit, BB);
692 addPhiValues(BB, NewExit);
693 if (IncludeDominator)
694 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000695 }
Tom Stellardf8794352012-12-19 22:10:31 +0000696}
697
Tom Stellardf8794352012-12-19 22:10:31 +0000698/// \brief Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000699BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000700 LLVMContext &Context = Func->getContext();
701 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
702 Order.back()->getEntry();
703 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
704 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000705 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000706 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000707 return Flow;
708}
709
Tom Stellard7370ede2013-02-08 22:24:38 +0000710/// \brief Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000711BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000712 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000713
Christian Konigfc6a9852013-02-16 11:27:45 +0000714 if (!PrevNode->isSubRegion()) {
715 killTerminator(Entry);
716 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
717 return Entry;
Tom Stellard7370ede2013-02-08 22:24:38 +0000718
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000719 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000720
Christian Konigfc6a9852013-02-16 11:27:45 +0000721 // create a new flow node
722 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000723
Christian Konigfc6a9852013-02-16 11:27:45 +0000724 // and wire it up
725 changeExit(PrevNode, Flow, true);
726 PrevNode = ParentRegion->getBBNode(Flow);
727 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000728}
729
730/// \brief Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000731BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
732 bool ExitUseAllowed) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000733 if (Order.empty() && ExitUseAllowed) {
734 BasicBlock *Exit = ParentRegion->getExit();
735 DT->changeImmediateDominator(Exit, Flow);
736 addPhiValues(Flow, Exit);
737 return Exit;
738 }
739 return getNextFlow(Flow);
740}
741
Christian Konigfc6a9852013-02-16 11:27:45 +0000742/// \brief Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000743void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000744 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
745 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000746}
747
748/// \brief Does BB dominate all the predicates of Node ?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000749bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000750 BBPredicates &Preds = Predicates[Node->getEntry()];
751 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
752 PI != PE; ++PI) {
753
754 if (!DT->dominates(BB, PI->first))
755 return false;
756 }
757 return true;
758}
759
Tom Stellardf8794352012-12-19 22:10:31 +0000760/// \brief Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000761bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000762 BBPredicates &Preds = Predicates[Node->getEntry()];
763 bool Dominated = false;
764
765 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000766 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000767 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000768
769 for (BBPredicates::iterator I = Preds.begin(), E = Preds.end();
770 I != E; ++I) {
771
772 if (I->second != BoolTrue)
773 return false;
774
Christian Konigfc6a9852013-02-16 11:27:45 +0000775 if (!Dominated && DT->dominates(I->first, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000776 Dominated = true;
777 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000778
779 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000780 return Dominated;
781}
782
Tom Stellard7370ede2013-02-08 22:24:38 +0000783/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000784void StructurizeCFG::wireFlow(bool ExitUseAllowed,
785 BasicBlock *LoopEnd) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000786 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000787 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000788
Christian Konigfc6a9852013-02-16 11:27:45 +0000789 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000790 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000791 if (PrevNode) {
792 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000793 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000794 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000795
796 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000797 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000798 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000799
Tom Stellard7370ede2013-02-08 22:24:38 +0000800 // Insert extra postfix node (or use exit instead)
801 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000802 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000803
804 // let it point to entry and next block
805 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
806 addPhiValues(Flow, Entry);
807 DT->changeImmediateDominator(Entry, Flow);
808
Christian Konigfc6a9852013-02-16 11:27:45 +0000809 PrevNode = Node;
810 while (!Order.empty() && !Visited.count(LoopEnd) &&
Tom Stellard7370ede2013-02-08 22:24:38 +0000811 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000812 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000813 }
814
Christian Konigfc6a9852013-02-16 11:27:45 +0000815 changeExit(PrevNode, Next, false);
816 setPrevNode(Next);
817 }
818}
819
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000820void StructurizeCFG::handleLoops(bool ExitUseAllowed,
821 BasicBlock *LoopEnd) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000822 RegionNode *Node = Order.back();
823 BasicBlock *LoopStart = Node->getEntry();
824
825 if (!Loops.count(LoopStart)) {
826 wireFlow(ExitUseAllowed, LoopEnd);
827 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000828 }
829
Christian Konigfc6a9852013-02-16 11:27:45 +0000830 if (!isPredictableTrue(Node))
831 LoopStart = needPrefix(true);
832
833 LoopEnd = Loops[Node->getEntry()];
834 wireFlow(false, LoopEnd);
835 while (!Visited.count(LoopEnd)) {
836 handleLoops(false, LoopEnd);
837 }
838
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000839 // If the start of the loop is the entry block, we can't branch to it so
840 // insert a new dummy entry block.
841 Function *LoopFunc = LoopStart->getParent();
842 if (LoopStart == &LoopFunc->getEntryBlock()) {
843 LoopStart->setName("entry.orig");
844
845 BasicBlock *NewEntry =
846 BasicBlock::Create(LoopStart->getContext(),
847 "entry",
848 LoopFunc,
849 LoopStart);
850 BranchInst::Create(LoopStart, NewEntry);
851 }
852
Christian Konigfc6a9852013-02-16 11:27:45 +0000853 // Create an extra loop end node
854 LoopEnd = needPrefix(false);
855 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
856 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
857 BoolUndef, LoopEnd));
858 addPhiValues(LoopEnd, LoopStart);
859 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000860}
861
Tom Stellardf8794352012-12-19 22:10:31 +0000862/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000863/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000864void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000865 BasicBlock *Exit = ParentRegion->getExit();
866 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
867
Tom Stellardf8794352012-12-19 22:10:31 +0000868 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000869 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000870 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000871 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000872
Craig Topperf40110f2014-04-25 05:29:35 +0000873 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000874 Visited.clear();
875
Tom Stellardf8794352012-12-19 22:10:31 +0000876 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000877 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000878 }
879
Christian Konigfc6a9852013-02-16 11:27:45 +0000880 if (PrevNode)
881 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000882 else
883 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000884}
885
Tom Stellardf8794352012-12-19 22:10:31 +0000886/// Handle a rare case where the disintegrated nodes instructions
887/// no longer dominate all their uses. Not sure if this is really nessasary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000888void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000889 SSAUpdater Updater;
Richard Trieu6b1aa5f2015-04-15 01:21:15 +0000890 for (auto *BB : ParentRegion->blocks())
Tom Stellardf8794352012-12-19 22:10:31 +0000891 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
892 II != IE; ++II) {
893
894 bool Initialized = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000895 for (auto I = II->use_begin(), E = II->use_end(); I != E;) {
896 Use &U = *I++;
897 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000898 if (User->getParent() == BB) {
899 continue;
900
901 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000902 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000903 continue;
904 }
905
906 if (DT->dominates(II, User))
907 continue;
908
909 if (!Initialized) {
910 Value *Undef = UndefValue::get(II->getType());
911 Updater.Initialize(II->getType(), "");
912 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
913 Updater.AddAvailableValue(BB, II);
914 Initialized = true;
915 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000916 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000917 }
918 }
Tom Stellardf8794352012-12-19 22:10:31 +0000919}
920
921/// \brief Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000922bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000923 if (R->isTopLevelRegion())
924 return false;
925
926 Func = R->getEntry()->getParent();
927 ParentRegion = R;
928
Chandler Carruth73523022014-01-13 13:07:17 +0000929 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000930 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +0000931
932 orderNodes();
933 collectInfos();
934 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000935 insertConditions(false);
936 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000937 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +0000938 rebuildSSA();
939
Tom Stellard048f14f2013-02-08 22:24:37 +0000940 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +0000941 Order.clear();
942 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000943 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000944 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000945 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000946 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000947 Loops.clear();
948 LoopPreds.clear();
949 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000950
951 return true;
952}
953
954/// \brief Create the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000955Pass *llvm::createStructurizeCFGPass() {
956 return new StructurizeCFG();
Tom Stellardf8794352012-12-19 22:10:31 +0000957}