LLVM  8.0.1
SIAnnotateControlFlow.cpp
Go to the documentation of this file.
1 //===- SIAnnotateControlFlow.cpp ------------------------------------------===//
2 //
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 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// Annotates the control flow with hardware specific intrinsics.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPU.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Analysis/LoopInfo.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/DerivedTypes.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/Debug.h"
41 #include <cassert>
42 #include <utility>
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "si-annotate-control-flow"
47 
48 namespace {
49 
50 // Complex types used in this pass
51 using StackEntry = std::pair<BasicBlock *, Value *>;
52 using StackVector = SmallVector<StackEntry, 16>;
53 
54 class SIAnnotateControlFlow : public FunctionPass {
56 
57  Type *Boolean;
58  Type *Void;
59  Type *Int64;
60  Type *ReturnStruct;
61 
62  ConstantInt *BoolTrue;
63  ConstantInt *BoolFalse;
64  UndefValue *BoolUndef;
65  Constant *Int64Zero;
66 
67  Function *If;
68  Function *Else;
69  Function *IfBreak;
70  Function *Loop;
71  Function *EndCf;
72 
73  DominatorTree *DT;
74  StackVector Stack;
75 
76  LoopInfo *LI;
77 
78  bool isUniform(BranchInst *T);
79 
80  bool isTopOfStack(BasicBlock *BB);
81 
82  Value *popSaved();
83 
84  void push(BasicBlock *BB, Value *Saved);
85 
86  bool isElse(PHINode *Phi);
87 
88  void eraseIfUnused(PHINode *Phi);
89 
90  void openIf(BranchInst *Term);
91 
92  void insertElse(BranchInst *Term);
93 
94  Value *
95  handleLoopCondition(Value *Cond, PHINode *Broken, llvm::Loop *L,
96  BranchInst *Term);
97 
98  void handleLoop(BranchInst *Term);
99 
100  void closeControlFlow(BasicBlock *BB);
101 
102 public:
103  static char ID;
104 
105  SIAnnotateControlFlow() : FunctionPass(ID) {}
106 
107  bool doInitialization(Module &M) override;
108 
109  bool runOnFunction(Function &F) override;
110 
111  StringRef getPassName() const override { return "SI annotate control flow"; }
112 
113  void getAnalysisUsage(AnalysisUsage &AU) const override {
119  }
120 };
121 
122 } // end anonymous namespace
123 
124 INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE,
125  "Annotate SI Control Flow", false, false)
128 INITIALIZE_PASS_END(SIAnnotateControlFlow, DEBUG_TYPE,
129  "Annotate SI Control Flow", false, false)
130 
131 char SIAnnotateControlFlow::ID = 0;
132 
133 /// Initialize all the types and constants used in the pass
134 bool SIAnnotateControlFlow::doInitialization(Module &M) {
135  LLVMContext &Context = M.getContext();
136 
137  Void = Type::getVoidTy(Context);
138  Boolean = Type::getInt1Ty(Context);
139  Int64 = Type::getInt64Ty(Context);
140  ReturnStruct = StructType::get(Boolean, Int64);
141 
142  BoolTrue = ConstantInt::getTrue(Context);
143  BoolFalse = ConstantInt::getFalse(Context);
144  BoolUndef = UndefValue::get(Boolean);
145  Int64Zero = ConstantInt::get(Int64, 0);
146 
152  return false;
153 }
154 
155 /// Is the branch condition uniform or did the StructurizeCFG pass
156 /// consider it as such?
157 bool SIAnnotateControlFlow::isUniform(BranchInst *T) {
158  return DA->isUniform(T) ||
159  T->getMetadata("structurizecfg.uniform") != nullptr;
160 }
161 
162 /// Is BB the last block saved on the stack ?
163 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
164  return !Stack.empty() && Stack.back().first == BB;
165 }
166 
167 /// Pop the last saved value from the control flow stack
168 Value *SIAnnotateControlFlow::popSaved() {
169  return Stack.pop_back_val().second;
170 }
171 
172 /// Push a BB and saved value to the control flow stack
173 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
174  Stack.push_back(std::make_pair(BB, Saved));
175 }
176 
177 /// Can the condition represented by this PHI node treated like
178 /// an "Else" block?
179 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
180  BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
181  for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
182  if (Phi->getIncomingBlock(i) == IDom) {
183 
184  if (Phi->getIncomingValue(i) != BoolTrue)
185  return false;
186 
187  } else {
188  if (Phi->getIncomingValue(i) != BoolFalse)
189  return false;
190 
191  }
192  }
193  return true;
194 }
195 
196 // Erase "Phi" if it is not used any more
197 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
198  if (RecursivelyDeleteDeadPHINode(Phi)) {
199  LLVM_DEBUG(dbgs() << "Erased unused condition phi\n");
200  }
201 }
202 
203 /// Open a new "If" block
204 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
205  if (isUniform(Term))
206  return;
207 
208  Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
209  Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
210  push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
211 }
212 
213 /// Close the last "If" block and open a new "Else" block
214 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
215  if (isUniform(Term)) {
216  return;
217  }
218  Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
219  Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
220  push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
221 }
222 
223 /// Recursively handle the condition leading to a loop
224 Value *SIAnnotateControlFlow::handleLoopCondition(
225  Value *Cond, PHINode *Broken, llvm::Loop *L, BranchInst *Term) {
226  if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
227  BasicBlock *Parent = Inst->getParent();
228  Instruction *Insert;
229  if (L->contains(Inst)) {
230  Insert = Parent->getTerminator();
231  } else {
232  Insert = L->getHeader()->getFirstNonPHIOrDbgOrLifetime();
233  }
234 
235  Value *Args[] = { Cond, Broken };
236  return CallInst::Create(IfBreak, Args, "", Insert);
237  }
238 
239  // Insert IfBreak in the loop header TERM for constant COND other than true.
240  if (isa<Constant>(Cond)) {
241  Instruction *Insert = Cond == BoolTrue ?
242  Term : L->getHeader()->getTerminator();
243 
244  Value *Args[] = { Cond, Broken };
245  return CallInst::Create(IfBreak, Args, "", Insert);
246  }
247 
248  llvm_unreachable("Unhandled loop condition!");
249 }
250 
251 /// Handle a back edge (loop)
252 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
253  if (isUniform(Term))
254  return;
255 
256  BasicBlock *BB = Term->getParent();
257  llvm::Loop *L = LI->getLoopFor(BB);
258  if (!L)
259  return;
260 
261  BasicBlock *Target = Term->getSuccessor(1);
262  PHINode *Broken = PHINode::Create(Int64, 0, "phi.broken", &Target->front());
263 
264  Value *Cond = Term->getCondition();
265  Term->setCondition(BoolTrue);
266  Value *Arg = handleLoopCondition(Cond, Broken, L, Term);
267 
268  for (BasicBlock *Pred : predecessors(Target))
269  Broken->addIncoming(Pred == BB ? Arg : Int64Zero, Pred);
270 
271  Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
272 
273  push(Term->getSuccessor(0), Arg);
274 }
275 
276 /// Close the last opened control flow
277 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
278  llvm::Loop *L = LI->getLoopFor(BB);
279 
280  assert(Stack.back().first == BB);
281 
282  if (L && L->getHeader() == BB) {
283  // We can't insert an EndCF call into a loop header, because it will
284  // get executed on every iteration of the loop, when it should be
285  // executed only once before the loop.
287  L->getLoopLatches(Latches);
288 
290  for (BasicBlock *Pred : predecessors(BB)) {
291  if (!is_contained(Latches, Pred))
292  Preds.push_back(Pred);
293  }
294 
295  BB = SplitBlockPredecessors(BB, Preds, "endcf.split", DT, LI, nullptr,
296  false);
297  }
298 
299  Value *Exec = popSaved();
300  Instruction *FirstInsertionPt = &*BB->getFirstInsertionPt();
301  if (!isa<UndefValue>(Exec) && !isa<UnreachableInst>(FirstInsertionPt))
302  CallInst::Create(EndCf, Exec, "", FirstInsertionPt);
303 }
304 
305 /// Annotate the control flow with intrinsics so the backend can
306 /// recognize if/then/else and loops.
308  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
309  LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
310  DA = &getAnalysis<LegacyDivergenceAnalysis>();
311 
313  E = df_end(&F.getEntryBlock()); I != E; ++I) {
314  BasicBlock *BB = *I;
316 
317  if (!Term || Term->isUnconditional()) {
318  if (isTopOfStack(BB))
319  closeControlFlow(BB);
320 
321  continue;
322  }
323 
324  if (I.nodeVisited(Term->getSuccessor(1))) {
325  if (isTopOfStack(BB))
326  closeControlFlow(BB);
327 
328  handleLoop(Term);
329  continue;
330  }
331 
332  if (isTopOfStack(BB)) {
333  PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
334  if (Phi && Phi->getParent() == BB && isElse(Phi)) {
335  insertElse(Term);
336  eraseIfUnused(Phi);
337  continue;
338  }
339 
340  closeControlFlow(BB);
341  }
342 
343  openIf(Term);
344  }
345 
346  if (!Stack.empty()) {
347  // CFG was probably not structured.
348  report_fatal_error("failed to annotate CFG");
349  }
350 
351  return true;
352 }
353 
354 /// Create the annotation pass
356  return new SIAnnotateControlFlow();
357 }
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:585
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:173
FunctionPass * createSIAnnotateControlFlowPass()
Create the annotation pass.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
LLVMContext & Context
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE, "Annotate SI Control Flow", false, false) INITIALIZE_PASS_END(SIAnnotateControlFlow
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
F(f)
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:138
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
&#39;undef&#39; values are things that do not have specified contents.
Definition: Constants.h:1286
void getLoopLatches(SmallVectorImpl< BlockT *> &LoopLatches) const
Return all loop latch blocks of this loop.
Definition: LoopInfo.h:304
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:342
BlockT * getHeader() const
Definition: LoopInfo.h:100
const Instruction * getFirstNonPHIOrDbgOrLifetime() const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic...
Definition: BasicBlock.cpp:204
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:92
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:221
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:145
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1020
const BasicBlock & getEntryBlock() const
Definition: Function.h:640
static bool runOnFunction(Function &F, bool PostInlining)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:217
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
Conditional or Unconditional Branch instruction.
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
df_iterator< T > df_end(const T &G)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
Definition: BasicBlock.h:281
unsigned char Boolean
Definition: ConvertUTF.h:113
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:161
Annotate SI Control Flow
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1415
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:110
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition: Local.cpp:513
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:622
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:125
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:578
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
df_iterator< T > df_begin(const T &G)
Target - Wrapper for Target specific information.
amdgpu Simplify well known AMD library false Value Value * Arg
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:465
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:107
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
bool isUnconditional() const
void setCondition(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
The legacy pass manager&#39;s analysis pass to compute loop information.
Definition: LoopInfo.h:970
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:260
#define LLVM_DEBUG(X)
Definition: Debug.h:123
#define DEBUG_TYPE
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
const BasicBlock * getParent() const
Definition: Instruction.h:67
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:1245