blob: 1d93374be9eababe2ea5ed515e98b3876dc55a0f [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.
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000144/// The incoming values of the PHI node are true for the "If" edge and false
Tom Stellardf8794352012-12-19 22:10:31 +0000145/// 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;
Tom Stellard755a4e62016-02-10 00:39:37 +0000166
Tom Stellardf8794352012-12-19 22:10:31 +0000167 Type *Boolean;
168 ConstantInt *BoolTrue;
169 ConstantInt *BoolFalse;
170 UndefValue *BoolUndef;
171
172 Function *Func;
173 Region *ParentRegion;
174
175 DominatorTree *DT;
Tom Stellard1f0dded2014-12-03 04:28:32 +0000176 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000177
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000178 SmallVector<RegionNode *, 8> Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000179 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000180
Tom Stellardf8794352012-12-19 22:10:31 +0000181 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000182 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000183
184 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000185 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000186
Christian Konigfc6a9852013-02-16 11:27:45 +0000187 BB2BBMap Loops;
188 PredMap LoopPreds;
189 BranchVector LoopConds;
190
191 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000192
193 void orderNodes();
194
Christian Konigfc6a9852013-02-16 11:27:45 +0000195 void analyzeLoops(RegionNode *N);
196
Christian Konigd8860992013-02-16 11:27:50 +0000197 Value *invert(Value *Condition);
198
Tom Stellard048f14f2013-02-08 22:24:37 +0000199 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000200
Christian Konigfc6a9852013-02-16 11:27:45 +0000201 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000202
203 void collectInfos();
204
Christian Konigfc6a9852013-02-16 11:27:45 +0000205 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000206
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000207 void delPhiValues(BasicBlock *From, BasicBlock *To);
208
209 void addPhiValues(BasicBlock *From, BasicBlock *To);
210
211 void setPhiValues();
212
Tom Stellardf8794352012-12-19 22:10:31 +0000213 void killTerminator(BasicBlock *BB);
214
Tom Stellard7370ede2013-02-08 22:24:38 +0000215 void changeExit(RegionNode *Node, BasicBlock *NewExit,
216 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000217
Tom Stellard7370ede2013-02-08 22:24:38 +0000218 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000219
Christian Konigfc6a9852013-02-16 11:27:45 +0000220 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000221
Tom Stellard7370ede2013-02-08 22:24:38 +0000222 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
223
Christian Konigfc6a9852013-02-16 11:27:45 +0000224 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000225
226 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
227
Christian Konigfc6a9852013-02-16 11:27:45 +0000228 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000229
Christian Konigfc6a9852013-02-16 11:27:45 +0000230 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
231
232 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000233
234 void createFlow();
235
Tom Stellardf8794352012-12-19 22:10:31 +0000236 void rebuildSSA();
237
238public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000239 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000240
Justin Lebar73c4baf2016-11-22 23:13:44 +0000241 explicit StructurizeCFG(bool SkipUniformRegions = false)
242 : RegionPass(ID), SkipUniformRegions(SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000243 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
244 }
245
Craig Topper3e4c6972014-03-05 09:10:37 +0000246 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000247
Craig Topper3e4c6972014-03-05 09:10:37 +0000248 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000249
Mehdi Amini117296c2016-10-01 02:56:57 +0000250 StringRef getPassName() const override { return "Structurize control flow"; }
Tom Stellardf8794352012-12-19 22:10:31 +0000251
Craig Topper3e4c6972014-03-05 09:10:37 +0000252 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard755a4e62016-02-10 00:39:37 +0000253 if (SkipUniformRegions)
254 AU.addRequired<DivergenceAnalysis>();
Tom Stellardd3e916e2013-10-02 17:04:59 +0000255 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000256 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000257 AU.addRequired<LoopInfoWrapperPass>();
Justin Lebar23aaf602016-11-22 23:14:07 +0000258
Chandler Carruth73523022014-01-13 13:07:17 +0000259 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000260 RegionPass::getAnalysisUsage(AU);
261 }
Tom Stellardf8794352012-12-19 22:10:31 +0000262};
263
264} // end anonymous namespace
265
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000266char StructurizeCFG::ID = 0;
267
268INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
269 false, false)
Tom Stellard755a4e62016-02-10 00:39:37 +0000270INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000271INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000272INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000273INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000274INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
275 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000276
277/// \brief Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000278bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000279 LLVMContext &Context = R->getEntry()->getContext();
280
281 Boolean = Type::getInt1Ty(Context);
282 BoolTrue = ConstantInt::getTrue(Context);
283 BoolFalse = ConstantInt::getFalse(Context);
284 BoolUndef = UndefValue::get(Boolean);
285
286 return false;
287}
288
289/// \brief Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000290void StructurizeCFG::orderNodes() {
Tom Stellard071ec902015-02-04 20:49:44 +0000291 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000292 SmallDenseMap<Loop*, unsigned, 8> LoopBlocks;
Tom Stellard071ec902015-02-04 20:49:44 +0000293
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.
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000297 for (RegionNode *RN : RPOT) {
Tom Stellard071ec902015-02-04 20:49:44 +0000298 BasicBlock *BB = RN->getEntry();
299 Loop *Loop = LI->getLoopFor(BB);
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000300 ++LoopBlocks[Loop];
Tom Stellardf8794352012-12-19 22:10:31 +0000301 }
Tom Stellard071ec902015-02-04 20:49:44 +0000302
303 unsigned CurrentLoopDepth = 0;
304 Loop *CurrentLoop = nullptr;
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000305 for (auto I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
Tom Stellard071ec902015-02-04 20:49:44 +0000306 BasicBlock *BB = (*I)->getEntry();
307 unsigned LoopDepth = LI->getLoopDepth(BB);
308
David Majnemer0d955d02016-08-11 22:21:41 +0000309 if (is_contained(Order, *I))
Tom Stellard071ec902015-02-04 20:49:44 +0000310 continue;
311
312 if (LoopDepth < CurrentLoopDepth) {
313 // Make sure we have visited all blocks in this loop before moving back to
314 // the outer loop.
315
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000316 auto LoopI = I;
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000317 while (unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
Tom Stellard071ec902015-02-04 20:49:44 +0000318 LoopI++;
319 BasicBlock *LoopBB = (*LoopI)->getEntry();
320 if (LI->getLoopFor(LoopBB) == CurrentLoop) {
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000321 --BlockCount;
Tom Stellard071ec902015-02-04 20:49:44 +0000322 Order.push_back(*LoopI);
323 }
324 }
325 }
326
327 CurrentLoop = LI->getLoopFor(BB);
Justin Lebar6c0f25a2016-11-22 23:14:11 +0000328 if (CurrentLoop)
Tom Stellard071ec902015-02-04 20:49:44 +0000329 LoopBlocks[CurrentLoop]--;
Tom Stellard071ec902015-02-04 20:49:44 +0000330
331 CurrentLoopDepth = LoopDepth;
332 Order.push_back(*I);
333 }
334
335 // This pass originally used a post-order traversal and then operated on
336 // the list in reverse. Now that we are using a reverse post-order traversal
337 // rather than re-working the whole pass to operate on the list in order,
338 // we just reverse the list and continue to operate on it in reverse.
339 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000340}
341
Christian Konigfc6a9852013-02-16 11:27:45 +0000342/// \brief Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000343void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000344 if (N->isSubRegion()) {
345 // Test for exit as back edge
346 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
347 if (Visited.count(Exit))
348 Loops[Exit] = N->getEntry();
349
350 } else {
351 // Test for sucessors as back edge
352 BasicBlock *BB = N->getNodeAs<BasicBlock>();
353 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
354
Pete Cooperebcd7482015-08-06 20:22:46 +0000355 for (BasicBlock *Succ : Term->successors())
356 if (Visited.count(Succ))
Christian Konigfc6a9852013-02-16 11:27:45 +0000357 Loops[Succ] = BB;
Christian Konigfc6a9852013-02-16 11:27:45 +0000358 }
359}
360
Christian Konigd8860992013-02-16 11:27:50 +0000361/// \brief Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000362Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000363 // First: Check if it's a constant
Matt Arsenault93be6e82016-07-15 22:13:16 +0000364 if (Constant *C = dyn_cast<Constant>(Condition))
365 return ConstantExpr::getNot(C);
Christian Konigd8860992013-02-16 11:27:50 +0000366
367 // Second: If the condition is already inverted, return the original value
368 if (match(Condition, m_Not(m_Value(Condition))))
369 return Condition;
370
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000371 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
372 // Third: Check all the users for an invert
373 BasicBlock *Parent = Inst->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000374 for (User *U : Condition->users())
375 if (Instruction *I = dyn_cast<Instruction>(U))
376 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
377 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000378
379 // Last option: Create a new instruction
380 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000381 }
382
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000383 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
384 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
385 return BinaryOperator::CreateNot(Condition,
386 Arg->getName() + ".inv",
387 EntryBlock.getTerminator());
388 }
389
390 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000391}
392
Tom Stellard048f14f2013-02-08 22:24:37 +0000393/// \brief Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000394Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
395 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000396 Value *Cond = Invert ? BoolFalse : BoolTrue;
397 if (Term->isConditional()) {
398 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000399
Aaron Ballman19978552013-06-04 01:03:03 +0000400 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000401 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000402 }
403 return Cond;
404}
405
Tom Stellard048f14f2013-02-08 22:24:37 +0000406/// \brief Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000407void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000408 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000409 BasicBlock *BB = N->getEntry();
410 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000411 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000412
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000413 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
414 PI != PE; ++PI) {
415
Christian Konigfc6a9852013-02-16 11:27:45 +0000416 // Ignore it if it's a branch from outside into our region entry
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000417 if (!ParentRegion->contains(*PI))
Tom Stellard048f14f2013-02-08 22:24:37 +0000418 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000419
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000420 Region *R = RI->getRegionFor(*PI);
Tom Stellard048f14f2013-02-08 22:24:37 +0000421 if (R == ParentRegion) {
Tom Stellardf8794352012-12-19 22:10:31 +0000422
Tom Stellard048f14f2013-02-08 22:24:37 +0000423 // It's a top level block in our region
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000424 BranchInst *Term = cast<BranchInst>((*PI)->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000425 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
426 BasicBlock *Succ = Term->getSuccessor(i);
427 if (Succ != BB)
428 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000429
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000430 if (Visited.count(*PI)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000431 // Normal forward edge
432 if (Term->isConditional()) {
433 // Try to treat it like an ELSE block
434 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000435 if (Visited.count(Other) && !Loops.count(Other) &&
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000436 !Pred.count(Other) && !Pred.count(*PI)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000437
Tom Stellard048f14f2013-02-08 22:24:37 +0000438 Pred[Other] = BoolFalse;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000439 Pred[*PI] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000440 continue;
441 }
442 }
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000443 Pred[*PI] = buildCondition(Term, i, false);
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000444
Tom Stellard048f14f2013-02-08 22:24:37 +0000445 } else {
446 // Back edge
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000447 LPred[*PI] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000448 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000449 }
450
451 } else {
452
453 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000454 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000455 R = R->getParent();
456
457 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000458 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000459 continue;
460
461 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000462 if (Visited.count(Entry))
463 Pred[Entry] = BoolTrue;
464 else
465 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000466 }
467 }
468}
469
470/// \brief Collect various loop and predicate infos
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000471void StructurizeCFG::collectInfos() {
Tom Stellardf8794352012-12-19 22:10:31 +0000472 // Reset predicate
473 Predicates.clear();
474
475 // and loop infos
Christian Konigfc6a9852013-02-16 11:27:45 +0000476 Loops.clear();
477 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000478
Tom Stellard048f14f2013-02-08 22:24:37 +0000479 // Reset the visited nodes
480 Visited.clear();
481
David Majnemerd7708772016-06-24 04:05:21 +0000482 for (RegionNode *RN : reverse(Order)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000483
David Majnemerd7708772016-06-24 04:05:21 +0000484 DEBUG(dbgs() << "Visiting: "
485 << (RN->isSubRegion() ? "SubRegion with entry: " : "")
486 << RN->getEntry()->getName() << " Loop Depth: "
487 << LI->getLoopDepth(RN->getEntry()) << "\n");
Tom Stellard071ec902015-02-04 20:49:44 +0000488
Tom Stellardf8794352012-12-19 22:10:31 +0000489 // Analyze all the conditions leading to a node
David Majnemerd7708772016-06-24 04:05:21 +0000490 gatherPredicates(RN);
Tom Stellardf8794352012-12-19 22:10:31 +0000491
Tom Stellard048f14f2013-02-08 22:24:37 +0000492 // Remember that we've seen this node
David Majnemerd7708772016-06-24 04:05:21 +0000493 Visited.insert(RN->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000494
Christian Konigfc6a9852013-02-16 11:27:45 +0000495 // Find the last back edges
David Majnemerd7708772016-06-24 04:05:21 +0000496 analyzeLoops(RN);
Tom Stellard048f14f2013-02-08 22:24:37 +0000497 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000498}
499
500/// \brief Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000501void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000502 BranchVector &Conds = Loops ? LoopConds : Conditions;
503 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000504 SSAUpdater PhiInserter;
505
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000506 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000507 assert(Term->isConditional());
508
Christian Konigfc6a9852013-02-16 11:27:45 +0000509 BasicBlock *Parent = Term->getParent();
510 BasicBlock *SuccTrue = Term->getSuccessor(0);
511 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000512
Christian Konigb5d88662013-02-16 11:27:40 +0000513 PhiInserter.Initialize(Boolean, "");
514 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000515 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000516
Christian Konigfc6a9852013-02-16 11:27:45 +0000517 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000518
519 NearestCommonDominator Dominator(DT);
520 Dominator.addBlock(Parent, false);
521
Craig Topperf40110f2014-04-25 05:29:35 +0000522 Value *ParentValue = nullptr;
Tom Stellard048f14f2013-02-08 22:24:37 +0000523 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
524 PI != PE; ++PI) {
525
Christian Konigb5d88662013-02-16 11:27:40 +0000526 if (PI->first == Parent) {
527 ParentValue = PI->second;
528 break;
529 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000530 PhiInserter.AddAvailableValue(PI->first, PI->second);
Christian Konigb5d88662013-02-16 11:27:40 +0000531 Dominator.addBlock(PI->first);
Tom Stellard048f14f2013-02-08 22:24:37 +0000532 }
533
Christian Konigb5d88662013-02-16 11:27:40 +0000534 if (ParentValue) {
535 Term->setCondition(ParentValue);
536 } else {
537 if (!Dominator.wasResultExplicitMentioned())
538 PhiInserter.AddAvailableValue(Dominator.getResult(), Default);
539
Tom Stellard048f14f2013-02-08 22:24:37 +0000540 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000541 }
Tom Stellardf8794352012-12-19 22:10:31 +0000542 }
543}
544
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000545/// \brief Remove all PHI values coming from "From" into "To" and remember
546/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000547void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000548 PhiMap &Map = DeletedPhis[To];
549 for (BasicBlock::iterator I = To->begin(), E = To->end();
550 I != E && isa<PHINode>(*I);) {
551
552 PHINode &Phi = cast<PHINode>(*I++);
553 while (Phi.getBasicBlockIndex(From) != -1) {
554 Value *Deleted = Phi.removeIncomingValue(From, false);
555 Map[&Phi].push_back(std::make_pair(From, Deleted));
556 }
557 }
558}
559
560/// \brief Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000561void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000562 for (BasicBlock::iterator I = To->begin(), E = To->end();
563 I != E && isa<PHINode>(*I);) {
564
565 PHINode &Phi = cast<PHINode>(*I++);
566 Value *Undef = UndefValue::get(Phi.getType());
567 Phi.addIncoming(Undef, From);
568 }
569 AddedPhis[To].push_back(From);
570}
571
572/// \brief Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000573void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000574 SSAUpdater Updater;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000575 for (const auto &AddedPhi : AddedPhis) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000576
Benjamin Kramer135f7352016-06-26 12:28:59 +0000577 BasicBlock *To = AddedPhi.first;
578 const BBVector &From = AddedPhi.second;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000579
580 if (!DeletedPhis.count(To))
581 continue;
582
583 PhiMap &Map = DeletedPhis[To];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000584 for (const auto &PI : Map) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000585
Benjamin Kramer135f7352016-06-26 12:28:59 +0000586 PHINode *Phi = PI.first;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000587 Value *Undef = UndefValue::get(Phi->getType());
588 Updater.Initialize(Phi->getType(), "");
589 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
590 Updater.AddAvailableValue(To, Undef);
591
Christian Konig0bccf9d2013-02-16 11:27:35 +0000592 NearestCommonDominator Dominator(DT);
593 Dominator.addBlock(To, false);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000594 for (const auto &VI : PI.second) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000595
Benjamin Kramer135f7352016-06-26 12:28:59 +0000596 Updater.AddAvailableValue(VI.first, VI.second);
597 Dominator.addBlock(VI.first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000598 }
599
Christian Konig0bccf9d2013-02-16 11:27:35 +0000600 if (!Dominator.wasResultExplicitMentioned())
601 Updater.AddAvailableValue(Dominator.getResult(), Undef);
602
Benjamin Kramer135f7352016-06-26 12:28:59 +0000603 for (BasicBlock *FI : From) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000604
Benjamin Kramer135f7352016-06-26 12:28:59 +0000605 int Idx = Phi->getBasicBlockIndex(FI);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000606 assert(Idx != -1);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000607 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(FI));
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000608 }
609 }
610
611 DeletedPhis.erase(To);
612 }
613 assert(DeletedPhis.empty());
614}
615
Tom Stellard7370ede2013-02-08 22:24:38 +0000616/// \brief Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000617void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000618 TerminatorInst *Term = BB->getTerminator();
619 if (!Term)
620 return;
621
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000622 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
623 SI != SE; ++SI) {
624
625 delPhiValues(BB, *SI);
626 }
Tom Stellardf8794352012-12-19 22:10:31 +0000627
628 Term->eraseFromParent();
629}
630
Tom Stellard7370ede2013-02-08 22:24:38 +0000631/// \brief Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000632void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
633 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000634 if (Node->isSubRegion()) {
635 Region *SubRegion = Node->getNodeAs<Region>();
636 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000637 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000638
Tom Stellard7370ede2013-02-08 22:24:38 +0000639 // Find all the edges from the sub region to the exit
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000640 for (pred_iterator I = pred_begin(OldExit), E = pred_end(OldExit);
641 I != E;) {
642
643 BasicBlock *BB = *I++;
Tom Stellard7370ede2013-02-08 22:24:38 +0000644 if (!SubRegion->contains(BB))
645 continue;
646
647 // Modify the edges to point to the new exit
648 delPhiValues(BB, OldExit);
649 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
650 addPhiValues(BB, NewExit);
651
652 // Find the new dominator (if requested)
653 if (IncludeDominator) {
654 if (!Dominator)
655 Dominator = BB;
656 else
657 Dominator = DT->findNearestCommonDominator(Dominator, BB);
658 }
Tom Stellardf8794352012-12-19 22:10:31 +0000659 }
660
Tom Stellard7370ede2013-02-08 22:24:38 +0000661 // Change the dominator (if requested)
662 if (Dominator)
663 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000664
Tom Stellard7370ede2013-02-08 22:24:38 +0000665 // Update the region info
666 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000667
Tom Stellardf8794352012-12-19 22:10:31 +0000668 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000669 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
670 killTerminator(BB);
671 BranchInst::Create(NewExit, BB);
672 addPhiValues(BB, NewExit);
673 if (IncludeDominator)
674 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000675 }
Tom Stellardf8794352012-12-19 22:10:31 +0000676}
677
Tom Stellardf8794352012-12-19 22:10:31 +0000678/// \brief Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000679BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000680 LLVMContext &Context = Func->getContext();
681 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
682 Order.back()->getEntry();
683 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
684 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000685 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000686 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000687 return Flow;
688}
689
Tom Stellard7370ede2013-02-08 22:24:38 +0000690/// \brief Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000691BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000692 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000693
Christian Konigfc6a9852013-02-16 11:27:45 +0000694 if (!PrevNode->isSubRegion()) {
695 killTerminator(Entry);
696 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
697 return Entry;
Tom Stellard7370ede2013-02-08 22:24:38 +0000698
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000699 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000700
Christian Konigfc6a9852013-02-16 11:27:45 +0000701 // create a new flow node
702 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000703
Christian Konigfc6a9852013-02-16 11:27:45 +0000704 // and wire it up
705 changeExit(PrevNode, Flow, true);
706 PrevNode = ParentRegion->getBBNode(Flow);
707 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000708}
709
710/// \brief Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000711BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
712 bool ExitUseAllowed) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000713 if (Order.empty() && ExitUseAllowed) {
714 BasicBlock *Exit = ParentRegion->getExit();
715 DT->changeImmediateDominator(Exit, Flow);
716 addPhiValues(Flow, Exit);
717 return Exit;
718 }
719 return getNextFlow(Flow);
720}
721
Christian Konigfc6a9852013-02-16 11:27:45 +0000722/// \brief Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000723void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000724 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
725 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000726}
727
728/// \brief Does BB dominate all the predicates of Node ?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000729bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000730 BBPredicates &Preds = Predicates[Node->getEntry()];
731 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
732 PI != PE; ++PI) {
733
734 if (!DT->dominates(BB, PI->first))
735 return false;
736 }
737 return true;
738}
739
Tom Stellardf8794352012-12-19 22:10:31 +0000740/// \brief Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000741bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000742 BBPredicates &Preds = Predicates[Node->getEntry()];
743 bool Dominated = false;
744
745 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000746 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000747 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000748
749 for (BBPredicates::iterator I = Preds.begin(), E = Preds.end();
750 I != E; ++I) {
751
752 if (I->second != BoolTrue)
753 return false;
754
Christian Konigfc6a9852013-02-16 11:27:45 +0000755 if (!Dominated && DT->dominates(I->first, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000756 Dominated = true;
757 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000758
759 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000760 return Dominated;
761}
762
Tom Stellard7370ede2013-02-08 22:24:38 +0000763/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000764void StructurizeCFG::wireFlow(bool ExitUseAllowed,
765 BasicBlock *LoopEnd) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000766 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000767 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000768
Christian Konigfc6a9852013-02-16 11:27:45 +0000769 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000770 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000771 if (PrevNode) {
772 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000773 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000774 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000775
776 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000777 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000778 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000779
Tom Stellard7370ede2013-02-08 22:24:38 +0000780 // Insert extra postfix node (or use exit instead)
781 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000782 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000783
784 // let it point to entry and next block
785 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
786 addPhiValues(Flow, Entry);
787 DT->changeImmediateDominator(Entry, Flow);
788
Christian Konigfc6a9852013-02-16 11:27:45 +0000789 PrevNode = Node;
790 while (!Order.empty() && !Visited.count(LoopEnd) &&
Tom Stellard7370ede2013-02-08 22:24:38 +0000791 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000792 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000793 }
794
Christian Konigfc6a9852013-02-16 11:27:45 +0000795 changeExit(PrevNode, Next, false);
796 setPrevNode(Next);
797 }
798}
799
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000800void StructurizeCFG::handleLoops(bool ExitUseAllowed,
801 BasicBlock *LoopEnd) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000802 RegionNode *Node = Order.back();
803 BasicBlock *LoopStart = Node->getEntry();
804
805 if (!Loops.count(LoopStart)) {
806 wireFlow(ExitUseAllowed, LoopEnd);
807 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000808 }
809
Christian Konigfc6a9852013-02-16 11:27:45 +0000810 if (!isPredictableTrue(Node))
811 LoopStart = needPrefix(true);
812
813 LoopEnd = Loops[Node->getEntry()];
814 wireFlow(false, LoopEnd);
815 while (!Visited.count(LoopEnd)) {
816 handleLoops(false, LoopEnd);
817 }
818
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000819 // If the start of the loop is the entry block, we can't branch to it so
820 // insert a new dummy entry block.
821 Function *LoopFunc = LoopStart->getParent();
822 if (LoopStart == &LoopFunc->getEntryBlock()) {
823 LoopStart->setName("entry.orig");
824
825 BasicBlock *NewEntry =
826 BasicBlock::Create(LoopStart->getContext(),
827 "entry",
828 LoopFunc,
829 LoopStart);
830 BranchInst::Create(LoopStart, NewEntry);
831 }
832
Christian Konigfc6a9852013-02-16 11:27:45 +0000833 // Create an extra loop end node
834 LoopEnd = needPrefix(false);
835 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
836 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
837 BoolUndef, LoopEnd));
838 addPhiValues(LoopEnd, LoopStart);
839 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000840}
841
Tom Stellardf8794352012-12-19 22:10:31 +0000842/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000843/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000844void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000845 BasicBlock *Exit = ParentRegion->getExit();
846 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
847
Tom Stellardf8794352012-12-19 22:10:31 +0000848 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000849 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000850 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000851 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000852
Craig Topperf40110f2014-04-25 05:29:35 +0000853 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000854 Visited.clear();
855
Tom Stellardf8794352012-12-19 22:10:31 +0000856 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000857 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000858 }
859
Christian Konigfc6a9852013-02-16 11:27:45 +0000860 if (PrevNode)
861 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000862 else
863 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000864}
865
Tom Stellardf8794352012-12-19 22:10:31 +0000866/// Handle a rare case where the disintegrated nodes instructions
867/// no longer dominate all their uses. Not sure if this is really nessasary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000868void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000869 SSAUpdater Updater;
Richard Trieu6b1aa5f2015-04-15 01:21:15 +0000870 for (auto *BB : ParentRegion->blocks())
Tom Stellardf8794352012-12-19 22:10:31 +0000871 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
872 II != IE; ++II) {
873
874 bool Initialized = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000875 for (auto I = II->use_begin(), E = II->use_end(); I != E;) {
876 Use &U = *I++;
877 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000878 if (User->getParent() == BB) {
879 continue;
880
881 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000882 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000883 continue;
884 }
885
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000886 if (DT->dominates(&*II, User))
Tom Stellardf8794352012-12-19 22:10:31 +0000887 continue;
888
889 if (!Initialized) {
890 Value *Undef = UndefValue::get(II->getType());
891 Updater.Initialize(II->getType(), "");
892 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000893 Updater.AddAvailableValue(BB, &*II);
Tom Stellardf8794352012-12-19 22:10:31 +0000894 Initialized = true;
895 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000896 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000897 }
898 }
Tom Stellardf8794352012-12-19 22:10:31 +0000899}
900
Justin Lebarc7445d52016-11-22 23:13:33 +0000901static bool hasOnlyUniformBranches(const Region *R,
902 const DivergenceAnalysis &DA) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000903 for (const BasicBlock *BB : R->blocks()) {
904 const BranchInst *Br = dyn_cast<BranchInst>(BB->getTerminator());
905 if (!Br || !Br->isConditional())
906 continue;
907
Justin Lebarc7445d52016-11-22 23:13:33 +0000908 if (!DA.isUniform(Br->getCondition()))
Tom Stellard755a4e62016-02-10 00:39:37 +0000909 return false;
910 DEBUG(dbgs() << "BB: " << BB->getName() << " has uniform terminator\n");
911 }
912 return true;
913}
914
Tom Stellardf8794352012-12-19 22:10:31 +0000915/// \brief Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000916bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000917 if (R->isTopLevelRegion())
918 return false;
919
Tom Stellard755a4e62016-02-10 00:39:37 +0000920 if (SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000921 // TODO: We could probably be smarter here with how we handle sub-regions.
Justin Lebarc7445d52016-11-22 23:13:33 +0000922 auto &DA = getAnalysis<DivergenceAnalysis>();
923 if (hasOnlyUniformBranches(R, DA)) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000924 DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R << '\n');
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000925
926 // Mark all direct child block terminators as having been treated as
927 // uniform. To account for a possible future in which non-uniform
928 // sub-regions are treated more cleverly, indirect children are not
929 // marked as uniform.
930 MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
Justin Lebar1b60d702016-11-22 23:13:37 +0000931 for (RegionNode *E : R->elements()) {
932 if (E->isSubRegion())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000933 continue;
934
Justin Lebar1b60d702016-11-22 23:13:37 +0000935 if (Instruction *Term = E->getEntry()->getTerminator())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000936 Term->setMetadata("structurizecfg.uniform", MD);
937 }
938
Tom Stellard755a4e62016-02-10 00:39:37 +0000939 return false;
940 }
941 }
942
Tom Stellardf8794352012-12-19 22:10:31 +0000943 Func = R->getEntry()->getParent();
944 ParentRegion = R;
945
Chandler Carruth73523022014-01-13 13:07:17 +0000946 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000947 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +0000948
949 orderNodes();
950 collectInfos();
951 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000952 insertConditions(false);
953 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000954 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +0000955 rebuildSSA();
956
Tom Stellard048f14f2013-02-08 22:24:37 +0000957 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +0000958 Order.clear();
959 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000960 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000961 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000962 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000963 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000964 Loops.clear();
965 LoopPreds.clear();
966 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000967
968 return true;
969}
970
Tom Stellard755a4e62016-02-10 00:39:37 +0000971Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
972 return new StructurizeCFG(SkipUniformRegions);
Tom Stellardf8794352012-12-19 22:10:31 +0000973}