blob: 9791cf41f6212fb86f0d96672e9d903b7d723e98 [file] [log] [blame]
Eugene Zelenko99241d72017-10-20 21:47:29 +00001//===- StructurizeCFG.cpp -------------------------------------------------===//
Tom Stellardf8794352012-12-19 22:10:31 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tom Stellardf8794352012-12-19 22:10:31 +00006//
7//===----------------------------------------------------------------------===//
Tom Stellardf8794352012-12-19 22:10:31 +00008
Eugene Zelenko99241d72017-10-20 21:47:29 +00009#include "llvm/ADT/DenseMap.h"
Christian Konig90b45122013-03-26 10:24:20 +000010#include "llvm/ADT/MapVector.h"
Tom Stellard071ec902015-02-04 20:49:44 +000011#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000012#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/SmallPtrSet.h"
14#include "llvm/ADT/SmallVector.h"
Nicolai Haehnle08230502018-10-17 15:37:41 +000015#include "llvm/Analysis/InstructionSimplify.h"
Nicolai Haehnle35617ed2018-08-30 14:21:36 +000016#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +000017#include "llvm/Analysis/LoopInfo.h"
Tom Stellardf8794352012-12-19 22:10:31 +000018#include "llvm/Analysis/RegionInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000019#include "llvm/Analysis/RegionIterator.h"
Tom Stellardf8794352012-12-19 22:10:31 +000020#include "llvm/Analysis/RegionPass.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000021#include "llvm/IR/Argument.h"
22#include "llvm/IR/BasicBlock.h"
23#include "llvm/IR/CFG.h"
24#include "llvm/IR/Constant.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/Dominators.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000032#include "llvm/IR/PatternMatch.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000033#include "llvm/IR/Type.h"
34#include "llvm/IR/Use.h"
35#include "llvm/IR/User.h"
36#include "llvm/IR/Value.h"
37#include "llvm/Pass.h"
38#include "llvm/Support/Casting.h"
Tom Stellard071ec902015-02-04 20:49:44 +000039#include "llvm/Support/Debug.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000040#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000041#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000042#include "llvm/Transforms/Scalar.h"
David Blaikiea373d182018-03-28 17:44:36 +000043#include "llvm/Transforms/Utils.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000044#include "llvm/Transforms/Utils/SSAUpdater.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000045#include <algorithm>
46#include <cassert>
47#include <utility>
Tom Stellardf8794352012-12-19 22:10:31 +000048
49using namespace llvm;
Christian Konigd8860992013-02-16 11:27:50 +000050using namespace llvm::PatternMatch;
Tom Stellardf8794352012-12-19 22:10:31 +000051
Chandler Carruth964daaa2014-04-22 02:55:47 +000052#define DEBUG_TYPE "structurizecfg"
53
Eugene Zelenko99241d72017-10-20 21:47:29 +000054// The name for newly created blocks.
55static const char *const FlowBlockName = "Flow";
56
Tom Stellardf8794352012-12-19 22:10:31 +000057namespace {
58
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +000059static cl::opt<bool> ForceSkipUniformRegions(
60 "structurizecfg-skip-uniform-regions",
61 cl::Hidden,
62 cl::desc("Force whether the StructurizeCFG pass skips uniform regions"),
63 cl::init(false));
64
Neil Henning119c31a2019-05-24 08:59:17 +000065static cl::opt<bool>
66 RelaxedUniformRegions("structurizecfg-relaxed-uniform-regions", cl::Hidden,
67 cl::desc("Allow relaxed uniform region checks"),
Tim Renouf5a079432019-08-06 14:30:19 +000068 cl::init(true));
Neil Henning119c31a2019-05-24 08:59:17 +000069
Tom Stellardf8794352012-12-19 22:10:31 +000070// Definition of the complex types used in this pass.
71
Eugene Zelenko99241d72017-10-20 21:47:29 +000072using BBValuePair = std::pair<BasicBlock *, Value *>;
Tom Stellardf8794352012-12-19 22:10:31 +000073
Eugene Zelenko99241d72017-10-20 21:47:29 +000074using RNVector = SmallVector<RegionNode *, 8>;
75using BBVector = SmallVector<BasicBlock *, 8>;
76using BranchVector = SmallVector<BranchInst *, 8>;
77using BBValueVector = SmallVector<BBValuePair, 2>;
Tom Stellardf8794352012-12-19 22:10:31 +000078
Eugene Zelenko99241d72017-10-20 21:47:29 +000079using BBSet = SmallPtrSet<BasicBlock *, 8>;
Tom Stellard048f14f2013-02-08 22:24:37 +000080
Eugene Zelenko99241d72017-10-20 21:47:29 +000081using PhiMap = MapVector<PHINode *, BBValueVector>;
82using BB2BBVecMap = MapVector<BasicBlock *, BBVector>;
Christian Konig90b45122013-03-26 10:24:20 +000083
Eugene Zelenko99241d72017-10-20 21:47:29 +000084using BBPhiMap = DenseMap<BasicBlock *, PhiMap>;
85using BBPredicates = DenseMap<BasicBlock *, Value *>;
86using PredMap = DenseMap<BasicBlock *, BBPredicates>;
87using BB2BBMap = DenseMap<BasicBlock *, BasicBlock *>;
Tom Stellardf8794352012-12-19 22:10:31 +000088
Justin Lebar62c20d82016-11-28 18:49:59 +000089/// Finds the nearest common dominator of a set of BasicBlocks.
Christian Konigd08e3d72013-02-16 11:27:29 +000090///
Justin Lebar62c20d82016-11-28 18:49:59 +000091/// For every BB you add to the set, you can specify whether we "remember" the
92/// block. When you get the common dominator, you can also ask whether it's one
93/// of the blocks we remembered.
Christian Konigd08e3d72013-02-16 11:27:29 +000094class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000095 DominatorTree *DT;
Justin Lebar62c20d82016-11-28 18:49:59 +000096 BasicBlock *Result = nullptr;
97 bool ResultIsRemembered = false;
Christian Konigd08e3d72013-02-16 11:27:29 +000098
Justin Lebar62c20d82016-11-28 18:49:59 +000099 /// Add BB to the resulting dominator.
100 void addBlock(BasicBlock *BB, bool Remember) {
Craig Topperf40110f2014-04-25 05:29:35 +0000101 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +0000102 Result = BB;
Justin Lebar62c20d82016-11-28 18:49:59 +0000103 ResultIsRemembered = Remember;
Christian Konigd08e3d72013-02-16 11:27:29 +0000104 return;
105 }
106
Justin Lebar62c20d82016-11-28 18:49:59 +0000107 BasicBlock *NewResult = DT->findNearestCommonDominator(Result, BB);
108 if (NewResult != Result)
109 ResultIsRemembered = false;
110 if (NewResult == BB)
111 ResultIsRemembered |= Remember;
112 Result = NewResult;
Christian Konigd08e3d72013-02-16 11:27:29 +0000113 }
114
Justin Lebar62c20d82016-11-28 18:49:59 +0000115public:
116 explicit NearestCommonDominator(DominatorTree *DomTree) : DT(DomTree) {}
117
118 void addBlock(BasicBlock *BB) {
119 addBlock(BB, /* Remember = */ false);
Christian Konigd08e3d72013-02-16 11:27:29 +0000120 }
121
Justin Lebar62c20d82016-11-28 18:49:59 +0000122 void addAndRememberBlock(BasicBlock *BB) {
123 addBlock(BB, /* Remember = */ true);
Christian Konigd08e3d72013-02-16 11:27:29 +0000124 }
Justin Lebar62c20d82016-11-28 18:49:59 +0000125
126 /// Get the nearest common dominator of all the BBs added via addBlock() and
127 /// addAndRememberBlock().
128 BasicBlock *result() { return Result; }
129
130 /// Is the BB returned by getResult() one of the blocks we added to the set
131 /// with addAndRememberBlock()?
132 bool resultIsRememberedBlock() { return ResultIsRemembered; }
Christian Konigd08e3d72013-02-16 11:27:29 +0000133};
134
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000135/// Transforms the control flow graph on one single entry/exit region
Tom Stellardf8794352012-12-19 22:10:31 +0000136/// at a time.
137///
138/// After the transform all "If"/"Then"/"Else" style control flow looks like
139/// this:
140///
141/// \verbatim
142/// 1
143/// ||
144/// | |
145/// 2 |
146/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000147/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000148/// 3
149/// || Where:
150/// | | 1 = "If" block, calculates the condition
151/// 4 | 2 = "Then" subregion, runs if the condition is true
152/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
153/// |/ 4 = "Else" optional subregion, runs if the condition is false
154/// 5 5 = "End" block, also rejoins the control flow
155/// \endverbatim
156///
157/// Control flow is expressed as a branch where the true exit goes into the
158/// "Then"/"Else" region, while the false exit skips the region
159/// The condition for the optional "Else" region is expressed as a PHI node.
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000160/// The incoming values of the PHI node are true for the "If" edge and false
Tom Stellardf8794352012-12-19 22:10:31 +0000161/// for the "Then" edge.
162///
163/// Additionally to that even complicated loops look like this:
164///
165/// \verbatim
166/// 1
167/// ||
168/// | |
169/// 2 ^ Where:
170/// | / 1 = "Entry" block
171/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
172/// 3 3 = "Flow" block, with back edge to entry block
173/// |
174/// \endverbatim
175///
176/// The back edge of the "Flow" block is always on the false side of the branch
177/// while the true side continues the general flow. So the loop condition
178/// consist of a network of PHI nodes where the true incoming values expresses
179/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000180class StructurizeCFG : public RegionPass {
Tom Stellard755a4e62016-02-10 00:39:37 +0000181 bool SkipUniformRegions;
Tom Stellard755a4e62016-02-10 00:39:37 +0000182
Tom Stellardf8794352012-12-19 22:10:31 +0000183 Type *Boolean;
184 ConstantInt *BoolTrue;
185 ConstantInt *BoolFalse;
186 UndefValue *BoolUndef;
187
188 Function *Func;
189 Region *ParentRegion;
190
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000191 LegacyDivergenceAnalysis *DA;
Tom Stellardf8794352012-12-19 22:10:31 +0000192 DominatorTree *DT;
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000193 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000194
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000195 SmallVector<RegionNode *, 8> Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000196 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000197
Tom Stellardf8794352012-12-19 22:10:31 +0000198 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000199 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000200
201 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000202 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000203
Christian Konigfc6a9852013-02-16 11:27:45 +0000204 BB2BBMap Loops;
205 PredMap LoopPreds;
206 BranchVector LoopConds;
207
208 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000209
210 void orderNodes();
211
Changpeng Fang5f915462018-05-23 18:34:48 +0000212 Loop *getAdjustedLoop(RegionNode *RN);
213 unsigned getAdjustedLoopDepth(RegionNode *RN);
214
Christian Konigfc6a9852013-02-16 11:27:45 +0000215 void analyzeLoops(RegionNode *N);
216
Christian Konigd8860992013-02-16 11:27:50 +0000217 Value *invert(Value *Condition);
218
Tom Stellard048f14f2013-02-08 22:24:37 +0000219 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000220
Christian Konigfc6a9852013-02-16 11:27:45 +0000221 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000222
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000223 void collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000224
Christian Konigfc6a9852013-02-16 11:27:45 +0000225 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000226
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000227 void delPhiValues(BasicBlock *From, BasicBlock *To);
228
229 void addPhiValues(BasicBlock *From, BasicBlock *To);
230
231 void setPhiValues();
232
Tom Stellardf8794352012-12-19 22:10:31 +0000233 void killTerminator(BasicBlock *BB);
234
Tom Stellard7370ede2013-02-08 22:24:38 +0000235 void changeExit(RegionNode *Node, BasicBlock *NewExit,
236 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000237
Tom Stellard7370ede2013-02-08 22:24:38 +0000238 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000239
Christian Konigfc6a9852013-02-16 11:27:45 +0000240 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000241
Tom Stellard7370ede2013-02-08 22:24:38 +0000242 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
243
Christian Konigfc6a9852013-02-16 11:27:45 +0000244 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000245
246 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
247
Christian Konigfc6a9852013-02-16 11:27:45 +0000248 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000249
Christian Konigfc6a9852013-02-16 11:27:45 +0000250 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
251
252 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000253
254 void createFlow();
255
Tom Stellardf8794352012-12-19 22:10:31 +0000256 void rebuildSSA();
257
258public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000259 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000260
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000261 explicit StructurizeCFG(bool SkipUniformRegions_ = false)
262 : RegionPass(ID),
263 SkipUniformRegions(SkipUniformRegions_) {
264 if (ForceSkipUniformRegions.getNumOccurrences())
265 SkipUniformRegions = ForceSkipUniformRegions.getValue();
Tom Stellard755a4e62016-02-10 00:39:37 +0000266 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
267 }
268
Craig Topper3e4c6972014-03-05 09:10:37 +0000269 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000270
Craig Topper3e4c6972014-03-05 09:10:37 +0000271 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000272
Mehdi Amini117296c2016-10-01 02:56:57 +0000273 StringRef getPassName() const override { return "Structurize control flow"; }
Tom Stellardf8794352012-12-19 22:10:31 +0000274
Craig Topper3e4c6972014-03-05 09:10:37 +0000275 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard755a4e62016-02-10 00:39:37 +0000276 if (SkipUniformRegions)
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000277 AU.addRequired<LegacyDivergenceAnalysis>();
Tom Stellardd3e916e2013-10-02 17:04:59 +0000278 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000279 AU.addRequired<DominatorTreeWrapperPass>();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000280 AU.addRequired<LoopInfoWrapperPass>();
Justin Lebar23aaf602016-11-22 23:14:07 +0000281
Chandler Carruth73523022014-01-13 13:07:17 +0000282 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000283 RegionPass::getAnalysisUsage(AU);
284 }
Tom Stellardf8794352012-12-19 22:10:31 +0000285};
286
287} // end anonymous namespace
288
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000289char StructurizeCFG::ID = 0;
290
291INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
292 false, false)
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000293INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000294INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000295INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000296INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000297INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
298 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000299
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000300/// Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000301bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000302 LLVMContext &Context = R->getEntry()->getContext();
303
304 Boolean = Type::getInt1Ty(Context);
305 BoolTrue = ConstantInt::getTrue(Context);
306 BoolFalse = ConstantInt::getFalse(Context);
307 BoolUndef = UndefValue::get(Boolean);
308
309 return false;
310}
311
Changpeng Fang5f915462018-05-23 18:34:48 +0000312/// Use the exit block to determine the loop if RN is a SubRegion.
313Loop *StructurizeCFG::getAdjustedLoop(RegionNode *RN) {
314 if (RN->isSubRegion()) {
315 Region *SubRegion = RN->getNodeAs<Region>();
316 return LI->getLoopFor(SubRegion->getExit());
317 }
318
319 return LI->getLoopFor(RN->getEntry());
320}
321
322/// Use the exit block to determine the loop depth if RN is a SubRegion.
323unsigned StructurizeCFG::getAdjustedLoopDepth(RegionNode *RN) {
324 if (RN->isSubRegion()) {
325 Region *SubR = RN->getNodeAs<Region>();
326 return LI->getLoopDepth(SubR->getExit());
327 }
328
329 return LI->getLoopDepth(RN->getEntry());
330}
331
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000332/// Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000333void StructurizeCFG::orderNodes() {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000334 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
335 SmallDenseMap<Loop*, unsigned, 8> LoopBlocks;
Tom Stellard071ec902015-02-04 20:49:44 +0000336
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000337 // The reverse post-order traversal of the list gives us an ordering close
338 // to what we want. The only problem with it is that sometimes backedges
339 // for outer loops will be visited before backedges for inner loops.
340 for (RegionNode *RN : RPOT) {
Changpeng Fang5f915462018-05-23 18:34:48 +0000341 Loop *Loop = getAdjustedLoop(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000342 ++LoopBlocks[Loop];
Tom Stellardf8794352012-12-19 22:10:31 +0000343 }
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000344
345 unsigned CurrentLoopDepth = 0;
346 Loop *CurrentLoop = nullptr;
347 for (auto I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
Changpeng Fang5f915462018-05-23 18:34:48 +0000348 RegionNode *RN = cast<RegionNode>(*I);
349 unsigned LoopDepth = getAdjustedLoopDepth(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000350
351 if (is_contained(Order, *I))
352 continue;
353
354 if (LoopDepth < CurrentLoopDepth) {
355 // Make sure we have visited all blocks in this loop before moving back to
356 // the outer loop.
357
358 auto LoopI = I;
359 while (unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
360 LoopI++;
Changpeng Fang5f915462018-05-23 18:34:48 +0000361 if (getAdjustedLoop(cast<RegionNode>(*LoopI)) == CurrentLoop) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000362 --BlockCount;
363 Order.push_back(*LoopI);
364 }
365 }
366 }
367
Changpeng Fang5f915462018-05-23 18:34:48 +0000368 CurrentLoop = getAdjustedLoop(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000369 if (CurrentLoop)
370 LoopBlocks[CurrentLoop]--;
371
372 CurrentLoopDepth = LoopDepth;
373 Order.push_back(*I);
374 }
375
376 // This pass originally used a post-order traversal and then operated on
377 // the list in reverse. Now that we are using a reverse post-order traversal
378 // rather than re-working the whole pass to operate on the list in order,
379 // we just reverse the list and continue to operate on it in reverse.
380 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000381}
382
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000383/// Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000384void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000385 if (N->isSubRegion()) {
386 // Test for exit as back edge
387 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
388 if (Visited.count(Exit))
389 Loops[Exit] = N->getEntry();
390
391 } else {
Hiroshi Inoue713b5ba2017-07-09 05:54:44 +0000392 // Test for successors as back edge
Christian Konigfc6a9852013-02-16 11:27:45 +0000393 BasicBlock *BB = N->getNodeAs<BasicBlock>();
394 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
395
Pete Cooperebcd7482015-08-06 20:22:46 +0000396 for (BasicBlock *Succ : Term->successors())
397 if (Visited.count(Succ))
Christian Konigfc6a9852013-02-16 11:27:45 +0000398 Loops[Succ] = BB;
Christian Konigfc6a9852013-02-16 11:27:45 +0000399 }
400}
401
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000402/// Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000403Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000404 // First: Check if it's a constant
Matt Arsenault93be6e82016-07-15 22:13:16 +0000405 if (Constant *C = dyn_cast<Constant>(Condition))
406 return ConstantExpr::getNot(C);
Christian Konigd8860992013-02-16 11:27:50 +0000407
408 // Second: If the condition is already inverted, return the original value
Marek Olsak3c5fd142018-05-15 21:41:55 +0000409 Value *NotCondition;
410 if (match(Condition, m_Not(m_Value(NotCondition))))
411 return NotCondition;
Christian Konigd8860992013-02-16 11:27:50 +0000412
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000413 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
414 // Third: Check all the users for an invert
415 BasicBlock *Parent = Inst->getParent();
Matt Arsenault44746522017-04-24 20:25:01 +0000416 for (User *U : Condition->users())
417 if (Instruction *I = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000418 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
419 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000420
421 // Last option: Create a new instruction
422 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000423 }
424
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000425 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
426 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
427 return BinaryOperator::CreateNot(Condition,
428 Arg->getName() + ".inv",
429 EntryBlock.getTerminator());
430 }
431
432 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000433}
434
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000435/// Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000436Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
437 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000438 Value *Cond = Invert ? BoolFalse : BoolTrue;
439 if (Term->isConditional()) {
440 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000441
Aaron Ballman19978552013-06-04 01:03:03 +0000442 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000443 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000444 }
445 return Cond;
446}
447
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000448/// Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000449void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000450 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000451 BasicBlock *BB = N->getEntry();
452 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000453 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000454
Justin Lebar3aec10c2016-11-28 18:50:03 +0000455 for (BasicBlock *P : predecessors(BB)) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000456 // Ignore it if it's a branch from outside into our region entry
Justin Lebar3aec10c2016-11-28 18:50:03 +0000457 if (!ParentRegion->contains(P))
Tom Stellard048f14f2013-02-08 22:24:37 +0000458 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000459
Justin Lebar3aec10c2016-11-28 18:50:03 +0000460 Region *R = RI->getRegionFor(P);
Tom Stellard048f14f2013-02-08 22:24:37 +0000461 if (R == ParentRegion) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000462 // It's a top level block in our region
Justin Lebar3aec10c2016-11-28 18:50:03 +0000463 BranchInst *Term = cast<BranchInst>(P->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000464 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
465 BasicBlock *Succ = Term->getSuccessor(i);
466 if (Succ != BB)
467 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000468
Justin Lebar3aec10c2016-11-28 18:50:03 +0000469 if (Visited.count(P)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000470 // Normal forward edge
471 if (Term->isConditional()) {
472 // Try to treat it like an ELSE block
473 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000474 if (Visited.count(Other) && !Loops.count(Other) &&
Justin Lebar3aec10c2016-11-28 18:50:03 +0000475 !Pred.count(Other) && !Pred.count(P)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000476
Tom Stellard048f14f2013-02-08 22:24:37 +0000477 Pred[Other] = BoolFalse;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000478 Pred[P] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000479 continue;
480 }
481 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000482 Pred[P] = buildCondition(Term, i, false);
Tom Stellard048f14f2013-02-08 22:24:37 +0000483 } else {
484 // Back edge
Justin Lebar3aec10c2016-11-28 18:50:03 +0000485 LPred[P] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000486 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000487 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000488 } else {
Tom Stellard048f14f2013-02-08 22:24:37 +0000489 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000490 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000491 R = R->getParent();
492
493 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000494 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000495 continue;
496
497 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000498 if (Visited.count(Entry))
499 Pred[Entry] = BoolTrue;
500 else
501 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000502 }
503 }
504}
505
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000506/// Collect various loop and predicate infos
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000507void StructurizeCFG::collectInfos() {
508 // Reset predicate
509 Predicates.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000510
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000511 // and loop infos
512 Loops.clear();
513 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000514
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000515 // Reset the visited nodes
516 Visited.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000517
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000518 for (RegionNode *RN : reverse(Order)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000519 LLVM_DEBUG(dbgs() << "Visiting: "
520 << (RN->isSubRegion() ? "SubRegion with entry: " : "")
521 << RN->getEntry()->getName() << " Loop Depth: "
522 << LI->getLoopDepth(RN->getEntry()) << "\n");
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000523
524 // Analyze all the conditions leading to a node
525 gatherPredicates(RN);
526
527 // Remember that we've seen this node
528 Visited.insert(RN->getEntry());
529
530 // Find the last back edges
531 analyzeLoops(RN);
532 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000533}
534
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000535/// Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000536void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000537 BranchVector &Conds = Loops ? LoopConds : Conditions;
538 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000539 SSAUpdater PhiInserter;
540
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000541 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000542 assert(Term->isConditional());
543
Christian Konigfc6a9852013-02-16 11:27:45 +0000544 BasicBlock *Parent = Term->getParent();
545 BasicBlock *SuccTrue = Term->getSuccessor(0);
546 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000547
Christian Konigb5d88662013-02-16 11:27:40 +0000548 PhiInserter.Initialize(Boolean, "");
549 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000550 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000551
Christian Konigfc6a9852013-02-16 11:27:45 +0000552 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000553
554 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000555 Dominator.addBlock(Parent);
Christian Konigb5d88662013-02-16 11:27:40 +0000556
Craig Topperf40110f2014-04-25 05:29:35 +0000557 Value *ParentValue = nullptr;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000558 for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
559 BasicBlock *BB = BBAndPred.first;
560 Value *Pred = BBAndPred.second;
Tom Stellard048f14f2013-02-08 22:24:37 +0000561
Justin Lebar3aec10c2016-11-28 18:50:03 +0000562 if (BB == Parent) {
563 ParentValue = Pred;
Christian Konigb5d88662013-02-16 11:27:40 +0000564 break;
565 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000566 PhiInserter.AddAvailableValue(BB, Pred);
567 Dominator.addAndRememberBlock(BB);
Tom Stellard048f14f2013-02-08 22:24:37 +0000568 }
569
Christian Konigb5d88662013-02-16 11:27:40 +0000570 if (ParentValue) {
571 Term->setCondition(ParentValue);
572 } else {
Justin Lebar62c20d82016-11-28 18:49:59 +0000573 if (!Dominator.resultIsRememberedBlock())
574 PhiInserter.AddAvailableValue(Dominator.result(), Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000575
Tom Stellard048f14f2013-02-08 22:24:37 +0000576 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000577 }
Tom Stellardf8794352012-12-19 22:10:31 +0000578 }
579}
580
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000581/// Remove all PHI values coming from "From" into "To" and remember
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000582/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000583void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000584 PhiMap &Map = DeletedPhis[To];
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000585 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000586 while (Phi.getBasicBlockIndex(From) != -1) {
587 Value *Deleted = Phi.removeIncomingValue(From, false);
588 Map[&Phi].push_back(std::make_pair(From, Deleted));
589 }
590 }
591}
592
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000593/// Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000594void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000595 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000596 Value *Undef = UndefValue::get(Phi.getType());
597 Phi.addIncoming(Undef, From);
598 }
599 AddedPhis[To].push_back(From);
600}
601
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000602/// Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000603void StructurizeCFG::setPhiValues() {
Nicolai Haehnle08230502018-10-17 15:37:41 +0000604 SmallVector<PHINode *, 8> InsertedPhis;
605 SSAUpdater Updater(&InsertedPhis);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000606 for (const auto &AddedPhi : AddedPhis) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000607 BasicBlock *To = AddedPhi.first;
608 const BBVector &From = AddedPhi.second;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000609
610 if (!DeletedPhis.count(To))
611 continue;
612
613 PhiMap &Map = DeletedPhis[To];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000614 for (const auto &PI : Map) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000615 PHINode *Phi = PI.first;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000616 Value *Undef = UndefValue::get(Phi->getType());
617 Updater.Initialize(Phi->getType(), "");
618 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
619 Updater.AddAvailableValue(To, Undef);
620
Christian Konig0bccf9d2013-02-16 11:27:35 +0000621 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000622 Dominator.addBlock(To);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000623 for (const auto &VI : PI.second) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000624 Updater.AddAvailableValue(VI.first, VI.second);
Justin Lebar62c20d82016-11-28 18:49:59 +0000625 Dominator.addAndRememberBlock(VI.first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000626 }
627
Justin Lebar62c20d82016-11-28 18:49:59 +0000628 if (!Dominator.resultIsRememberedBlock())
629 Updater.AddAvailableValue(Dominator.result(), Undef);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000630
Whitney Tsang15b7f5b2019-06-17 14:38:56 +0000631 for (BasicBlock *FI : From)
632 Phi->setIncomingValueForBlock(FI, Updater.GetValueAtEndOfBlock(FI));
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000633 }
634
635 DeletedPhis.erase(To);
636 }
637 assert(DeletedPhis.empty());
Nicolai Haehnle08230502018-10-17 15:37:41 +0000638
639 // Simplify any phis inserted by the SSAUpdater if possible
640 bool Changed;
641 do {
642 Changed = false;
643
644 SimplifyQuery Q(Func->getParent()->getDataLayout());
645 Q.DT = DT;
646 for (size_t i = 0; i < InsertedPhis.size(); ++i) {
647 PHINode *Phi = InsertedPhis[i];
648 if (Value *V = SimplifyInstruction(Phi, Q)) {
649 Phi->replaceAllUsesWith(V);
650 Phi->eraseFromParent();
651 InsertedPhis[i] = InsertedPhis.back();
652 InsertedPhis.pop_back();
653 i--;
654 Changed = true;
655 }
656 }
657 } while (Changed);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000658}
659
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000660/// Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000661void StructurizeCFG::killTerminator(BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000662 Instruction *Term = BB->getTerminator();
Tom Stellardf8794352012-12-19 22:10:31 +0000663 if (!Term)
664 return;
665
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000666 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000667 SI != SE; ++SI)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000668 delPhiValues(BB, *SI);
Tom Stellardf8794352012-12-19 22:10:31 +0000669
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000670 if (DA)
671 DA->removeValue(Term);
Tom Stellardf8794352012-12-19 22:10:31 +0000672 Term->eraseFromParent();
673}
674
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000675/// Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000676void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
677 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000678 if (Node->isSubRegion()) {
679 Region *SubRegion = Node->getNodeAs<Region>();
680 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000681 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000682
Tom Stellard7370ede2013-02-08 22:24:38 +0000683 // Find all the edges from the sub region to the exit
Justin Lebar3aec10c2016-11-28 18:50:03 +0000684 for (auto BBI = pred_begin(OldExit), E = pred_end(OldExit); BBI != E;) {
685 // Incrememt BBI before mucking with BB's terminator.
686 BasicBlock *BB = *BBI++;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000687
Tom Stellard7370ede2013-02-08 22:24:38 +0000688 if (!SubRegion->contains(BB))
689 continue;
690
691 // Modify the edges to point to the new exit
692 delPhiValues(BB, OldExit);
693 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
694 addPhiValues(BB, NewExit);
695
696 // Find the new dominator (if requested)
697 if (IncludeDominator) {
698 if (!Dominator)
699 Dominator = BB;
700 else
701 Dominator = DT->findNearestCommonDominator(Dominator, BB);
702 }
Tom Stellardf8794352012-12-19 22:10:31 +0000703 }
704
Tom Stellard7370ede2013-02-08 22:24:38 +0000705 // Change the dominator (if requested)
706 if (Dominator)
707 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000708
Tom Stellard7370ede2013-02-08 22:24:38 +0000709 // Update the region info
710 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000711 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000712 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
713 killTerminator(BB);
714 BranchInst::Create(NewExit, BB);
715 addPhiValues(BB, NewExit);
716 if (IncludeDominator)
717 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000718 }
Tom Stellardf8794352012-12-19 22:10:31 +0000719}
720
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000721/// Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000722BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000723 LLVMContext &Context = Func->getContext();
724 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000725 Order.back()->getEntry();
Tom Stellardf8794352012-12-19 22:10:31 +0000726 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
727 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000728 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000729 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000730 return Flow;
731}
732
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000733/// Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000734BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000735 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000736
Christian Konigfc6a9852013-02-16 11:27:45 +0000737 if (!PrevNode->isSubRegion()) {
738 killTerminator(Entry);
739 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
740 return Entry;
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000741 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000742
Christian Konigfc6a9852013-02-16 11:27:45 +0000743 // create a new flow node
744 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000745
Christian Konigfc6a9852013-02-16 11:27:45 +0000746 // and wire it up
747 changeExit(PrevNode, Flow, true);
748 PrevNode = ParentRegion->getBBNode(Flow);
749 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000750}
751
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000752/// Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000753BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
754 bool ExitUseAllowed) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000755 if (!Order.empty() || !ExitUseAllowed)
756 return getNextFlow(Flow);
757
758 BasicBlock *Exit = ParentRegion->getExit();
759 DT->changeImmediateDominator(Exit, Flow);
760 addPhiValues(Flow, Exit);
761 return Exit;
Tom Stellard7370ede2013-02-08 22:24:38 +0000762}
763
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000764/// Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000765void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000766 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
767 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000768}
769
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000770/// Does BB dominate all the predicates of Node?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000771bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000772 BBPredicates &Preds = Predicates[Node->getEntry()];
Justin Lebar3aec10c2016-11-28 18:50:03 +0000773 return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
774 return DT->dominates(BB, Pred.first);
775 });
Tom Stellard7370ede2013-02-08 22:24:38 +0000776}
777
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000778/// Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000779bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000780 BBPredicates &Preds = Predicates[Node->getEntry()];
781 bool Dominated = false;
782
783 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000784 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000785 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000786
Justin Lebar3aec10c2016-11-28 18:50:03 +0000787 for (std::pair<BasicBlock*, Value*> Pred : Preds) {
788 BasicBlock *BB = Pred.first;
789 Value *V = Pred.second;
Tom Stellardf8794352012-12-19 22:10:31 +0000790
Justin Lebar3aec10c2016-11-28 18:50:03 +0000791 if (V != BoolTrue)
Tom Stellardf8794352012-12-19 22:10:31 +0000792 return false;
793
Justin Lebar3aec10c2016-11-28 18:50:03 +0000794 if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000795 Dominated = true;
796 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000797
798 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000799 return Dominated;
800}
801
Tom Stellard7370ede2013-02-08 22:24:38 +0000802/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000803void StructurizeCFG::wireFlow(bool ExitUseAllowed,
804 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000805 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000806 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000807
Christian Konigfc6a9852013-02-16 11:27:45 +0000808 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000809 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000810 if (PrevNode) {
811 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000812 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000813 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000814 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000815 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000816 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000817
Tom Stellard7370ede2013-02-08 22:24:38 +0000818 // Insert extra postfix node (or use exit instead)
819 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000820 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000821
822 // let it point to entry and next block
823 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
824 addPhiValues(Flow, Entry);
825 DT->changeImmediateDominator(Entry, Flow);
826
Christian Konigfc6a9852013-02-16 11:27:45 +0000827 PrevNode = Node;
828 while (!Order.empty() && !Visited.count(LoopEnd) &&
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000829 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000830 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000831 }
832
Christian Konigfc6a9852013-02-16 11:27:45 +0000833 changeExit(PrevNode, Next, false);
834 setPrevNode(Next);
835 }
836}
837
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000838void StructurizeCFG::handleLoops(bool ExitUseAllowed,
839 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000840 RegionNode *Node = Order.back();
Christian Konigfc6a9852013-02-16 11:27:45 +0000841 BasicBlock *LoopStart = Node->getEntry();
842
843 if (!Loops.count(LoopStart)) {
844 wireFlow(ExitUseAllowed, LoopEnd);
845 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000846 }
847
Christian Konigfc6a9852013-02-16 11:27:45 +0000848 if (!isPredictableTrue(Node))
849 LoopStart = needPrefix(true);
850
851 LoopEnd = Loops[Node->getEntry()];
852 wireFlow(false, LoopEnd);
853 while (!Visited.count(LoopEnd)) {
854 handleLoops(false, LoopEnd);
855 }
856
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000857 // If the start of the loop is the entry block, we can't branch to it so
858 // insert a new dummy entry block.
859 Function *LoopFunc = LoopStart->getParent();
860 if (LoopStart == &LoopFunc->getEntryBlock()) {
861 LoopStart->setName("entry.orig");
862
863 BasicBlock *NewEntry =
864 BasicBlock::Create(LoopStart->getContext(),
865 "entry",
866 LoopFunc,
867 LoopStart);
868 BranchInst::Create(LoopStart, NewEntry);
Serge Pavlov0668cd22017-01-10 02:50:47 +0000869 DT->setNewRoot(NewEntry);
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000870 }
871
Christian Konigfc6a9852013-02-16 11:27:45 +0000872 // Create an extra loop end node
873 LoopEnd = needPrefix(false);
874 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
875 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
876 BoolUndef, LoopEnd));
877 addPhiValues(LoopEnd, LoopStart);
878 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000879}
880
Tom Stellardf8794352012-12-19 22:10:31 +0000881/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000882/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000883void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000884 BasicBlock *Exit = ParentRegion->getExit();
885 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
886
Tom Stellardf8794352012-12-19 22:10:31 +0000887 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000888 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000889 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000890 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000891
Craig Topperf40110f2014-04-25 05:29:35 +0000892 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000893 Visited.clear();
894
Tom Stellardf8794352012-12-19 22:10:31 +0000895 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000896 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000897 }
898
Christian Konigfc6a9852013-02-16 11:27:45 +0000899 if (PrevNode)
900 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000901 else
902 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000903}
904
Tom Stellardf8794352012-12-19 22:10:31 +0000905/// Handle a rare case where the disintegrated nodes instructions
Hiroshi Inouef2096492018-06-14 05:41:49 +0000906/// no longer dominate all their uses. Not sure if this is really necessary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000907void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000908 SSAUpdater Updater;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000909 for (BasicBlock *BB : ParentRegion->blocks())
910 for (Instruction &I : *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000911 bool Initialized = false;
Justin Lebar96e29152016-11-29 21:49:02 +0000912 // We may modify the use list as we iterate over it, so be careful to
913 // compute the next element in the use list at the top of the loop.
914 for (auto UI = I.use_begin(), E = I.use_end(); UI != E;) {
915 Use &U = *UI++;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000916 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000917 if (User->getParent() == BB) {
918 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000919 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000920 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000921 continue;
922 }
923
Justin Lebar3aec10c2016-11-28 18:50:03 +0000924 if (DT->dominates(&I, User))
Tom Stellardf8794352012-12-19 22:10:31 +0000925 continue;
926
927 if (!Initialized) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000928 Value *Undef = UndefValue::get(I.getType());
929 Updater.Initialize(I.getType(), "");
Tom Stellardf8794352012-12-19 22:10:31 +0000930 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000931 Updater.AddAvailableValue(BB, &I);
Tom Stellardf8794352012-12-19 22:10:31 +0000932 Initialized = true;
933 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000934 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000935 }
936 }
Tom Stellardf8794352012-12-19 22:10:31 +0000937}
938
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000939static bool hasOnlyUniformBranches(Region *R, unsigned UniformMDKindID,
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000940 const LegacyDivergenceAnalysis &DA) {
Neil Henning119c31a2019-05-24 08:59:17 +0000941 // Bool for if all sub-regions are uniform.
942 bool SubRegionsAreUniform = true;
943 // Count of how many direct children are conditional.
944 unsigned ConditionalDirectChildren = 0;
945
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000946 for (auto E : R->elements()) {
947 if (!E->isSubRegion()) {
948 auto Br = dyn_cast<BranchInst>(E->getEntry()->getTerminator());
949 if (!Br || !Br->isConditional())
950 continue;
Tom Stellard755a4e62016-02-10 00:39:37 +0000951
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000952 if (!DA.isUniform(Br))
953 return false;
Neil Henning119c31a2019-05-24 08:59:17 +0000954
955 // One of our direct children is conditional.
956 ConditionalDirectChildren++;
957
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000958 LLVM_DEBUG(dbgs() << "BB: " << Br->getParent()->getName()
959 << " has uniform terminator\n");
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000960 } else {
961 // Explicitly refuse to treat regions as uniform if they have non-uniform
962 // subregions. We cannot rely on DivergenceAnalysis for branches in
963 // subregions because those branches may have been removed and re-created,
964 // so we look for our metadata instead.
965 //
966 // Warning: It would be nice to treat regions as uniform based only on
967 // their direct child basic blocks' terminators, regardless of whether
968 // subregions are uniform or not. However, this requires a very careful
969 // look at SIAnnotateControlFlow to make sure nothing breaks there.
970 for (auto BB : E->getNodeAs<Region>()->blocks()) {
971 auto Br = dyn_cast<BranchInst>(BB->getTerminator());
972 if (!Br || !Br->isConditional())
973 continue;
974
Neil Henning119c31a2019-05-24 08:59:17 +0000975 if (!Br->getMetadata(UniformMDKindID)) {
976 // Early exit if we cannot have relaxed uniform regions.
977 if (!RelaxedUniformRegions)
978 return false;
979
980 SubRegionsAreUniform = false;
981 break;
982 }
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000983 }
984 }
Tom Stellard755a4e62016-02-10 00:39:37 +0000985 }
Neil Henning119c31a2019-05-24 08:59:17 +0000986
987 // Our region is uniform if:
988 // 1. All conditional branches that are direct children are uniform (checked
989 // above).
990 // 2. And either:
991 // a. All sub-regions are uniform.
992 // b. There is one or less conditional branches among the direct children.
993 return SubRegionsAreUniform || (ConditionalDirectChildren <= 1);
Tom Stellard755a4e62016-02-10 00:39:37 +0000994}
995
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000996/// Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000997bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000998 if (R->isTopLevelRegion())
999 return false;
1000
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +00001001 DA = nullptr;
1002
Tom Stellard755a4e62016-02-10 00:39:37 +00001003 if (SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +00001004 // TODO: We could probably be smarter here with how we handle sub-regions.
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +00001005 // We currently rely on the fact that metadata is set by earlier invocations
1006 // of the pass on sub-regions, and that this metadata doesn't get lost --
1007 // but we shouldn't rely on metadata for correctness!
1008 unsigned UniformMDKindID =
1009 R->getEntry()->getContext().getMDKindID("structurizecfg.uniform");
Nicolai Haehnle35617ed2018-08-30 14:21:36 +00001010 DA = &getAnalysis<LegacyDivergenceAnalysis>();
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +00001011
1012 if (hasOnlyUniformBranches(R, UniformMDKindID, *DA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001013 LLVM_DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R
1014 << '\n');
Nicolai Haehnle05b127d2016-04-14 17:42:35 +00001015
1016 // Mark all direct child block terminators as having been treated as
1017 // uniform. To account for a possible future in which non-uniform
1018 // sub-regions are treated more cleverly, indirect children are not
1019 // marked as uniform.
1020 MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
Justin Lebar1b60d702016-11-22 23:13:37 +00001021 for (RegionNode *E : R->elements()) {
1022 if (E->isSubRegion())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +00001023 continue;
1024
Justin Lebar1b60d702016-11-22 23:13:37 +00001025 if (Instruction *Term = E->getEntry()->getTerminator())
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +00001026 Term->setMetadata(UniformMDKindID, MD);
Nicolai Haehnle05b127d2016-04-14 17:42:35 +00001027 }
1028
Tom Stellard755a4e62016-02-10 00:39:37 +00001029 return false;
1030 }
1031 }
1032
Tom Stellardf8794352012-12-19 22:10:31 +00001033 Func = R->getEntry()->getParent();
1034 ParentRegion = R;
1035
Chandler Carruth73523022014-01-13 13:07:17 +00001036 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +00001037 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +00001038
1039 orderNodes();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +00001040 collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +00001041 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +00001042 insertConditions(false);
1043 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +00001044 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +00001045 rebuildSSA();
1046
Tom Stellard048f14f2013-02-08 22:24:37 +00001047 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +00001048 Order.clear();
1049 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +00001050 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +00001051 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +00001052 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +00001053 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +00001054 Loops.clear();
1055 LoopPreds.clear();
1056 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +00001057
1058 return true;
1059}
1060
Tom Stellard755a4e62016-02-10 00:39:37 +00001061Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
1062 return new StructurizeCFG(SkipUniformRegions);
Tom Stellardf8794352012-12-19 22:10:31 +00001063}