blob: d45683294c7e6c22da94b8601e4fa8a403b89759 [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
Christian Konigd08e3d72013-02-16 11:27:29 +000046typedef DenseMap<DomTreeNode *, unsigned> DTN2UnsignedMap;
Tom Stellardf8794352012-12-19 22:10:31 +000047typedef DenseMap<BasicBlock *, PhiMap> BBPhiMap;
48typedef DenseMap<BasicBlock *, Value *> BBPredicates;
49typedef DenseMap<BasicBlock *, BBPredicates> PredMap;
Christian Konigfc6a9852013-02-16 11:27:45 +000050typedef DenseMap<BasicBlock *, BasicBlock*> BB2BBMap;
Tom Stellardf8794352012-12-19 22:10:31 +000051
52// The name for newly created blocks.
53
Craig Topperd3a34f82013-07-16 01:17:10 +000054static const char *const FlowBlockName = "Flow";
Tom Stellardf8794352012-12-19 22:10:31 +000055
Christian Konigd08e3d72013-02-16 11:27:29 +000056/// @brief Find the nearest common dominator for multiple BasicBlocks
57///
Matt Arsenaultd46fce12013-06-19 20:18:24 +000058/// Helper class for StructurizeCFG
Christian Konigd08e3d72013-02-16 11:27:29 +000059/// TODO: Maybe move into common code
60class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000061 DominatorTree *DT;
62
63 DTN2UnsignedMap IndexMap;
64
65 BasicBlock *Result;
66 unsigned ResultIndex;
67 bool ExplicitMentioned;
68
69public:
70 /// \brief Start a new query
71 NearestCommonDominator(DominatorTree *DomTree) {
72 DT = DomTree;
Craig Topperf40110f2014-04-25 05:29:35 +000073 Result = nullptr;
Christian Konigd08e3d72013-02-16 11:27:29 +000074 }
75
76 /// \brief Add BB to the resulting dominator
77 void addBlock(BasicBlock *BB, bool Remember = true) {
Christian Konigd08e3d72013-02-16 11:27:29 +000078 DomTreeNode *Node = DT->getNode(BB);
79
Craig Topperf40110f2014-04-25 05:29:35 +000080 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000081 unsigned Numbering = 0;
82 for (;Node;Node = Node->getIDom())
83 IndexMap[Node] = ++Numbering;
84 Result = BB;
85 ResultIndex = 1;
86 ExplicitMentioned = Remember;
87 return;
88 }
89
90 for (;Node;Node = Node->getIDom())
91 if (IndexMap.count(Node))
92 break;
93 else
94 IndexMap[Node] = 0;
95
96 assert(Node && "Dominator tree invalid!");
97
98 unsigned Numbering = IndexMap[Node];
99 if (Numbering > ResultIndex) {
100 Result = Node->getBlock();
101 ResultIndex = Numbering;
102 ExplicitMentioned = Remember && (Result == BB);
103 } else if (Numbering == ResultIndex) {
104 ExplicitMentioned |= Remember;
105 }
106 }
107
108 /// \brief Is "Result" one of the BBs added with "Remember" = True?
109 bool wasResultExplicitMentioned() {
110 return ExplicitMentioned;
111 }
112
113 /// \brief Get the query result
114 BasicBlock *getResult() {
115 return Result;
116 }
117};
118
Tom Stellardf8794352012-12-19 22:10:31 +0000119/// @brief Transforms the control flow graph on one single entry/exit region
120/// at a time.
121///
122/// After the transform all "If"/"Then"/"Else" style control flow looks like
123/// this:
124///
125/// \verbatim
126/// 1
127/// ||
128/// | |
129/// 2 |
130/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000131/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000132/// 3
133/// || Where:
134/// | | 1 = "If" block, calculates the condition
135/// 4 | 2 = "Then" subregion, runs if the condition is true
136/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
137/// |/ 4 = "Else" optional subregion, runs if the condition is false
138/// 5 5 = "End" block, also rejoins the control flow
139/// \endverbatim
140///
141/// Control flow is expressed as a branch where the true exit goes into the
142/// "Then"/"Else" region, while the false exit skips the region
143/// The condition for the optional "Else" region is expressed as a PHI node.
144/// The incomming values of the PHI node are true for the "If" edge and false
145/// for the "Then" edge.
146///
147/// Additionally to that even complicated loops look like this:
148///
149/// \verbatim
150/// 1
151/// ||
152/// | |
153/// 2 ^ Where:
154/// | / 1 = "Entry" block
155/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
156/// 3 3 = "Flow" block, with back edge to entry block
157/// |
158/// \endverbatim
159///
160/// The back edge of the "Flow" block is always on the false side of the branch
161/// while the true side continues the general flow. So the loop condition
162/// consist of a network of PHI nodes where the true incoming values expresses
163/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000164class StructurizeCFG : public RegionPass {
Tom Stellard755a4e62016-02-10 00:39:37 +0000165 bool SkipUniformRegions;
166 DivergenceAnalysis *DA;
167
Tom Stellardf8794352012-12-19 22:10:31 +0000168 Type *Boolean;
169 ConstantInt *BoolTrue;
170 ConstantInt *BoolFalse;
171 UndefValue *BoolUndef;
172
173 Function *Func;
174 Region *ParentRegion;
175
176 DominatorTree *DT;
Tom Stellard1f0dded2014-12-03 04:28:32 +0000177 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000178
179 RNVector Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000180 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000181
Tom Stellardf8794352012-12-19 22:10:31 +0000182 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000183 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000184
185 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000186 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000187
Christian Konigfc6a9852013-02-16 11:27:45 +0000188 BB2BBMap Loops;
189 PredMap LoopPreds;
190 BranchVector LoopConds;
191
192 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000193
194 void orderNodes();
195
Christian Konigfc6a9852013-02-16 11:27:45 +0000196 void analyzeLoops(RegionNode *N);
197
Christian Konigd8860992013-02-16 11:27:50 +0000198 Value *invert(Value *Condition);
199
Tom Stellard048f14f2013-02-08 22:24:37 +0000200 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000201
Christian Konigfc6a9852013-02-16 11:27:45 +0000202 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000203
204 void collectInfos();
205
Christian Konigfc6a9852013-02-16 11:27:45 +0000206 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000207
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000208 void delPhiValues(BasicBlock *From, BasicBlock *To);
209
210 void addPhiValues(BasicBlock *From, BasicBlock *To);
211
212 void setPhiValues();
213
Tom Stellardf8794352012-12-19 22:10:31 +0000214 void killTerminator(BasicBlock *BB);
215
Tom Stellard7370ede2013-02-08 22:24:38 +0000216 void changeExit(RegionNode *Node, BasicBlock *NewExit,
217 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000218
Tom Stellard7370ede2013-02-08 22:24:38 +0000219 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000220
Christian Konigfc6a9852013-02-16 11:27:45 +0000221 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000222
Tom Stellard7370ede2013-02-08 22:24:38 +0000223 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
224
Christian Konigfc6a9852013-02-16 11:27:45 +0000225 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000226
227 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
228
Christian Konigfc6a9852013-02-16 11:27:45 +0000229 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000230
Christian Konigfc6a9852013-02-16 11:27:45 +0000231 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
232
233 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000234
235 void createFlow();
236
Tom Stellardf8794352012-12-19 22:10:31 +0000237 void rebuildSSA();
238
Tom Stellard755a4e62016-02-10 00:39:37 +0000239 bool hasOnlyUniformBranches(const Region *R);
240
Tom Stellardf8794352012-12-19 22:10:31 +0000241public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000242 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000243
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000244 StructurizeCFG() :
Tom Stellard6fa4e292016-02-10 01:10:09 +0000245 RegionPass(ID), SkipUniformRegions(false) {
Tom Stellardd3e916e2013-10-02 17:04:59 +0000246 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
Tom Stellardf8794352012-12-19 22:10:31 +0000247 }
248
Tom Stellard755a4e62016-02-10 00:39:37 +0000249 StructurizeCFG(bool SkipUniformRegions) :
250 RegionPass(ID), SkipUniformRegions(SkipUniformRegions) {
251 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
252 }
253
Christian Konig01fd1f62013-03-01 09:46:11 +0000254 using Pass::doInitialization;
Craig Topper3e4c6972014-03-05 09:10:37 +0000255 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000256
Craig Topper3e4c6972014-03-05 09:10:37 +0000257 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000258
Craig Topper3e4c6972014-03-05 09:10:37 +0000259 const char *getPassName() const override {
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000260 return "Structurize control flow";
Tom Stellardf8794352012-12-19 22:10:31 +0000261 }
262
Craig Topper3e4c6972014-03-05 09:10:37 +0000263 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard755a4e62016-02-10 00:39:37 +0000264 if (SkipUniformRegions)
265 AU.addRequired<DivergenceAnalysis>();
Tom Stellardd3e916e2013-10-02 17:04:59 +0000266 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000267 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000268 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000269 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000270 RegionPass::getAnalysisUsage(AU);
271 }
Tom Stellardf8794352012-12-19 22:10:31 +0000272};
273
274} // end anonymous namespace
275
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000276char StructurizeCFG::ID = 0;
277
278INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
279 false, false)
Tom Stellard755a4e62016-02-10 00:39:37 +0000280INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000281INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000282INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000283INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000284INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
285 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000286
287/// \brief Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000288bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000289 LLVMContext &Context = R->getEntry()->getContext();
290
291 Boolean = Type::getInt1Ty(Context);
292 BoolTrue = ConstantInt::getTrue(Context);
293 BoolFalse = ConstantInt::getFalse(Context);
294 BoolUndef = UndefValue::get(Boolean);
295
296 return false;
297}
298
299/// \brief Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000300void StructurizeCFG::orderNodes() {
Tom Stellard071ec902015-02-04 20:49:44 +0000301 RNVector TempOrder;
302 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
303 TempOrder.append(RPOT.begin(), RPOT.end());
304
305 std::map<Loop*, unsigned> LoopBlocks;
306
307
308 // The reverse post-order traversal of the list gives us an ordering close
309 // to what we want. The only problem with it is that sometimes backedges
310 // for outer loops will be visited before backedges for inner loops.
311 for (RegionNode *RN : TempOrder) {
312 BasicBlock *BB = RN->getEntry();
313 Loop *Loop = LI->getLoopFor(BB);
314 if (!LoopBlocks.count(Loop)) {
315 LoopBlocks[Loop] = 1;
316 continue;
317 }
318 LoopBlocks[Loop]++;
Tom Stellardf8794352012-12-19 22:10:31 +0000319 }
Tom Stellard071ec902015-02-04 20:49:44 +0000320
321 unsigned CurrentLoopDepth = 0;
322 Loop *CurrentLoop = nullptr;
323 BBSet TempVisited;
324 for (RNVector::iterator I = TempOrder.begin(), E = TempOrder.end(); I != E; ++I) {
325 BasicBlock *BB = (*I)->getEntry();
326 unsigned LoopDepth = LI->getLoopDepth(BB);
327
328 if (std::find(Order.begin(), Order.end(), *I) != Order.end())
329 continue;
330
331 if (LoopDepth < CurrentLoopDepth) {
332 // Make sure we have visited all blocks in this loop before moving back to
333 // the outer loop.
334
335 RNVector::iterator LoopI = I;
336 while(LoopBlocks[CurrentLoop]) {
337 LoopI++;
338 BasicBlock *LoopBB = (*LoopI)->getEntry();
339 if (LI->getLoopFor(LoopBB) == CurrentLoop) {
340 LoopBlocks[CurrentLoop]--;
341 Order.push_back(*LoopI);
342 }
343 }
344 }
345
346 CurrentLoop = LI->getLoopFor(BB);
347 if (CurrentLoop) {
348 LoopBlocks[CurrentLoop]--;
349 }
350
351 CurrentLoopDepth = LoopDepth;
352 Order.push_back(*I);
353 }
354
355 // This pass originally used a post-order traversal and then operated on
356 // the list in reverse. Now that we are using a reverse post-order traversal
357 // rather than re-working the whole pass to operate on the list in order,
358 // we just reverse the list and continue to operate on it in reverse.
359 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000360}
361
Christian Konigfc6a9852013-02-16 11:27:45 +0000362/// \brief Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000363void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000364 if (N->isSubRegion()) {
365 // Test for exit as back edge
366 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
367 if (Visited.count(Exit))
368 Loops[Exit] = N->getEntry();
369
370 } else {
371 // Test for sucessors as back edge
372 BasicBlock *BB = N->getNodeAs<BasicBlock>();
373 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
374
Pete Cooperebcd7482015-08-06 20:22:46 +0000375 for (BasicBlock *Succ : Term->successors())
376 if (Visited.count(Succ))
Christian Konigfc6a9852013-02-16 11:27:45 +0000377 Loops[Succ] = BB;
Christian Konigfc6a9852013-02-16 11:27:45 +0000378 }
379}
380
Christian Konigd8860992013-02-16 11:27:50 +0000381/// \brief Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000382Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000383 // First: Check if it's a constant
384 if (Condition == BoolTrue)
385 return BoolFalse;
386
387 if (Condition == BoolFalse)
388 return BoolTrue;
389
390 if (Condition == BoolUndef)
391 return BoolUndef;
392
393 // Second: If the condition is already inverted, return the original value
394 if (match(Condition, m_Not(m_Value(Condition))))
395 return Condition;
396
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000397 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
398 // Third: Check all the users for an invert
399 BasicBlock *Parent = Inst->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000400 for (User *U : Condition->users())
401 if (Instruction *I = dyn_cast<Instruction>(U))
402 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
403 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000404
405 // Last option: Create a new instruction
406 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000407 }
408
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000409 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
410 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
411 return BinaryOperator::CreateNot(Condition,
412 Arg->getName() + ".inv",
413 EntryBlock.getTerminator());
414 }
415
416 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000417}
418
Tom Stellard048f14f2013-02-08 22:24:37 +0000419/// \brief Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000420Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
421 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000422 Value *Cond = Invert ? BoolFalse : BoolTrue;
423 if (Term->isConditional()) {
424 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000425
Aaron Ballman19978552013-06-04 01:03:03 +0000426 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000427 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000428 }
429 return Cond;
430}
431
Tom Stellard048f14f2013-02-08 22:24:37 +0000432/// \brief Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000433void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000434 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000435 BasicBlock *BB = N->getEntry();
436 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000437 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000438
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000439 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
440 PI != PE; ++PI) {
441
Christian Konigfc6a9852013-02-16 11:27:45 +0000442 // Ignore it if it's a branch from outside into our region entry
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000443 if (!ParentRegion->contains(*PI))
Tom Stellard048f14f2013-02-08 22:24:37 +0000444 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000445
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000446 Region *R = RI->getRegionFor(*PI);
Tom Stellard048f14f2013-02-08 22:24:37 +0000447 if (R == ParentRegion) {
Tom Stellardf8794352012-12-19 22:10:31 +0000448
Tom Stellard048f14f2013-02-08 22:24:37 +0000449 // It's a top level block in our region
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000450 BranchInst *Term = cast<BranchInst>((*PI)->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000451 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
452 BasicBlock *Succ = Term->getSuccessor(i);
453 if (Succ != BB)
454 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000455
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000456 if (Visited.count(*PI)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000457 // Normal forward edge
458 if (Term->isConditional()) {
459 // Try to treat it like an ELSE block
460 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000461 if (Visited.count(Other) && !Loops.count(Other) &&
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000462 !Pred.count(Other) && !Pred.count(*PI)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000463
Tom Stellard048f14f2013-02-08 22:24:37 +0000464 Pred[Other] = BoolFalse;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000465 Pred[*PI] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000466 continue;
467 }
468 }
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000469 Pred[*PI] = buildCondition(Term, i, false);
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000470
Tom Stellard048f14f2013-02-08 22:24:37 +0000471 } else {
472 // Back edge
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000473 LPred[*PI] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000474 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000475 }
476
477 } else {
478
479 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000480 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000481 R = R->getParent();
482
483 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000484 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000485 continue;
486
487 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000488 if (Visited.count(Entry))
489 Pred[Entry] = BoolTrue;
490 else
491 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000492 }
493 }
494}
495
496/// \brief Collect various loop and predicate infos
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000497void StructurizeCFG::collectInfos() {
Tom Stellardf8794352012-12-19 22:10:31 +0000498 // Reset predicate
499 Predicates.clear();
500
501 // and loop infos
Christian Konigfc6a9852013-02-16 11:27:45 +0000502 Loops.clear();
503 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000504
Tom Stellard048f14f2013-02-08 22:24:37 +0000505 // Reset the visited nodes
506 Visited.clear();
507
508 for (RNVector::reverse_iterator OI = Order.rbegin(), OE = Order.rend();
509 OI != OE; ++OI) {
Tom Stellardf8794352012-12-19 22:10:31 +0000510
Tom Stellard071ec902015-02-04 20:49:44 +0000511 DEBUG(dbgs() << "Visiting: " <<
512 ((*OI)->isSubRegion() ? "SubRegion with entry: " : "") <<
513 (*OI)->getEntry()->getName() << " Loop Depth: " << LI->getLoopDepth((*OI)->getEntry()) << "\n");
514
Tom Stellardf8794352012-12-19 22:10:31 +0000515 // Analyze all the conditions leading to a node
Christian Konigfc6a9852013-02-16 11:27:45 +0000516 gatherPredicates(*OI);
Tom Stellardf8794352012-12-19 22:10:31 +0000517
Tom Stellard048f14f2013-02-08 22:24:37 +0000518 // Remember that we've seen this node
Tom Stellard7370ede2013-02-08 22:24:38 +0000519 Visited.insert((*OI)->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000520
Christian Konigfc6a9852013-02-16 11:27:45 +0000521 // Find the last back edges
522 analyzeLoops(*OI);
Tom Stellard048f14f2013-02-08 22:24:37 +0000523 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000524}
525
526/// \brief Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000527void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000528 BranchVector &Conds = Loops ? LoopConds : Conditions;
529 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000530 SSAUpdater PhiInserter;
531
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000532 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000533 assert(Term->isConditional());
534
Christian Konigfc6a9852013-02-16 11:27:45 +0000535 BasicBlock *Parent = Term->getParent();
536 BasicBlock *SuccTrue = Term->getSuccessor(0);
537 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000538
Christian Konigb5d88662013-02-16 11:27:40 +0000539 PhiInserter.Initialize(Boolean, "");
540 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000541 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000542
Christian Konigfc6a9852013-02-16 11:27:45 +0000543 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000544
545 NearestCommonDominator Dominator(DT);
546 Dominator.addBlock(Parent, false);
547
Craig Topperf40110f2014-04-25 05:29:35 +0000548 Value *ParentValue = nullptr;
Tom Stellard048f14f2013-02-08 22:24:37 +0000549 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
550 PI != PE; ++PI) {
551
Christian Konigb5d88662013-02-16 11:27:40 +0000552 if (PI->first == Parent) {
553 ParentValue = PI->second;
554 break;
555 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000556 PhiInserter.AddAvailableValue(PI->first, PI->second);
Christian Konigb5d88662013-02-16 11:27:40 +0000557 Dominator.addBlock(PI->first);
Tom Stellard048f14f2013-02-08 22:24:37 +0000558 }
559
Christian Konigb5d88662013-02-16 11:27:40 +0000560 if (ParentValue) {
561 Term->setCondition(ParentValue);
562 } else {
563 if (!Dominator.wasResultExplicitMentioned())
564 PhiInserter.AddAvailableValue(Dominator.getResult(), Default);
565
Tom Stellard048f14f2013-02-08 22:24:37 +0000566 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000567 }
Tom Stellardf8794352012-12-19 22:10:31 +0000568 }
569}
570
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000571/// \brief Remove all PHI values coming from "From" into "To" and remember
572/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000573void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000574 PhiMap &Map = DeletedPhis[To];
575 for (BasicBlock::iterator I = To->begin(), E = To->end();
576 I != E && isa<PHINode>(*I);) {
577
578 PHINode &Phi = cast<PHINode>(*I++);
579 while (Phi.getBasicBlockIndex(From) != -1) {
580 Value *Deleted = Phi.removeIncomingValue(From, false);
581 Map[&Phi].push_back(std::make_pair(From, Deleted));
582 }
583 }
584}
585
586/// \brief Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000587void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000588 for (BasicBlock::iterator I = To->begin(), E = To->end();
589 I != E && isa<PHINode>(*I);) {
590
591 PHINode &Phi = cast<PHINode>(*I++);
592 Value *Undef = UndefValue::get(Phi.getType());
593 Phi.addIncoming(Undef, From);
594 }
595 AddedPhis[To].push_back(From);
596}
597
598/// \brief Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000599void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000600 SSAUpdater Updater;
601 for (BB2BBVecMap::iterator AI = AddedPhis.begin(), AE = AddedPhis.end();
602 AI != AE; ++AI) {
603
604 BasicBlock *To = AI->first;
605 BBVector &From = AI->second;
606
607 if (!DeletedPhis.count(To))
608 continue;
609
610 PhiMap &Map = DeletedPhis[To];
611 for (PhiMap::iterator PI = Map.begin(), PE = Map.end();
612 PI != PE; ++PI) {
613
614 PHINode *Phi = PI->first;
615 Value *Undef = UndefValue::get(Phi->getType());
616 Updater.Initialize(Phi->getType(), "");
617 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
618 Updater.AddAvailableValue(To, Undef);
619
Christian Konig0bccf9d2013-02-16 11:27:35 +0000620 NearestCommonDominator Dominator(DT);
621 Dominator.addBlock(To, false);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000622 for (BBValueVector::iterator VI = PI->second.begin(),
623 VE = PI->second.end(); VI != VE; ++VI) {
624
625 Updater.AddAvailableValue(VI->first, VI->second);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000626 Dominator.addBlock(VI->first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000627 }
628
Christian Konig0bccf9d2013-02-16 11:27:35 +0000629 if (!Dominator.wasResultExplicitMentioned())
630 Updater.AddAvailableValue(Dominator.getResult(), Undef);
631
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000632 for (BBVector::iterator FI = From.begin(), FE = From.end();
633 FI != FE; ++FI) {
634
635 int Idx = Phi->getBasicBlockIndex(*FI);
636 assert(Idx != -1);
637 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(*FI));
638 }
639 }
640
641 DeletedPhis.erase(To);
642 }
643 assert(DeletedPhis.empty());
644}
645
Tom Stellard7370ede2013-02-08 22:24:38 +0000646/// \brief Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000647void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000648 TerminatorInst *Term = BB->getTerminator();
649 if (!Term)
650 return;
651
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000652 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
653 SI != SE; ++SI) {
654
655 delPhiValues(BB, *SI);
656 }
Tom Stellardf8794352012-12-19 22:10:31 +0000657
658 Term->eraseFromParent();
659}
660
Tom Stellard7370ede2013-02-08 22:24:38 +0000661/// \brief Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000662void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
663 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000664 if (Node->isSubRegion()) {
665 Region *SubRegion = Node->getNodeAs<Region>();
666 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000667 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000668
Tom Stellard7370ede2013-02-08 22:24:38 +0000669 // Find all the edges from the sub region to the exit
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000670 for (pred_iterator I = pred_begin(OldExit), E = pred_end(OldExit);
671 I != E;) {
672
673 BasicBlock *BB = *I++;
Tom Stellard7370ede2013-02-08 22:24:38 +0000674 if (!SubRegion->contains(BB))
675 continue;
676
677 // Modify the edges to point to the new exit
678 delPhiValues(BB, OldExit);
679 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
680 addPhiValues(BB, NewExit);
681
682 // Find the new dominator (if requested)
683 if (IncludeDominator) {
684 if (!Dominator)
685 Dominator = BB;
686 else
687 Dominator = DT->findNearestCommonDominator(Dominator, BB);
688 }
Tom Stellardf8794352012-12-19 22:10:31 +0000689 }
690
Tom Stellard7370ede2013-02-08 22:24:38 +0000691 // Change the dominator (if requested)
692 if (Dominator)
693 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000694
Tom Stellard7370ede2013-02-08 22:24:38 +0000695 // Update the region info
696 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000697
Tom Stellardf8794352012-12-19 22:10:31 +0000698 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000699 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
700 killTerminator(BB);
701 BranchInst::Create(NewExit, BB);
702 addPhiValues(BB, NewExit);
703 if (IncludeDominator)
704 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000705 }
Tom Stellardf8794352012-12-19 22:10:31 +0000706}
707
Tom Stellardf8794352012-12-19 22:10:31 +0000708/// \brief Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000709BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000710 LLVMContext &Context = Func->getContext();
711 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
712 Order.back()->getEntry();
713 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
714 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000715 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000716 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000717 return Flow;
718}
719
Tom Stellard7370ede2013-02-08 22:24:38 +0000720/// \brief Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000721BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000722 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000723
Christian Konigfc6a9852013-02-16 11:27:45 +0000724 if (!PrevNode->isSubRegion()) {
725 killTerminator(Entry);
726 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
727 return Entry;
Tom Stellard7370ede2013-02-08 22:24:38 +0000728
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000729 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000730
Christian Konigfc6a9852013-02-16 11:27:45 +0000731 // create a new flow node
732 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000733
Christian Konigfc6a9852013-02-16 11:27:45 +0000734 // and wire it up
735 changeExit(PrevNode, Flow, true);
736 PrevNode = ParentRegion->getBBNode(Flow);
737 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000738}
739
740/// \brief Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000741BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
742 bool ExitUseAllowed) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000743 if (Order.empty() && ExitUseAllowed) {
744 BasicBlock *Exit = ParentRegion->getExit();
745 DT->changeImmediateDominator(Exit, Flow);
746 addPhiValues(Flow, Exit);
747 return Exit;
748 }
749 return getNextFlow(Flow);
750}
751
Christian Konigfc6a9852013-02-16 11:27:45 +0000752/// \brief Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000753void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000754 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
755 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000756}
757
758/// \brief Does BB dominate all the predicates of Node ?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000759bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000760 BBPredicates &Preds = Predicates[Node->getEntry()];
761 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
762 PI != PE; ++PI) {
763
764 if (!DT->dominates(BB, PI->first))
765 return false;
766 }
767 return true;
768}
769
Tom Stellardf8794352012-12-19 22:10:31 +0000770/// \brief Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000771bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000772 BBPredicates &Preds = Predicates[Node->getEntry()];
773 bool Dominated = false;
774
775 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000776 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000777 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000778
779 for (BBPredicates::iterator I = Preds.begin(), E = Preds.end();
780 I != E; ++I) {
781
782 if (I->second != BoolTrue)
783 return false;
784
Christian Konigfc6a9852013-02-16 11:27:45 +0000785 if (!Dominated && DT->dominates(I->first, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000786 Dominated = true;
787 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000788
789 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000790 return Dominated;
791}
792
Tom Stellard7370ede2013-02-08 22:24:38 +0000793/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000794void StructurizeCFG::wireFlow(bool ExitUseAllowed,
795 BasicBlock *LoopEnd) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000796 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000797 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000798
Christian Konigfc6a9852013-02-16 11:27:45 +0000799 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000800 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000801 if (PrevNode) {
802 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000803 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000804 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000805
806 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000807 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000808 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000809
Tom Stellard7370ede2013-02-08 22:24:38 +0000810 // Insert extra postfix node (or use exit instead)
811 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000812 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000813
814 // let it point to entry and next block
815 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
816 addPhiValues(Flow, Entry);
817 DT->changeImmediateDominator(Entry, Flow);
818
Christian Konigfc6a9852013-02-16 11:27:45 +0000819 PrevNode = Node;
820 while (!Order.empty() && !Visited.count(LoopEnd) &&
Tom Stellard7370ede2013-02-08 22:24:38 +0000821 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000822 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000823 }
824
Christian Konigfc6a9852013-02-16 11:27:45 +0000825 changeExit(PrevNode, Next, false);
826 setPrevNode(Next);
827 }
828}
829
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000830void StructurizeCFG::handleLoops(bool ExitUseAllowed,
831 BasicBlock *LoopEnd) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000832 RegionNode *Node = Order.back();
833 BasicBlock *LoopStart = Node->getEntry();
834
835 if (!Loops.count(LoopStart)) {
836 wireFlow(ExitUseAllowed, LoopEnd);
837 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000838 }
839
Christian Konigfc6a9852013-02-16 11:27:45 +0000840 if (!isPredictableTrue(Node))
841 LoopStart = needPrefix(true);
842
843 LoopEnd = Loops[Node->getEntry()];
844 wireFlow(false, LoopEnd);
845 while (!Visited.count(LoopEnd)) {
846 handleLoops(false, LoopEnd);
847 }
848
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000849 // If the start of the loop is the entry block, we can't branch to it so
850 // insert a new dummy entry block.
851 Function *LoopFunc = LoopStart->getParent();
852 if (LoopStart == &LoopFunc->getEntryBlock()) {
853 LoopStart->setName("entry.orig");
854
855 BasicBlock *NewEntry =
856 BasicBlock::Create(LoopStart->getContext(),
857 "entry",
858 LoopFunc,
859 LoopStart);
860 BranchInst::Create(LoopStart, NewEntry);
861 }
862
Christian Konigfc6a9852013-02-16 11:27:45 +0000863 // Create an extra loop end node
864 LoopEnd = needPrefix(false);
865 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
866 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
867 BoolUndef, LoopEnd));
868 addPhiValues(LoopEnd, LoopStart);
869 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000870}
871
Tom Stellardf8794352012-12-19 22:10:31 +0000872/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000873/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000874void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000875 BasicBlock *Exit = ParentRegion->getExit();
876 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
877
Tom Stellardf8794352012-12-19 22:10:31 +0000878 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000879 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000880 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000881 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000882
Craig Topperf40110f2014-04-25 05:29:35 +0000883 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000884 Visited.clear();
885
Tom Stellardf8794352012-12-19 22:10:31 +0000886 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000887 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000888 }
889
Christian Konigfc6a9852013-02-16 11:27:45 +0000890 if (PrevNode)
891 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000892 else
893 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000894}
895
Tom Stellardf8794352012-12-19 22:10:31 +0000896/// Handle a rare case where the disintegrated nodes instructions
897/// no longer dominate all their uses. Not sure if this is really nessasary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000898void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000899 SSAUpdater Updater;
Richard Trieu6b1aa5f2015-04-15 01:21:15 +0000900 for (auto *BB : ParentRegion->blocks())
Tom Stellardf8794352012-12-19 22:10:31 +0000901 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
902 II != IE; ++II) {
903
904 bool Initialized = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000905 for (auto I = II->use_begin(), E = II->use_end(); I != E;) {
906 Use &U = *I++;
907 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000908 if (User->getParent() == BB) {
909 continue;
910
911 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000912 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000913 continue;
914 }
915
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000916 if (DT->dominates(&*II, User))
Tom Stellardf8794352012-12-19 22:10:31 +0000917 continue;
918
919 if (!Initialized) {
920 Value *Undef = UndefValue::get(II->getType());
921 Updater.Initialize(II->getType(), "");
922 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000923 Updater.AddAvailableValue(BB, &*II);
Tom Stellardf8794352012-12-19 22:10:31 +0000924 Initialized = true;
925 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000926 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000927 }
928 }
Tom Stellardf8794352012-12-19 22:10:31 +0000929}
930
Tom Stellard755a4e62016-02-10 00:39:37 +0000931bool StructurizeCFG::hasOnlyUniformBranches(const Region *R) {
932 for (const BasicBlock *BB : R->blocks()) {
933 const BranchInst *Br = dyn_cast<BranchInst>(BB->getTerminator());
934 if (!Br || !Br->isConditional())
935 continue;
936
937 if (!DA->isUniform(Br->getCondition()))
938 return false;
939 DEBUG(dbgs() << "BB: " << BB->getName() << " has uniform terminator\n");
940 }
941 return true;
942}
943
Tom Stellardf8794352012-12-19 22:10:31 +0000944/// \brief Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000945bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000946 if (R->isTopLevelRegion())
947 return false;
948
Tom Stellard755a4e62016-02-10 00:39:37 +0000949 if (SkipUniformRegions) {
950 DA = &getAnalysis<DivergenceAnalysis>();
951 // TODO: We could probably be smarter here with how we handle sub-regions.
952 if (hasOnlyUniformBranches(R)) {
953 DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R << '\n');
954 return false;
955 }
956 }
957
Tom Stellardf8794352012-12-19 22:10:31 +0000958 Func = R->getEntry()->getParent();
959 ParentRegion = R;
960
Chandler Carruth73523022014-01-13 13:07:17 +0000961 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000962 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +0000963
964 orderNodes();
965 collectInfos();
966 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000967 insertConditions(false);
968 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000969 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +0000970 rebuildSSA();
971
Tom Stellard048f14f2013-02-08 22:24:37 +0000972 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +0000973 Order.clear();
974 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000975 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000976 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000977 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000978 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000979 Loops.clear();
980 LoopPreds.clear();
981 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000982
983 return true;
984}
985
Tom Stellard755a4e62016-02-10 00:39:37 +0000986Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
987 return new StructurizeCFG(SkipUniformRegions);
Tom Stellardf8794352012-12-19 22:10:31 +0000988}