Home | History | Annotate | Line # | Download | only in AMDGPU
      1 //===- SIAnnotateControlFlow.cpp ------------------------------------------===//
      2 //
      3 // 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
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 /// \file
     10 /// Annotates the control flow with hardware specific intrinsics.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "AMDGPU.h"
     15 #include "GCNSubtarget.h"
     16 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
     17 #include "llvm/Analysis/LoopInfo.h"
     18 #include "llvm/CodeGen/TargetPassConfig.h"
     19 #include "llvm/IR/BasicBlock.h"
     20 #include "llvm/IR/Constants.h"
     21 #include "llvm/IR/Dominators.h"
     22 #include "llvm/IR/IntrinsicsAMDGPU.h"
     23 #include "llvm/InitializePasses.h"
     24 #include "llvm/Target/TargetMachine.h"
     25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
     26 #include "llvm/Transforms/Utils/Local.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 using StackEntry = std::pair<BasicBlock *, Value *>;
     36 using StackVector = SmallVector<StackEntry, 16>;
     37 
     38 class SIAnnotateControlFlow : public FunctionPass {
     39   LegacyDivergenceAnalysis *DA;
     40 
     41   Type *Boolean;
     42   Type *Void;
     43   Type *IntMask;
     44   Type *ReturnStruct;
     45 
     46   ConstantInt *BoolTrue;
     47   ConstantInt *BoolFalse;
     48   UndefValue *BoolUndef;
     49   Constant *IntMaskZero;
     50 
     51   Function *If;
     52   Function *Else;
     53   Function *IfBreak;
     54   Function *Loop;
     55   Function *EndCf;
     56 
     57   DominatorTree *DT;
     58   StackVector Stack;
     59 
     60   LoopInfo *LI;
     61 
     62   void initialize(Module &M, const GCNSubtarget &ST);
     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   bool hasKill(const BasicBlock *BB);
     75 
     76   void eraseIfUnused(PHINode *Phi);
     77 
     78   void openIf(BranchInst *Term);
     79 
     80   void insertElse(BranchInst *Term);
     81 
     82   Value *
     83   handleLoopCondition(Value *Cond, PHINode *Broken, llvm::Loop *L,
     84                       BranchInst *Term);
     85 
     86   void handleLoop(BranchInst *Term);
     87 
     88   void closeControlFlow(BasicBlock *BB);
     89 
     90 public:
     91   static char ID;
     92 
     93   SIAnnotateControlFlow() : FunctionPass(ID) {}
     94 
     95   bool runOnFunction(Function &F) override;
     96 
     97   StringRef getPassName() const override { return "SI annotate control flow"; }
     98 
     99   void getAnalysisUsage(AnalysisUsage &AU) const override {
    100     AU.addRequired<LoopInfoWrapperPass>();
    101     AU.addRequired<DominatorTreeWrapperPass>();
    102     AU.addRequired<LegacyDivergenceAnalysis>();
    103     AU.addPreserved<DominatorTreeWrapperPass>();
    104     AU.addRequired<TargetPassConfig>();
    105     FunctionPass::getAnalysisUsage(AU);
    106   }
    107 };
    108 
    109 } // end anonymous namespace
    110 
    111 INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE,
    112                       "Annotate SI Control Flow", false, false)
    113 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
    114 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
    115 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
    116 INITIALIZE_PASS_END(SIAnnotateControlFlow, DEBUG_TYPE,
    117                     "Annotate SI Control Flow", false, false)
    118 
    119 char SIAnnotateControlFlow::ID = 0;
    120 
    121 /// Initialize all the types and constants used in the pass
    122 void SIAnnotateControlFlow::initialize(Module &M, const GCNSubtarget &ST) {
    123   LLVMContext &Context = M.getContext();
    124 
    125   Void = Type::getVoidTy(Context);
    126   Boolean = Type::getInt1Ty(Context);
    127   IntMask = ST.isWave32() ? Type::getInt32Ty(Context)
    128                            : Type::getInt64Ty(Context);
    129   ReturnStruct = StructType::get(Boolean, IntMask);
    130 
    131   BoolTrue = ConstantInt::getTrue(Context);
    132   BoolFalse = ConstantInt::getFalse(Context);
    133   BoolUndef = UndefValue::get(Boolean);
    134   IntMaskZero = ConstantInt::get(IntMask, 0);
    135 
    136   If = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_if, { IntMask });
    137   Else = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_else,
    138                                    { IntMask, IntMask });
    139   IfBreak = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_if_break,
    140                                       { IntMask });
    141   Loop = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_loop, { IntMask });
    142   EndCf = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_end_cf, { IntMask });
    143 }
    144 
    145 /// Is the branch condition uniform or did the StructurizeCFG pass
    146 /// consider it as such?
    147 bool SIAnnotateControlFlow::isUniform(BranchInst *T) {
    148   return DA->isUniform(T) ||
    149          T->getMetadata("structurizecfg.uniform") != nullptr;
    150 }
    151 
    152 /// Is BB the last block saved on the stack ?
    153 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
    154   return !Stack.empty() && Stack.back().first == BB;
    155 }
    156 
    157 /// Pop the last saved value from the control flow stack
    158 Value *SIAnnotateControlFlow::popSaved() {
    159   return Stack.pop_back_val().second;
    160 }
    161 
    162 /// Push a BB and saved value to the control flow stack
    163 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
    164   Stack.push_back(std::make_pair(BB, Saved));
    165 }
    166 
    167 /// Can the condition represented by this PHI node treated like
    168 /// an "Else" block?
    169 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
    170   BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
    171   for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
    172     if (Phi->getIncomingBlock(i) == IDom) {
    173 
    174       if (Phi->getIncomingValue(i) != BoolTrue)
    175         return false;
    176 
    177     } else {
    178       if (Phi->getIncomingValue(i) != BoolFalse)
    179         return false;
    180 
    181     }
    182   }
    183   return true;
    184 }
    185 
    186 bool SIAnnotateControlFlow::hasKill(const BasicBlock *BB) {
    187   for (const Instruction &I : *BB) {
    188     if (const CallInst *CI = dyn_cast<CallInst>(&I))
    189       if (CI->getIntrinsicID() == Intrinsic::amdgcn_kill)
    190         return true;
    191   }
    192   return false;
    193 }
    194 
    195 // Erase "Phi" if it is not used any more
    196 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
    197   if (RecursivelyDeleteDeadPHINode(Phi)) {
    198     LLVM_DEBUG(dbgs() << "Erased unused condition phi\n");
    199   }
    200 }
    201 
    202 /// Open a new "If" block
    203 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
    204   if (isUniform(Term))
    205     return;
    206 
    207   Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
    208   Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
    209   push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
    210 }
    211 
    212 /// Close the last "If" block and open a new "Else" block
    213 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
    214   if (isUniform(Term)) {
    215     return;
    216   }
    217   Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
    218   Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
    219   push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
    220 }
    221 
    222 /// Recursively handle the condition leading to a loop
    223 Value *SIAnnotateControlFlow::handleLoopCondition(
    224     Value *Cond, PHINode *Broken, llvm::Loop *L, BranchInst *Term) {
    225   if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
    226     BasicBlock *Parent = Inst->getParent();
    227     Instruction *Insert;
    228     if (L->contains(Inst)) {
    229       Insert = Parent->getTerminator();
    230     } else {
    231       Insert = L->getHeader()->getFirstNonPHIOrDbgOrLifetime();
    232     }
    233 
    234     Value *Args[] = { Cond, Broken };
    235     return CallInst::Create(IfBreak, Args, "", Insert);
    236   }
    237 
    238   // Insert IfBreak in the loop header TERM for constant COND other than true.
    239   if (isa<Constant>(Cond)) {
    240     Instruction *Insert = Cond == BoolTrue ?
    241       Term : L->getHeader()->getTerminator();
    242 
    243     Value *Args[] = { Cond, Broken };
    244     return CallInst::Create(IfBreak, Args, "", Insert);
    245   }
    246 
    247   llvm_unreachable("Unhandled loop condition!");
    248 }
    249 
    250 /// Handle a back edge (loop)
    251 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
    252   if (isUniform(Term))
    253     return;
    254 
    255   BasicBlock *BB = Term->getParent();
    256   llvm::Loop *L = LI->getLoopFor(BB);
    257   if (!L)
    258     return;
    259 
    260   BasicBlock *Target = Term->getSuccessor(1);
    261   PHINode *Broken = PHINode::Create(IntMask, 0, "phi.broken", &Target->front());
    262 
    263   Value *Cond = Term->getCondition();
    264   Term->setCondition(BoolTrue);
    265   Value *Arg = handleLoopCondition(Cond, Broken, L, Term);
    266 
    267   for (BasicBlock *Pred : predecessors(Target)) {
    268     Value *PHIValue = IntMaskZero;
    269     if (Pred == BB) // Remember the value of the previous iteration.
    270       PHIValue = Arg;
    271     // If the backedge from Pred to Target could be executed before the exit
    272     // of the loop at BB, it should not reset or change "Broken", which keeps
    273     // track of the number of threads exited the loop at BB.
    274     else if (L->contains(Pred) && DT->dominates(Pred, BB))
    275       PHIValue = Broken;
    276     Broken->addIncoming(PHIValue, Pred);
    277   }
    278 
    279   Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
    280 
    281   push(Term->getSuccessor(0), Arg);
    282 }
    283 
    284 /// Close the last opened control flow
    285 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
    286   llvm::Loop *L = LI->getLoopFor(BB);
    287 
    288   assert(Stack.back().first == BB);
    289 
    290   if (L && L->getHeader() == BB) {
    291     // We can't insert an EndCF call into a loop header, because it will
    292     // get executed on every iteration of the loop, when it should be
    293     // executed only once before the loop.
    294     SmallVector <BasicBlock *, 8> Latches;
    295     L->getLoopLatches(Latches);
    296 
    297     SmallVector<BasicBlock *, 2> Preds;
    298     for (BasicBlock *Pred : predecessors(BB)) {
    299       if (!is_contained(Latches, Pred))
    300         Preds.push_back(Pred);
    301     }
    302 
    303     BB = SplitBlockPredecessors(BB, Preds, "endcf.split", DT, LI, nullptr,
    304                                 false);
    305   }
    306 
    307   Value *Exec = popSaved();
    308   Instruction *FirstInsertionPt = &*BB->getFirstInsertionPt();
    309   if (!isa<UndefValue>(Exec) && !isa<UnreachableInst>(FirstInsertionPt)) {
    310     Instruction *ExecDef = cast<Instruction>(Exec);
    311     BasicBlock *DefBB = ExecDef->getParent();
    312     if (!DT->dominates(DefBB, BB)) {
    313       // Split edge to make Def dominate Use
    314       FirstInsertionPt = &*SplitEdge(DefBB, BB, DT, LI)->getFirstInsertionPt();
    315     }
    316     CallInst::Create(EndCf, Exec, "", FirstInsertionPt);
    317   }
    318 }
    319 
    320 /// Annotate the control flow with intrinsics so the backend can
    321 /// recognize if/then/else and loops.
    322 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
    323   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
    324   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
    325   DA = &getAnalysis<LegacyDivergenceAnalysis>();
    326   TargetPassConfig &TPC = getAnalysis<TargetPassConfig>();
    327   const TargetMachine &TM = TPC.getTM<TargetMachine>();
    328 
    329   initialize(*F.getParent(), TM.getSubtarget<GCNSubtarget>(F));
    330   for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
    331        E = df_end(&F.getEntryBlock()); I != E; ++I) {
    332     BasicBlock *BB = *I;
    333     BranchInst *Term = dyn_cast<BranchInst>(BB->getTerminator());
    334 
    335     if (!Term || Term->isUnconditional()) {
    336       if (isTopOfStack(BB))
    337         closeControlFlow(BB);
    338 
    339       continue;
    340     }
    341 
    342     if (I.nodeVisited(Term->getSuccessor(1))) {
    343       if (isTopOfStack(BB))
    344         closeControlFlow(BB);
    345 
    346       if (DT->dominates(Term->getSuccessor(1), BB))
    347         handleLoop(Term);
    348       continue;
    349     }
    350 
    351     if (isTopOfStack(BB)) {
    352       PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
    353       if (Phi && Phi->getParent() == BB && isElse(Phi) && !hasKill(BB)) {
    354         insertElse(Term);
    355         eraseIfUnused(Phi);
    356         continue;
    357       }
    358 
    359       closeControlFlow(BB);
    360     }
    361 
    362     openIf(Term);
    363   }
    364 
    365   if (!Stack.empty()) {
    366     // CFG was probably not structured.
    367     report_fatal_error("failed to annotate CFG");
    368   }
    369 
    370   return true;
    371 }
    372 
    373 /// Create the annotation pass
    374 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
    375   return new SIAnnotateControlFlow();
    376 }
    377