LLVM  5.0.0
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"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Dominators.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Pass.h"
27 
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "si-annotate-control-flow"
31 
32 namespace {
33 
34 // Complex types used in this pass
35 typedef std::pair<BasicBlock *, Value *> StackEntry;
36 typedef SmallVector<StackEntry, 16> StackVector;
37 
38 class SIAnnotateControlFlow : public FunctionPass {
40 
41  Type *Boolean;
42  Type *Void;
43  Type *Int64;
44  Type *ReturnStruct;
45 
46  ConstantInt *BoolTrue;
47  ConstantInt *BoolFalse;
48  UndefValue *BoolUndef;
49  Constant *Int64Zero;
50 
51  Function *If;
52  Function *Else;
53  Function *Break;
54  Function *IfBreak;
55  Function *ElseBreak;
56  Function *Loop;
57  Function *EndCf;
58 
59  DominatorTree *DT;
60  StackVector Stack;
61 
62  LoopInfo *LI;
63 
64  bool isUniform(BranchInst *T);
65 
66  bool isTopOfStack(BasicBlock *BB);
67 
68  Value *popSaved();
69 
70  void push(BasicBlock *BB, Value *Saved);
71 
72  bool isElse(PHINode *Phi);
73 
74  void eraseIfUnused(PHINode *Phi);
75 
76  void openIf(BranchInst *Term);
77 
78  void insertElse(BranchInst *Term);
79 
80  Value *
81  handleLoopCondition(Value *Cond, PHINode *Broken, llvm::Loop *L,
82  BranchInst *Term,
83  SmallVectorImpl<WeakTrackingVH> &LoopPhiConditions);
84 
85  void handleLoop(BranchInst *Term);
86 
87  void closeControlFlow(BasicBlock *BB);
88 
89 public:
90  static char ID;
91 
92  SIAnnotateControlFlow():
93  FunctionPass(ID) { }
94 
95  bool doInitialization(Module &M) override;
96 
97  bool runOnFunction(Function &F) override;
98 
99  StringRef getPassName() const override { return "SI annotate control flow"; }
100 
101  void getAnalysisUsage(AnalysisUsage &AU) const override {
107  }
108 
109 };
110 
111 } // end anonymous namespace
112 
113 INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE,
114  "Annotate SI Control Flow", false, false)
117 INITIALIZE_PASS_END(SIAnnotateControlFlow, DEBUG_TYPE,
118  "Annotate SI Control Flow", false, false)
119 
120 char SIAnnotateControlFlow::ID = 0;
121 
122 /// \brief Initialize all the types and constants used in the pass
123 bool SIAnnotateControlFlow::doInitialization(Module &M) {
124  LLVMContext &Context = M.getContext();
125 
126  Void = Type::getVoidTy(Context);
127  Boolean = Type::getInt1Ty(Context);
128  Int64 = Type::getInt64Ty(Context);
129  ReturnStruct = StructType::get(Boolean, Int64);
130 
131  BoolTrue = ConstantInt::getTrue(Context);
132  BoolFalse = ConstantInt::getFalse(Context);
133  BoolUndef = UndefValue::get(Boolean);
134  Int64Zero = ConstantInt::get(Int64, 0);
135 
136  If = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_if);
137  Else = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_else);
138  Break = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_break);
139  IfBreak = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_if_break);
140  ElseBreak = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_else_break);
141  Loop = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_loop);
142  EndCf = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_end_cf);
143  return false;
144 }
145 
146 /// \brief Is the branch condition uniform or did the StructurizeCFG pass
147 /// consider it as such?
148 bool SIAnnotateControlFlow::isUniform(BranchInst *T) {
149  return DA->isUniform(T->getCondition()) ||
150  T->getMetadata("structurizecfg.uniform") != nullptr;
151 }
152 
153 /// \brief Is BB the last block saved on the stack ?
154 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
155  return !Stack.empty() && Stack.back().first == BB;
156 }
157 
158 /// \brief Pop the last saved value from the control flow stack
159 Value *SIAnnotateControlFlow::popSaved() {
160  return Stack.pop_back_val().second;
161 }
162 
163 /// \brief Push a BB and saved value to the control flow stack
164 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
165  Stack.push_back(std::make_pair(BB, Saved));
166 }
167 
168 /// \brief Can the condition represented by this PHI node treated like
169 /// an "Else" block?
170 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
171  BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
172  for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
173  if (Phi->getIncomingBlock(i) == IDom) {
174 
175  if (Phi->getIncomingValue(i) != BoolTrue)
176  return false;
177 
178  } else {
179  if (Phi->getIncomingValue(i) != BoolFalse)
180  return false;
181 
182  }
183  }
184  return true;
185 }
186 
187 // \brief Erase "Phi" if it is not used any more
188 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
190  DEBUG(dbgs() << "Erased unused condition phi\n");
191  }
192 }
193 
194 /// \brief Open a new "If" block
195 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
196  if (isUniform(Term))
197  return;
198 
199  Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
200  Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
201  push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
202 }
203 
204 /// \brief Close the last "If" block and open a new "Else" block
205 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
206  if (isUniform(Term)) {
207  return;
208  }
209  Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
210  Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
211  push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
212 }
213 
214 /// \brief Recursively handle the condition leading to a loop
215 Value *SIAnnotateControlFlow::handleLoopCondition(
216  Value *Cond, PHINode *Broken, llvm::Loop *L, BranchInst *Term,
217  SmallVectorImpl<WeakTrackingVH> &LoopPhiConditions) {
218 
219  // Only search through PHI nodes which are inside the loop. If we try this
220  // with PHI nodes that are outside of the loop, we end up inserting new PHI
221  // nodes outside of the loop which depend on values defined inside the loop.
222  // This will break the module with
223  // 'Instruction does not dominate all users!' errors.
224  PHINode *Phi = nullptr;
225  if ((Phi = dyn_cast<PHINode>(Cond)) && L->contains(Phi)) {
226 
227  BasicBlock *Parent = Phi->getParent();
228  PHINode *NewPhi = PHINode::Create(Int64, 0, "loop.phi", &Parent->front());
229  Value *Ret = NewPhi;
230 
231  // Handle all non-constant incoming values first
232  for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
233  Value *Incoming = Phi->getIncomingValue(i);
234  BasicBlock *From = Phi->getIncomingBlock(i);
235  if (isa<ConstantInt>(Incoming)) {
236  NewPhi->addIncoming(Broken, From);
237  continue;
238  }
239 
240  Phi->setIncomingValue(i, BoolFalse);
241  Value *PhiArg = handleLoopCondition(Incoming, Broken, L,
242  Term, LoopPhiConditions);
243  NewPhi->addIncoming(PhiArg, From);
244  }
245 
246  BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
247 
248  for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
249  Value *Incoming = Phi->getIncomingValue(i);
250  if (Incoming != BoolTrue)
251  continue;
252 
253  BasicBlock *From = Phi->getIncomingBlock(i);
254  if (From == IDom) {
255  // We're in the following situation:
256  // IDom/From
257  // | \
258  // | If-block
259  // | /
260  // Parent
261  // where we want to break out of the loop if the If-block is not taken.
262  // Due to the depth-first traversal, there should be an end.cf
263  // intrinsic in Parent, and we insert an else.break before it.
264  //
265  // Note that the end.cf need not be the first non-phi instruction
266  // of parent, particularly when we're dealing with a multi-level
267  // break, but it should occur within a group of intrinsic calls
268  // at the beginning of the block.
269  CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
270  while (OldEnd && OldEnd->getCalledFunction() != EndCf)
271  OldEnd = dyn_cast<CallInst>(OldEnd->getNextNode());
272  if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
273  Value *Args[] = { OldEnd->getArgOperand(0), NewPhi };
274  Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
275  continue;
276  }
277  }
278 
279  TerminatorInst *Insert = From->getTerminator();
280  Value *PhiArg = CallInst::Create(Break, Broken, "", Insert);
281  NewPhi->setIncomingValue(i, PhiArg);
282  }
283 
284  LoopPhiConditions.push_back(WeakTrackingVH(Phi));
285  return Ret;
286  }
287 
288  if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
289  BasicBlock *Parent = Inst->getParent();
290  Instruction *Insert;
291  if (L->contains(Inst)) {
292  Insert = Parent->getTerminator();
293  } else {
294  Insert = L->getHeader()->getFirstNonPHIOrDbgOrLifetime();
295  }
296 
297  Value *Args[] = { Cond, Broken };
298  return CallInst::Create(IfBreak, Args, "", Insert);
299  }
300 
301  // Insert IfBreak in the loop header TERM for constant COND other than true.
302  if (isa<Constant>(Cond)) {
303  Instruction *Insert = Cond == BoolTrue ?
304  Term : L->getHeader()->getTerminator();
305 
306  Value *Args[] = { Cond, Broken };
307  return CallInst::Create(IfBreak, Args, "", Insert);
308  }
309 
310  llvm_unreachable("Unhandled loop condition!");
311 }
312 
313 /// \brief Handle a back edge (loop)
314 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
315  if (isUniform(Term))
316  return;
317 
318  BasicBlock *BB = Term->getParent();
319  llvm::Loop *L = LI->getLoopFor(BB);
320  if (!L)
321  return;
322 
323  BasicBlock *Target = Term->getSuccessor(1);
324  PHINode *Broken = PHINode::Create(Int64, 0, "phi.broken", &Target->front());
325 
326  SmallVector<WeakTrackingVH, 8> LoopPhiConditions;
327  Value *Cond = Term->getCondition();
328  Term->setCondition(BoolTrue);
329  Value *Arg = handleLoopCondition(Cond, Broken, L, Term, LoopPhiConditions);
330 
331  for (BasicBlock *Pred : predecessors(Target))
332  Broken->addIncoming(Pred == BB ? Arg : Int64Zero, Pred);
333 
334  Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
335 
336  for (WeakTrackingVH Val : reverse(LoopPhiConditions)) {
337  if (PHINode *Cond = cast_or_null<PHINode>(Val))
338  eraseIfUnused(Cond);
339  }
340 
341  push(Term->getSuccessor(0), Arg);
342 }
343 
344 /// \brief Close the last opened control flow
345 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
346  llvm::Loop *L = LI->getLoopFor(BB);
347 
348  assert(Stack.back().first == BB);
349 
350  if (L && L->getHeader() == BB) {
351  // We can't insert an EndCF call into a loop header, because it will
352  // get executed on every iteration of the loop, when it should be
353  // executed only once before the loop.
355  L->getLoopLatches(Latches);
356 
358  for (BasicBlock *Pred : predecessors(BB)) {
359  if (!is_contained(Latches, Pred))
360  Preds.push_back(Pred);
361  }
362 
363  BB = llvm::SplitBlockPredecessors(BB, Preds, "endcf.split", DT, LI, false);
364  }
365 
366  Value *Exec = popSaved();
367  Instruction *FirstInsertionPt = &*BB->getFirstInsertionPt();
368  if (!isa<UndefValue>(Exec) && !isa<UnreachableInst>(FirstInsertionPt))
369  CallInst::Create(EndCf, Exec, "", FirstInsertionPt);
370 }
371 
372 /// \brief Annotate the control flow with intrinsics so the backend can
373 /// recognize if/then/else and loops.
374 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
375  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
376  LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
377  DA = &getAnalysis<DivergenceAnalysis>();
378 
380  E = df_end(&F.getEntryBlock()); I != E; ++I) {
381  BasicBlock *BB = *I;
383 
384  if (!Term || Term->isUnconditional()) {
385  if (isTopOfStack(BB))
386  closeControlFlow(BB);
387 
388  continue;
389  }
390 
391  if (I.nodeVisited(Term->getSuccessor(1))) {
392  if (isTopOfStack(BB))
393  closeControlFlow(BB);
394 
395  handleLoop(Term);
396  continue;
397  }
398 
399  if (isTopOfStack(BB)) {
400  PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
401  if (Phi && Phi->getParent() == BB && isElse(Phi)) {
402  insertElse(Term);
403  eraseIfUnused(Phi);
404  continue;
405  }
406 
407  closeControlFlow(BB);
408  }
409 
410  openIf(Term);
411  }
412 
413  assert(Stack.empty());
414  return true;
415 }
416 
417 /// \brief Create the annotation pass
419  return new SIAnnotateControlFlow();
420 }
MachineLoop * L
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:523
Annotate SI Control false
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
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
void getLoopLatches(SmallVectorImpl< BlockT * > &LoopLatches) const
Return all loop latch blocks of this loop.
Definition: LoopInfo.h:245
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
Maximum length of the test input If
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:84
This class represents a function call, abstracting a target machine's calling convention.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
const Instruction & front() const
Definition: BasicBlock.h:264
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
BlockT * getHeader() const
Definition: LoopInfo.h:103
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
bool isUnconditional() const
'undef' values are things that do not have specified contents.
Definition: Constants.h:1247
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:250
#define F(x, y, z)
Definition: MD5.cpp:55
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:182
BasicBlock * getSuccessor(unsigned i) const
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:975
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:134
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:54
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
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:68
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)
This is an important base class in LLVM.
Definition: Constant.h:42
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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:200
unsigned char Boolean
Definition: ConvertUTF.h:112
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:161
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Annotate SI Control Flow
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:110
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1320
#define E
Definition: LargeTest.cpp:27
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
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:336
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:190
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:427
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:560
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
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:110
const BasicBlock & getEntryBlock() const
Definition: Function.h:564
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:516
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
df_iterator< T > df_begin(const T &G)
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Target - Wrapper for Target specific information.
llvm_unreachable("Unknown RegBank!")
Value * getCondition() const
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:360
#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
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
void setCondition(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
#define DEBUG(X)
Definition: Debug.h:118
The legacy pass manager's analysis pass to compute loop information.
Definition: LoopInfo.h:845
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:261
const TerminatorInst * 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:120
void setIncomingValue(unsigned i, Value *V)
INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE,"Annotate SI Control Flow", false, false) INITIALIZE_PASS_END(SIAnnotateControlFlow
#define DEBUG_TYPE
const BasicBlock * getParent() const
Definition: Instruction.h:66
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:872