blob: 65e1a8b1d474acd3984f44cbae1b4e99143f3666 [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"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000012#include "llvm/ADT/SCCIterator.h"
Tom Stellardf8794352012-12-19 22:10:31 +000013#include "llvm/Analysis/RegionInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000014#include "llvm/Analysis/RegionIterator.h"
Tom Stellardf8794352012-12-19 22:10:31 +000015#include "llvm/Analysis/RegionPass.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/Module.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000017#include "llvm/IR/PatternMatch.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000018#include "llvm/Transforms/Utils/SSAUpdater.h"
Tom Stellardf8794352012-12-19 22:10:31 +000019
20using namespace llvm;
Christian Konigd8860992013-02-16 11:27:50 +000021using namespace llvm::PatternMatch;
Tom Stellardf8794352012-12-19 22:10:31 +000022
Chandler Carruth964daaa2014-04-22 02:55:47 +000023#define DEBUG_TYPE "structurizecfg"
24
Tom Stellardf8794352012-12-19 22:10:31 +000025namespace {
26
27// Definition of the complex types used in this pass.
28
29typedef std::pair<BasicBlock *, Value *> BBValuePair;
Tom Stellardf8794352012-12-19 22:10:31 +000030
31typedef SmallVector<RegionNode*, 8> RNVector;
32typedef SmallVector<BasicBlock*, 8> BBVector;
Tom Stellard048f14f2013-02-08 22:24:37 +000033typedef SmallVector<BranchInst*, 8> BranchVector;
Tom Stellardf8794352012-12-19 22:10:31 +000034typedef SmallVector<BBValuePair, 2> BBValueVector;
35
Tom Stellard048f14f2013-02-08 22:24:37 +000036typedef SmallPtrSet<BasicBlock *, 8> BBSet;
37
Christian Konig90b45122013-03-26 10:24:20 +000038typedef MapVector<PHINode *, BBValueVector> PhiMap;
39typedef MapVector<BasicBlock *, BBVector> BB2BBVecMap;
40
Christian Konigd08e3d72013-02-16 11:27:29 +000041typedef DenseMap<DomTreeNode *, unsigned> DTN2UnsignedMap;
Tom Stellardf8794352012-12-19 22:10:31 +000042typedef DenseMap<BasicBlock *, PhiMap> BBPhiMap;
43typedef DenseMap<BasicBlock *, Value *> BBPredicates;
44typedef DenseMap<BasicBlock *, BBPredicates> PredMap;
Christian Konigfc6a9852013-02-16 11:27:45 +000045typedef DenseMap<BasicBlock *, BasicBlock*> BB2BBMap;
Tom Stellardf8794352012-12-19 22:10:31 +000046
47// The name for newly created blocks.
48
Craig Topperd3a34f82013-07-16 01:17:10 +000049static const char *const FlowBlockName = "Flow";
Tom Stellardf8794352012-12-19 22:10:31 +000050
Christian Konigd08e3d72013-02-16 11:27:29 +000051/// @brief Find the nearest common dominator for multiple BasicBlocks
52///
Matt Arsenaultd46fce12013-06-19 20:18:24 +000053/// Helper class for StructurizeCFG
Christian Konigd08e3d72013-02-16 11:27:29 +000054/// TODO: Maybe move into common code
55class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000056 DominatorTree *DT;
57
58 DTN2UnsignedMap IndexMap;
59
60 BasicBlock *Result;
61 unsigned ResultIndex;
62 bool ExplicitMentioned;
63
64public:
65 /// \brief Start a new query
66 NearestCommonDominator(DominatorTree *DomTree) {
67 DT = DomTree;
Craig Topperf40110f2014-04-25 05:29:35 +000068 Result = nullptr;
Christian Konigd08e3d72013-02-16 11:27:29 +000069 }
70
71 /// \brief Add BB to the resulting dominator
72 void addBlock(BasicBlock *BB, bool Remember = true) {
Christian Konigd08e3d72013-02-16 11:27:29 +000073 DomTreeNode *Node = DT->getNode(BB);
74
Craig Topperf40110f2014-04-25 05:29:35 +000075 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000076 unsigned Numbering = 0;
77 for (;Node;Node = Node->getIDom())
78 IndexMap[Node] = ++Numbering;
79 Result = BB;
80 ResultIndex = 1;
81 ExplicitMentioned = Remember;
82 return;
83 }
84
85 for (;Node;Node = Node->getIDom())
86 if (IndexMap.count(Node))
87 break;
88 else
89 IndexMap[Node] = 0;
90
91 assert(Node && "Dominator tree invalid!");
92
93 unsigned Numbering = IndexMap[Node];
94 if (Numbering > ResultIndex) {
95 Result = Node->getBlock();
96 ResultIndex = Numbering;
97 ExplicitMentioned = Remember && (Result == BB);
98 } else if (Numbering == ResultIndex) {
99 ExplicitMentioned |= Remember;
100 }
101 }
102
103 /// \brief Is "Result" one of the BBs added with "Remember" = True?
104 bool wasResultExplicitMentioned() {
105 return ExplicitMentioned;
106 }
107
108 /// \brief Get the query result
109 BasicBlock *getResult() {
110 return Result;
111 }
112};
113
Tom Stellardf8794352012-12-19 22:10:31 +0000114/// @brief Transforms the control flow graph on one single entry/exit region
115/// at a time.
116///
117/// After the transform all "If"/"Then"/"Else" style control flow looks like
118/// this:
119///
120/// \verbatim
121/// 1
122/// ||
123/// | |
124/// 2 |
125/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000126/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000127/// 3
128/// || Where:
129/// | | 1 = "If" block, calculates the condition
130/// 4 | 2 = "Then" subregion, runs if the condition is true
131/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
132/// |/ 4 = "Else" optional subregion, runs if the condition is false
133/// 5 5 = "End" block, also rejoins the control flow
134/// \endverbatim
135///
136/// Control flow is expressed as a branch where the true exit goes into the
137/// "Then"/"Else" region, while the false exit skips the region
138/// The condition for the optional "Else" region is expressed as a PHI node.
139/// The incomming values of the PHI node are true for the "If" edge and false
140/// for the "Then" edge.
141///
142/// Additionally to that even complicated loops look like this:
143///
144/// \verbatim
145/// 1
146/// ||
147/// | |
148/// 2 ^ Where:
149/// | / 1 = "Entry" block
150/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
151/// 3 3 = "Flow" block, with back edge to entry block
152/// |
153/// \endverbatim
154///
155/// The back edge of the "Flow" block is always on the false side of the branch
156/// while the true side continues the general flow. So the loop condition
157/// consist of a network of PHI nodes where the true incoming values expresses
158/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000159class StructurizeCFG : public RegionPass {
Tom Stellardf8794352012-12-19 22:10:31 +0000160 Type *Boolean;
161 ConstantInt *BoolTrue;
162 ConstantInt *BoolFalse;
163 UndefValue *BoolUndef;
164
165 Function *Func;
166 Region *ParentRegion;
167
168 DominatorTree *DT;
169
170 RNVector Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000171 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000172
Tom Stellardf8794352012-12-19 22:10:31 +0000173 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000174 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000175
176 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000177 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000178
Christian Konigfc6a9852013-02-16 11:27:45 +0000179 BB2BBMap Loops;
180 PredMap LoopPreds;
181 BranchVector LoopConds;
182
183 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000184
185 void orderNodes();
186
Christian Konigfc6a9852013-02-16 11:27:45 +0000187 void analyzeLoops(RegionNode *N);
188
Christian Konigd8860992013-02-16 11:27:50 +0000189 Value *invert(Value *Condition);
190
Tom Stellard048f14f2013-02-08 22:24:37 +0000191 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000192
Christian Konigfc6a9852013-02-16 11:27:45 +0000193 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000194
195 void collectInfos();
196
Christian Konigfc6a9852013-02-16 11:27:45 +0000197 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000198
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000199 void delPhiValues(BasicBlock *From, BasicBlock *To);
200
201 void addPhiValues(BasicBlock *From, BasicBlock *To);
202
203 void setPhiValues();
204
Tom Stellardf8794352012-12-19 22:10:31 +0000205 void killTerminator(BasicBlock *BB);
206
Tom Stellard7370ede2013-02-08 22:24:38 +0000207 void changeExit(RegionNode *Node, BasicBlock *NewExit,
208 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000209
Tom Stellard7370ede2013-02-08 22:24:38 +0000210 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000211
Christian Konigfc6a9852013-02-16 11:27:45 +0000212 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000213
Tom Stellard7370ede2013-02-08 22:24:38 +0000214 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
215
Christian Konigfc6a9852013-02-16 11:27:45 +0000216 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000217
218 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
219
Christian Konigfc6a9852013-02-16 11:27:45 +0000220 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000221
Christian Konigfc6a9852013-02-16 11:27:45 +0000222 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
223
224 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000225
226 void createFlow();
227
Tom Stellardf8794352012-12-19 22:10:31 +0000228 void rebuildSSA();
229
230public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000231 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000232
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000233 StructurizeCFG() :
234 RegionPass(ID) {
Tom Stellardd3e916e2013-10-02 17:04:59 +0000235 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
Tom Stellardf8794352012-12-19 22:10:31 +0000236 }
237
Christian Konig01fd1f62013-03-01 09:46:11 +0000238 using Pass::doInitialization;
Craig Topper3e4c6972014-03-05 09:10:37 +0000239 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000240
Craig Topper3e4c6972014-03-05 09:10:37 +0000241 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000242
Craig Topper3e4c6972014-03-05 09:10:37 +0000243 const char *getPassName() const override {
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000244 return "Structurize control flow";
Tom Stellardf8794352012-12-19 22:10:31 +0000245 }
246
Craig Topper3e4c6972014-03-05 09:10:37 +0000247 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellardd3e916e2013-10-02 17:04:59 +0000248 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000249 AU.addRequired<DominatorTreeWrapperPass>();
250 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000251 RegionPass::getAnalysisUsage(AU);
252 }
Tom Stellardf8794352012-12-19 22:10:31 +0000253};
254
255} // end anonymous namespace
256
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000257char StructurizeCFG::ID = 0;
258
259INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
260 false, false)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000261INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000262INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000263INITIALIZE_PASS_DEPENDENCY(RegionInfo)
264INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
265 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000266
267/// \brief Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000268bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000269 LLVMContext &Context = R->getEntry()->getContext();
270
271 Boolean = Type::getInt1Ty(Context);
272 BoolTrue = ConstantInt::getTrue(Context);
273 BoolFalse = ConstantInt::getFalse(Context);
274 BoolUndef = UndefValue::get(Boolean);
275
276 return false;
277}
278
279/// \brief Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000280void StructurizeCFG::orderNodes() {
Duncan P. N. Exon Smith8e661ef2014-02-04 19:19:07 +0000281 scc_iterator<Region *> I = scc_begin(ParentRegion);
282 for (Order.clear(); !I.isAtEnd(); ++I) {
Tom Stellardf8794352012-12-19 22:10:31 +0000283 std::vector<RegionNode *> &Nodes = *I;
284 Order.append(Nodes.begin(), Nodes.end());
285 }
286}
287
Christian Konigfc6a9852013-02-16 11:27:45 +0000288/// \brief Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000289void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000290 if (N->isSubRegion()) {
291 // Test for exit as back edge
292 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
293 if (Visited.count(Exit))
294 Loops[Exit] = N->getEntry();
295
296 } else {
297 // Test for sucessors as back edge
298 BasicBlock *BB = N->getNodeAs<BasicBlock>();
299 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
300
301 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
302 BasicBlock *Succ = Term->getSuccessor(i);
303
304 if (Visited.count(Succ))
305 Loops[Succ] = BB;
306 }
307 }
308}
309
Christian Konigd8860992013-02-16 11:27:50 +0000310/// \brief Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000311Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000312 // First: Check if it's a constant
313 if (Condition == BoolTrue)
314 return BoolFalse;
315
316 if (Condition == BoolFalse)
317 return BoolTrue;
318
319 if (Condition == BoolUndef)
320 return BoolUndef;
321
322 // Second: If the condition is already inverted, return the original value
323 if (match(Condition, m_Not(m_Value(Condition))))
324 return Condition;
325
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000326 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
327 // Third: Check all the users for an invert
328 BasicBlock *Parent = Inst->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000329 for (User *U : Condition->users())
330 if (Instruction *I = dyn_cast<Instruction>(U))
331 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
332 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000333
334 // Last option: Create a new instruction
335 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000336 }
337
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000338 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
339 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
340 return BinaryOperator::CreateNot(Condition,
341 Arg->getName() + ".inv",
342 EntryBlock.getTerminator());
343 }
344
345 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000346}
347
Tom Stellard048f14f2013-02-08 22:24:37 +0000348/// \brief Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000349Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
350 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000351 Value *Cond = Invert ? BoolFalse : BoolTrue;
352 if (Term->isConditional()) {
353 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000354
Aaron Ballman19978552013-06-04 01:03:03 +0000355 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000356 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000357 }
358 return Cond;
359}
360
Tom Stellard048f14f2013-02-08 22:24:37 +0000361/// \brief Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000362void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000363 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000364 BasicBlock *BB = N->getEntry();
365 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000366 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000367
Tom Stellard048f14f2013-02-08 22:24:37 +0000368 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
369 PI != PE; ++PI) {
Tom Stellardf8794352012-12-19 22:10:31 +0000370
Christian Konigfc6a9852013-02-16 11:27:45 +0000371 // Ignore it if it's a branch from outside into our region entry
372 if (!ParentRegion->contains(*PI))
Tom Stellard048f14f2013-02-08 22:24:37 +0000373 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000374
Tom Stellard048f14f2013-02-08 22:24:37 +0000375 Region *R = RI->getRegionFor(*PI);
376 if (R == ParentRegion) {
Tom Stellardf8794352012-12-19 22:10:31 +0000377
Tom Stellard048f14f2013-02-08 22:24:37 +0000378 // It's a top level block in our region
379 BranchInst *Term = cast<BranchInst>((*PI)->getTerminator());
380 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
381 BasicBlock *Succ = Term->getSuccessor(i);
382 if (Succ != BB)
383 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000384
Tom Stellard048f14f2013-02-08 22:24:37 +0000385 if (Visited.count(*PI)) {
386 // Normal forward edge
387 if (Term->isConditional()) {
388 // Try to treat it like an ELSE block
389 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000390 if (Visited.count(Other) && !Loops.count(Other) &&
Tom Stellard048f14f2013-02-08 22:24:37 +0000391 !Pred.count(Other) && !Pred.count(*PI)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000392
Tom Stellard048f14f2013-02-08 22:24:37 +0000393 Pred[Other] = BoolFalse;
394 Pred[*PI] = BoolTrue;
395 continue;
396 }
397 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000398 Pred[*PI] = buildCondition(Term, i, false);
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000399
Tom Stellard048f14f2013-02-08 22:24:37 +0000400 } else {
401 // Back edge
Christian Konigfc6a9852013-02-16 11:27:45 +0000402 LPred[*PI] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000403 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000404 }
405
406 } else {
407
408 // It's an exit from a sub region
409 while(R->getParent() != ParentRegion)
410 R = R->getParent();
411
412 // Edge from inside a subregion to its entry, ignore it
413 if (R == N)
414 continue;
415
416 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000417 if (Visited.count(Entry))
418 Pred[Entry] = BoolTrue;
419 else
420 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000421 }
422 }
423}
424
425/// \brief Collect various loop and predicate infos
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000426void StructurizeCFG::collectInfos() {
Tom Stellardf8794352012-12-19 22:10:31 +0000427 // Reset predicate
428 Predicates.clear();
429
430 // and loop infos
Christian Konigfc6a9852013-02-16 11:27:45 +0000431 Loops.clear();
432 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000433
Tom Stellard048f14f2013-02-08 22:24:37 +0000434 // Reset the visited nodes
435 Visited.clear();
436
437 for (RNVector::reverse_iterator OI = Order.rbegin(), OE = Order.rend();
438 OI != OE; ++OI) {
Tom Stellardf8794352012-12-19 22:10:31 +0000439
440 // Analyze all the conditions leading to a node
Christian Konigfc6a9852013-02-16 11:27:45 +0000441 gatherPredicates(*OI);
Tom Stellardf8794352012-12-19 22:10:31 +0000442
Tom Stellard048f14f2013-02-08 22:24:37 +0000443 // Remember that we've seen this node
Tom Stellard7370ede2013-02-08 22:24:38 +0000444 Visited.insert((*OI)->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000445
Christian Konigfc6a9852013-02-16 11:27:45 +0000446 // Find the last back edges
447 analyzeLoops(*OI);
Tom Stellard048f14f2013-02-08 22:24:37 +0000448 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000449}
450
451/// \brief Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000452void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000453 BranchVector &Conds = Loops ? LoopConds : Conditions;
454 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000455 SSAUpdater PhiInserter;
456
Christian Konigfc6a9852013-02-16 11:27:45 +0000457 for (BranchVector::iterator I = Conds.begin(),
458 E = Conds.end(); I != E; ++I) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000459
460 BranchInst *Term = *I;
Tom Stellard048f14f2013-02-08 22:24:37 +0000461 assert(Term->isConditional());
462
Christian Konigfc6a9852013-02-16 11:27:45 +0000463 BasicBlock *Parent = Term->getParent();
464 BasicBlock *SuccTrue = Term->getSuccessor(0);
465 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000466
Christian Konigb5d88662013-02-16 11:27:40 +0000467 PhiInserter.Initialize(Boolean, "");
468 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000469 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000470
Christian Konigfc6a9852013-02-16 11:27:45 +0000471 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000472
473 NearestCommonDominator Dominator(DT);
474 Dominator.addBlock(Parent, false);
475
Craig Topperf40110f2014-04-25 05:29:35 +0000476 Value *ParentValue = nullptr;
Tom Stellard048f14f2013-02-08 22:24:37 +0000477 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
478 PI != PE; ++PI) {
479
Christian Konigb5d88662013-02-16 11:27:40 +0000480 if (PI->first == Parent) {
481 ParentValue = PI->second;
482 break;
483 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000484 PhiInserter.AddAvailableValue(PI->first, PI->second);
Christian Konigb5d88662013-02-16 11:27:40 +0000485 Dominator.addBlock(PI->first);
Tom Stellard048f14f2013-02-08 22:24:37 +0000486 }
487
Christian Konigb5d88662013-02-16 11:27:40 +0000488 if (ParentValue) {
489 Term->setCondition(ParentValue);
490 } else {
491 if (!Dominator.wasResultExplicitMentioned())
492 PhiInserter.AddAvailableValue(Dominator.getResult(), Default);
493
Tom Stellard048f14f2013-02-08 22:24:37 +0000494 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000495 }
Tom Stellardf8794352012-12-19 22:10:31 +0000496 }
497}
498
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000499/// \brief Remove all PHI values coming from "From" into "To" and remember
500/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000501void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000502 PhiMap &Map = DeletedPhis[To];
503 for (BasicBlock::iterator I = To->begin(), E = To->end();
504 I != E && isa<PHINode>(*I);) {
505
506 PHINode &Phi = cast<PHINode>(*I++);
507 while (Phi.getBasicBlockIndex(From) != -1) {
508 Value *Deleted = Phi.removeIncomingValue(From, false);
509 Map[&Phi].push_back(std::make_pair(From, Deleted));
510 }
511 }
512}
513
514/// \brief Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000515void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000516 for (BasicBlock::iterator I = To->begin(), E = To->end();
517 I != E && isa<PHINode>(*I);) {
518
519 PHINode &Phi = cast<PHINode>(*I++);
520 Value *Undef = UndefValue::get(Phi.getType());
521 Phi.addIncoming(Undef, From);
522 }
523 AddedPhis[To].push_back(From);
524}
525
526/// \brief Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000527void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000528 SSAUpdater Updater;
529 for (BB2BBVecMap::iterator AI = AddedPhis.begin(), AE = AddedPhis.end();
530 AI != AE; ++AI) {
531
532 BasicBlock *To = AI->first;
533 BBVector &From = AI->second;
534
535 if (!DeletedPhis.count(To))
536 continue;
537
538 PhiMap &Map = DeletedPhis[To];
539 for (PhiMap::iterator PI = Map.begin(), PE = Map.end();
540 PI != PE; ++PI) {
541
542 PHINode *Phi = PI->first;
543 Value *Undef = UndefValue::get(Phi->getType());
544 Updater.Initialize(Phi->getType(), "");
545 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
546 Updater.AddAvailableValue(To, Undef);
547
Christian Konig0bccf9d2013-02-16 11:27:35 +0000548 NearestCommonDominator Dominator(DT);
549 Dominator.addBlock(To, false);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000550 for (BBValueVector::iterator VI = PI->second.begin(),
551 VE = PI->second.end(); VI != VE; ++VI) {
552
553 Updater.AddAvailableValue(VI->first, VI->second);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000554 Dominator.addBlock(VI->first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000555 }
556
Christian Konig0bccf9d2013-02-16 11:27:35 +0000557 if (!Dominator.wasResultExplicitMentioned())
558 Updater.AddAvailableValue(Dominator.getResult(), Undef);
559
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000560 for (BBVector::iterator FI = From.begin(), FE = From.end();
561 FI != FE; ++FI) {
562
563 int Idx = Phi->getBasicBlockIndex(*FI);
564 assert(Idx != -1);
565 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(*FI));
566 }
567 }
568
569 DeletedPhis.erase(To);
570 }
571 assert(DeletedPhis.empty());
572}
573
Tom Stellard7370ede2013-02-08 22:24:38 +0000574/// \brief Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000575void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000576 TerminatorInst *Term = BB->getTerminator();
577 if (!Term)
578 return;
579
580 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
581 SI != SE; ++SI) {
582
583 delPhiValues(BB, *SI);
584 }
585
586 Term->eraseFromParent();
587}
588
Tom Stellard7370ede2013-02-08 22:24:38 +0000589/// \brief Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000590void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
591 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000592 if (Node->isSubRegion()) {
593 Region *SubRegion = Node->getNodeAs<Region>();
594 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000595 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000596
Tom Stellard7370ede2013-02-08 22:24:38 +0000597 // Find all the edges from the sub region to the exit
598 for (pred_iterator I = pred_begin(OldExit), E = pred_end(OldExit);
599 I != E;) {
600
601 BasicBlock *BB = *I++;
602 if (!SubRegion->contains(BB))
603 continue;
604
605 // Modify the edges to point to the new exit
606 delPhiValues(BB, OldExit);
607 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
608 addPhiValues(BB, NewExit);
609
610 // Find the new dominator (if requested)
611 if (IncludeDominator) {
612 if (!Dominator)
613 Dominator = BB;
614 else
615 Dominator = DT->findNearestCommonDominator(Dominator, BB);
616 }
Tom Stellardf8794352012-12-19 22:10:31 +0000617 }
618
Tom Stellard7370ede2013-02-08 22:24:38 +0000619 // Change the dominator (if requested)
620 if (Dominator)
621 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000622
Tom Stellard7370ede2013-02-08 22:24:38 +0000623 // Update the region info
624 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000625
Tom Stellardf8794352012-12-19 22:10:31 +0000626 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000627 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
628 killTerminator(BB);
629 BranchInst::Create(NewExit, BB);
630 addPhiValues(BB, NewExit);
631 if (IncludeDominator)
632 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000633 }
Tom Stellardf8794352012-12-19 22:10:31 +0000634}
635
Tom Stellardf8794352012-12-19 22:10:31 +0000636/// \brief Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000637BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000638 LLVMContext &Context = Func->getContext();
639 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
640 Order.back()->getEntry();
641 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
642 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000643 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000644 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000645 return Flow;
646}
647
Tom Stellard7370ede2013-02-08 22:24:38 +0000648/// \brief Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000649BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000650 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000651
Christian Konigfc6a9852013-02-16 11:27:45 +0000652 if (!PrevNode->isSubRegion()) {
653 killTerminator(Entry);
654 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
655 return Entry;
Tom Stellard7370ede2013-02-08 22:24:38 +0000656
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000657 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000658
Christian Konigfc6a9852013-02-16 11:27:45 +0000659 // create a new flow node
660 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000661
Christian Konigfc6a9852013-02-16 11:27:45 +0000662 // and wire it up
663 changeExit(PrevNode, Flow, true);
664 PrevNode = ParentRegion->getBBNode(Flow);
665 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000666}
667
668/// \brief Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000669BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
670 bool ExitUseAllowed) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000671 if (Order.empty() && ExitUseAllowed) {
672 BasicBlock *Exit = ParentRegion->getExit();
673 DT->changeImmediateDominator(Exit, Flow);
674 addPhiValues(Flow, Exit);
675 return Exit;
676 }
677 return getNextFlow(Flow);
678}
679
Christian Konigfc6a9852013-02-16 11:27:45 +0000680/// \brief Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000681void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000682 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
683 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000684}
685
686/// \brief Does BB dominate all the predicates of Node ?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000687bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000688 BBPredicates &Preds = Predicates[Node->getEntry()];
689 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
690 PI != PE; ++PI) {
691
692 if (!DT->dominates(BB, PI->first))
693 return false;
694 }
695 return true;
696}
697
Tom Stellardf8794352012-12-19 22:10:31 +0000698/// \brief Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000699bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000700 BBPredicates &Preds = Predicates[Node->getEntry()];
701 bool Dominated = false;
702
703 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000704 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000705 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000706
707 for (BBPredicates::iterator I = Preds.begin(), E = Preds.end();
708 I != E; ++I) {
709
710 if (I->second != BoolTrue)
711 return false;
712
Christian Konigfc6a9852013-02-16 11:27:45 +0000713 if (!Dominated && DT->dominates(I->first, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000714 Dominated = true;
715 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000716
717 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000718 return Dominated;
719}
720
Tom Stellard7370ede2013-02-08 22:24:38 +0000721/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000722void StructurizeCFG::wireFlow(bool ExitUseAllowed,
723 BasicBlock *LoopEnd) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000724 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000725 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000726
Christian Konigfc6a9852013-02-16 11:27:45 +0000727 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000728 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000729 if (PrevNode) {
730 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000731 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000732 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000733
734 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000735 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000736 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000737
Tom Stellard7370ede2013-02-08 22:24:38 +0000738 // Insert extra postfix node (or use exit instead)
739 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000740 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000741
742 // let it point to entry and next block
743 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
744 addPhiValues(Flow, Entry);
745 DT->changeImmediateDominator(Entry, Flow);
746
Christian Konigfc6a9852013-02-16 11:27:45 +0000747 PrevNode = Node;
748 while (!Order.empty() && !Visited.count(LoopEnd) &&
Tom Stellard7370ede2013-02-08 22:24:38 +0000749 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000750 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000751 }
752
Christian Konigfc6a9852013-02-16 11:27:45 +0000753 changeExit(PrevNode, Next, false);
754 setPrevNode(Next);
755 }
756}
757
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000758void StructurizeCFG::handleLoops(bool ExitUseAllowed,
759 BasicBlock *LoopEnd) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000760 RegionNode *Node = Order.back();
761 BasicBlock *LoopStart = Node->getEntry();
762
763 if (!Loops.count(LoopStart)) {
764 wireFlow(ExitUseAllowed, LoopEnd);
765 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000766 }
767
Christian Konigfc6a9852013-02-16 11:27:45 +0000768 if (!isPredictableTrue(Node))
769 LoopStart = needPrefix(true);
770
771 LoopEnd = Loops[Node->getEntry()];
772 wireFlow(false, LoopEnd);
773 while (!Visited.count(LoopEnd)) {
774 handleLoops(false, LoopEnd);
775 }
776
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000777 // If the start of the loop is the entry block, we can't branch to it so
778 // insert a new dummy entry block.
779 Function *LoopFunc = LoopStart->getParent();
780 if (LoopStart == &LoopFunc->getEntryBlock()) {
781 LoopStart->setName("entry.orig");
782
783 BasicBlock *NewEntry =
784 BasicBlock::Create(LoopStart->getContext(),
785 "entry",
786 LoopFunc,
787 LoopStart);
788 BranchInst::Create(LoopStart, NewEntry);
789 }
790
Christian Konigfc6a9852013-02-16 11:27:45 +0000791 // Create an extra loop end node
792 LoopEnd = needPrefix(false);
793 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
794 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
795 BoolUndef, LoopEnd));
796 addPhiValues(LoopEnd, LoopStart);
797 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000798}
799
Tom Stellardf8794352012-12-19 22:10:31 +0000800/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000801/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000802void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000803 BasicBlock *Exit = ParentRegion->getExit();
804 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
805
Tom Stellardf8794352012-12-19 22:10:31 +0000806 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000807 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000808 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000809 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000810
Craig Topperf40110f2014-04-25 05:29:35 +0000811 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000812 Visited.clear();
813
Tom Stellardf8794352012-12-19 22:10:31 +0000814 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000815 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000816 }
817
Christian Konigfc6a9852013-02-16 11:27:45 +0000818 if (PrevNode)
819 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000820 else
821 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000822}
823
Tom Stellardf8794352012-12-19 22:10:31 +0000824/// Handle a rare case where the disintegrated nodes instructions
825/// no longer dominate all their uses. Not sure if this is really nessasary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000826void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000827 SSAUpdater Updater;
Tobias Grosser4abf9d32014-03-03 13:00:39 +0000828 for (const auto &BB : ParentRegion->blocks())
Tom Stellardf8794352012-12-19 22:10:31 +0000829 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
830 II != IE; ++II) {
831
832 bool Initialized = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000833 for (auto I = II->use_begin(), E = II->use_end(); I != E;) {
834 Use &U = *I++;
835 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000836 if (User->getParent() == BB) {
837 continue;
838
839 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000840 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000841 continue;
842 }
843
844 if (DT->dominates(II, User))
845 continue;
846
847 if (!Initialized) {
848 Value *Undef = UndefValue::get(II->getType());
849 Updater.Initialize(II->getType(), "");
850 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
851 Updater.AddAvailableValue(BB, II);
852 Initialized = true;
853 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000854 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000855 }
856 }
Tom Stellardf8794352012-12-19 22:10:31 +0000857}
858
859/// \brief Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000860bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000861 if (R->isTopLevelRegion())
862 return false;
863
864 Func = R->getEntry()->getParent();
865 ParentRegion = R;
866
Chandler Carruth73523022014-01-13 13:07:17 +0000867 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tom Stellardf8794352012-12-19 22:10:31 +0000868
869 orderNodes();
870 collectInfos();
871 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000872 insertConditions(false);
873 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000874 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +0000875 rebuildSSA();
876
Tom Stellard048f14f2013-02-08 22:24:37 +0000877 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +0000878 Order.clear();
879 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000880 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000881 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000882 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000883 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000884 Loops.clear();
885 LoopPreds.clear();
886 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000887
888 return true;
889}
890
891/// \brief Create the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000892Pass *llvm::createStructurizeCFGPass() {
893 return new StructurizeCFG();
Tom Stellardf8794352012-12-19 22:10:31 +0000894}