LLVM API Documentation

EarlyIfConversion.cpp
Go to the documentation of this file.
00001 //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Early if-conversion is for out-of-order CPUs that don't have a lot of
00011 // predicable instructions. The goal is to eliminate conditional branches that
00012 // may mispredict.
00013 //
00014 // Instructions from both sides of the branch are executed specutatively, and a
00015 // cmov instruction selects the result.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/ADT/BitVector.h"
00020 #include "llvm/ADT/PostOrderIterator.h"
00021 #include "llvm/ADT/SetVector.h"
00022 #include "llvm/ADT/SmallPtrSet.h"
00023 #include "llvm/ADT/SparseSet.h"
00024 #include "llvm/ADT/Statistic.h"
00025 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
00026 #include "llvm/CodeGen/MachineDominators.h"
00027 #include "llvm/CodeGen/MachineFunction.h"
00028 #include "llvm/CodeGen/MachineFunctionPass.h"
00029 #include "llvm/CodeGen/MachineLoopInfo.h"
00030 #include "llvm/CodeGen/MachineRegisterInfo.h"
00031 #include "llvm/CodeGen/MachineTraceMetrics.h"
00032 #include "llvm/CodeGen/Passes.h"
00033 #include "llvm/Support/CommandLine.h"
00034 #include "llvm/Support/Debug.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetInstrInfo.h"
00037 #include "llvm/Target/TargetRegisterInfo.h"
00038 #include "llvm/Target/TargetSubtargetInfo.h"
00039 
00040 using namespace llvm;
00041 
00042 #define DEBUG_TYPE "early-ifcvt"
00043 
00044 // Absolute maximum number of instructions allowed per speculated block.
00045 // This bypasses all other heuristics, so it should be set fairly high.
00046 static cl::opt<unsigned>
00047 BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
00048   cl::desc("Maximum number of instructions per speculated block."));
00049 
00050 // Stress testing mode - disable heuristics.
00051 static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
00052   cl::desc("Turn all knobs to 11"));
00053 
00054 STATISTIC(NumDiamondsSeen,  "Number of diamonds");
00055 STATISTIC(NumDiamondsConv,  "Number of diamonds converted");
00056 STATISTIC(NumTrianglesSeen, "Number of triangles");
00057 STATISTIC(NumTrianglesConv, "Number of triangles converted");
00058 
00059 //===----------------------------------------------------------------------===//
00060 //                                 SSAIfConv
00061 //===----------------------------------------------------------------------===//
00062 //
00063 // The SSAIfConv class performs if-conversion on SSA form machine code after
00064 // determining if it is possible. The class contains no heuristics; external
00065 // code should be used to determine when if-conversion is a good idea.
00066 //
00067 // SSAIfConv can convert both triangles and diamonds:
00068 //
00069 //   Triangle: Head              Diamond: Head
00070 //              | \                       /  \_
00071 //              |  \                     /    |
00072 //              |  [TF]BB              FBB    TBB
00073 //              |  /                     \    /
00074 //              | /                       \  /
00075 //             Tail                       Tail
00076 //
00077 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
00078 // Head block, and phis in the Tail block are converted to select instructions.
00079 //
00080 namespace {
00081 class SSAIfConv {
00082   const TargetInstrInfo *TII;
00083   const TargetRegisterInfo *TRI;
00084   MachineRegisterInfo *MRI;
00085 
00086 public:
00087   /// The block containing the conditional branch.
00088   MachineBasicBlock *Head;
00089 
00090   /// The block containing phis after the if-then-else.
00091   MachineBasicBlock *Tail;
00092 
00093   /// The 'true' conditional block as determined by AnalyzeBranch.
00094   MachineBasicBlock *TBB;
00095 
00096   /// The 'false' conditional block as determined by AnalyzeBranch.
00097   MachineBasicBlock *FBB;
00098 
00099   /// isTriangle - When there is no 'else' block, either TBB or FBB will be
00100   /// equal to Tail.
00101   bool isTriangle() const { return TBB == Tail || FBB == Tail; }
00102 
00103   /// Returns the Tail predecessor for the True side.
00104   MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
00105 
00106   /// Returns the Tail predecessor for the  False side.
00107   MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
00108 
00109   /// Information about each phi in the Tail block.
00110   struct PHIInfo {
00111     MachineInstr *PHI;
00112     unsigned TReg, FReg;
00113     // Latencies from Cond+Branch, TReg, and FReg to DstReg.
00114     int CondCycles, TCycles, FCycles;
00115 
00116     PHIInfo(MachineInstr *phi)
00117       : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
00118   };
00119 
00120   SmallVector<PHIInfo, 8> PHIs;
00121 
00122 private:
00123   /// The branch condition determined by AnalyzeBranch.
00124   SmallVector<MachineOperand, 4> Cond;
00125 
00126   /// Instructions in Head that define values used by the conditional blocks.
00127   /// The hoisted instructions must be inserted after these instructions.
00128   SmallPtrSet<MachineInstr*, 8> InsertAfter;
00129 
00130   /// Register units clobbered by the conditional blocks.
00131   BitVector ClobberedRegUnits;
00132 
00133   // Scratch pad for findInsertionPoint.
00134   SparseSet<unsigned> LiveRegUnits;
00135 
00136   /// Insertion point in Head for speculatively executed instructions form TBB
00137   /// and FBB.
00138   MachineBasicBlock::iterator InsertionPoint;
00139 
00140   /// Return true if all non-terminator instructions in MBB can be safely
00141   /// speculated.
00142   bool canSpeculateInstrs(MachineBasicBlock *MBB);
00143 
00144   /// Find a valid insertion point in Head.
00145   bool findInsertionPoint();
00146 
00147   /// Replace PHI instructions in Tail with selects.
00148   void replacePHIInstrs();
00149 
00150   /// Insert selects and rewrite PHI operands to use them.
00151   void rewritePHIOperands();
00152 
00153 public:
00154   /// runOnMachineFunction - Initialize per-function data structures.
00155   void runOnMachineFunction(MachineFunction &MF) {
00156     TII = MF.getSubtarget().getInstrInfo();
00157     TRI = MF.getSubtarget().getRegisterInfo();
00158     MRI = &MF.getRegInfo();
00159     LiveRegUnits.clear();
00160     LiveRegUnits.setUniverse(TRI->getNumRegUnits());
00161     ClobberedRegUnits.clear();
00162     ClobberedRegUnits.resize(TRI->getNumRegUnits());
00163   }
00164 
00165   /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
00166   /// initialize the internal state, and return true.
00167   bool canConvertIf(MachineBasicBlock *MBB);
00168 
00169   /// convertIf - If-convert the last block passed to canConvertIf(), assuming
00170   /// it is possible. Add any erased blocks to RemovedBlocks.
00171   void convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks);
00172 };
00173 } // end anonymous namespace
00174 
00175 
00176 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
00177 /// be speculated. The terminators are not considered.
00178 ///
00179 /// If instructions use any values that are defined in the head basic block,
00180 /// the defining instructions are added to InsertAfter.
00181 ///
00182 /// Any clobbered regunits are added to ClobberedRegUnits.
00183 ///
00184 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
00185   // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
00186   // get right.
00187   if (!MBB->livein_empty()) {
00188     DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
00189     return false;
00190   }
00191 
00192   unsigned InstrCount = 0;
00193 
00194   // Check all instructions, except the terminators. It is assumed that
00195   // terminators never have side effects or define any used register values.
00196   for (MachineBasicBlock::iterator I = MBB->begin(),
00197        E = MBB->getFirstTerminator(); I != E; ++I) {
00198     if (I->isDebugValue())
00199       continue;
00200 
00201     if (++InstrCount > BlockInstrLimit && !Stress) {
00202       DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
00203                    << BlockInstrLimit << " instructions.\n");
00204       return false;
00205     }
00206 
00207     // There shouldn't normally be any phis in a single-predecessor block.
00208     if (I->isPHI()) {
00209       DEBUG(dbgs() << "Can't hoist: " << *I);
00210       return false;
00211     }
00212 
00213     // Don't speculate loads. Note that it may be possible and desirable to
00214     // speculate GOT or constant pool loads that are guaranteed not to trap,
00215     // but we don't support that for now.
00216     if (I->mayLoad()) {
00217       DEBUG(dbgs() << "Won't speculate load: " << *I);
00218       return false;
00219     }
00220 
00221     // We never speculate stores, so an AA pointer isn't necessary.
00222     bool DontMoveAcrossStore = true;
00223     if (!I->isSafeToMove(TII, nullptr, DontMoveAcrossStore)) {
00224       DEBUG(dbgs() << "Can't speculate: " << *I);
00225       return false;
00226     }
00227 
00228     // Check for any dependencies on Head instructions.
00229     for (MIOperands MO(I); MO.isValid(); ++MO) {
00230       if (MO->isRegMask()) {
00231         DEBUG(dbgs() << "Won't speculate regmask: " << *I);
00232         return false;
00233       }
00234       if (!MO->isReg())
00235         continue;
00236       unsigned Reg = MO->getReg();
00237 
00238       // Remember clobbered regunits.
00239       if (MO->isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
00240         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
00241           ClobberedRegUnits.set(*Units);
00242 
00243       if (!MO->readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
00244         continue;
00245       MachineInstr *DefMI = MRI->getVRegDef(Reg);
00246       if (!DefMI || DefMI->getParent() != Head)
00247         continue;
00248       if (InsertAfter.insert(DefMI))
00249         DEBUG(dbgs() << "BB#" << MBB->getNumber() << " depends on " << *DefMI);
00250       if (DefMI->isTerminator()) {
00251         DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
00252         return false;
00253       }
00254     }
00255   }
00256   return true;
00257 }
00258 
00259 
00260 /// Find an insertion point in Head for the speculated instructions. The
00261 /// insertion point must be:
00262 ///
00263 /// 1. Before any terminators.
00264 /// 2. After any instructions in InsertAfter.
00265 /// 3. Not have any clobbered regunits live.
00266 ///
00267 /// This function sets InsertionPoint and returns true when successful, it
00268 /// returns false if no valid insertion point could be found.
00269 ///
00270 bool SSAIfConv::findInsertionPoint() {
00271   // Keep track of live regunits before the current position.
00272   // Only track RegUnits that are also in ClobberedRegUnits.
00273   LiveRegUnits.clear();
00274   SmallVector<unsigned, 8> Reads;
00275   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
00276   MachineBasicBlock::iterator I = Head->end();
00277   MachineBasicBlock::iterator B = Head->begin();
00278   while (I != B) {
00279     --I;
00280     // Some of the conditional code depends in I.
00281     if (InsertAfter.count(I)) {
00282       DEBUG(dbgs() << "Can't insert code after " << *I);
00283       return false;
00284     }
00285 
00286     // Update live regunits.
00287     for (MIOperands MO(I); MO.isValid(); ++MO) {
00288       // We're ignoring regmask operands. That is conservatively correct.
00289       if (!MO->isReg())
00290         continue;
00291       unsigned Reg = MO->getReg();
00292       if (!TargetRegisterInfo::isPhysicalRegister(Reg))
00293         continue;
00294       // I clobbers Reg, so it isn't live before I.
00295       if (MO->isDef())
00296         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
00297           LiveRegUnits.erase(*Units);
00298       // Unless I reads Reg.
00299       if (MO->readsReg())
00300         Reads.push_back(Reg);
00301     }
00302     // Anything read by I is live before I.
00303     while (!Reads.empty())
00304       for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
00305            ++Units)
00306         if (ClobberedRegUnits.test(*Units))
00307           LiveRegUnits.insert(*Units);
00308 
00309     // We can't insert before a terminator.
00310     if (I != FirstTerm && I->isTerminator())
00311       continue;
00312 
00313     // Some of the clobbered registers are live before I, not a valid insertion
00314     // point.
00315     if (!LiveRegUnits.empty()) {
00316       DEBUG({
00317         dbgs() << "Would clobber";
00318         for (SparseSet<unsigned>::const_iterator
00319              i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
00320           dbgs() << ' ' << PrintRegUnit(*i, TRI);
00321         dbgs() << " live before " << *I;
00322       });
00323       continue;
00324     }
00325 
00326     // This is a valid insertion point.
00327     InsertionPoint = I;
00328     DEBUG(dbgs() << "Can insert before " << *I);
00329     return true;
00330   }
00331   DEBUG(dbgs() << "No legal insertion point found.\n");
00332   return false;
00333 }
00334 
00335 
00336 
00337 /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
00338 /// a potential candidate for if-conversion. Fill out the internal state.
00339 ///
00340 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
00341   Head = MBB;
00342   TBB = FBB = Tail = nullptr;
00343 
00344   if (Head->succ_size() != 2)
00345     return false;
00346   MachineBasicBlock *Succ0 = Head->succ_begin()[0];
00347   MachineBasicBlock *Succ1 = Head->succ_begin()[1];
00348 
00349   // Canonicalize so Succ0 has MBB as its single predecessor.
00350   if (Succ0->pred_size() != 1)
00351     std::swap(Succ0, Succ1);
00352 
00353   if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
00354     return false;
00355 
00356   Tail = Succ0->succ_begin()[0];
00357 
00358   // This is not a triangle.
00359   if (Tail != Succ1) {
00360     // Check for a diamond. We won't deal with any critical edges.
00361     if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
00362         Succ1->succ_begin()[0] != Tail)
00363       return false;
00364     DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
00365                  << " -> BB#" << Succ0->getNumber()
00366                  << "/BB#" << Succ1->getNumber()
00367                  << " -> BB#" << Tail->getNumber() << '\n');
00368 
00369     // Live-in physregs are tricky to get right when speculating code.
00370     if (!Tail->livein_empty()) {
00371       DEBUG(dbgs() << "Tail has live-ins.\n");
00372       return false;
00373     }
00374   } else {
00375     DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
00376                  << " -> BB#" << Succ0->getNumber()
00377                  << " -> BB#" << Tail->getNumber() << '\n');
00378   }
00379 
00380   // This is a triangle or a diamond.
00381   // If Tail doesn't have any phis, there must be side effects.
00382   if (Tail->empty() || !Tail->front().isPHI()) {
00383     DEBUG(dbgs() << "No phis in tail.\n");
00384     return false;
00385   }
00386 
00387   // The branch we're looking to eliminate must be analyzable.
00388   Cond.clear();
00389   if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
00390     DEBUG(dbgs() << "Branch not analyzable.\n");
00391     return false;
00392   }
00393 
00394   // This is weird, probably some sort of degenerate CFG.
00395   if (!TBB) {
00396     DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
00397     return false;
00398   }
00399 
00400   // AnalyzeBranch doesn't set FBB on a fall-through branch.
00401   // Make sure it is always set.
00402   FBB = TBB == Succ0 ? Succ1 : Succ0;
00403 
00404   // Any phis in the tail block must be convertible to selects.
00405   PHIs.clear();
00406   MachineBasicBlock *TPred = getTPred();
00407   MachineBasicBlock *FPred = getFPred();
00408   for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
00409        I != E && I->isPHI(); ++I) {
00410     PHIs.push_back(&*I);
00411     PHIInfo &PI = PHIs.back();
00412     // Find PHI operands corresponding to TPred and FPred.
00413     for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
00414       if (PI.PHI->getOperand(i+1).getMBB() == TPred)
00415         PI.TReg = PI.PHI->getOperand(i).getReg();
00416       if (PI.PHI->getOperand(i+1).getMBB() == FPred)
00417         PI.FReg = PI.PHI->getOperand(i).getReg();
00418     }
00419     assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
00420     assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
00421 
00422     // Get target information.
00423     if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
00424                               PI.CondCycles, PI.TCycles, PI.FCycles)) {
00425       DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
00426       return false;
00427     }
00428   }
00429 
00430   // Check that the conditional instructions can be speculated.
00431   InsertAfter.clear();
00432   ClobberedRegUnits.reset();
00433   if (TBB != Tail && !canSpeculateInstrs(TBB))
00434     return false;
00435   if (FBB != Tail && !canSpeculateInstrs(FBB))
00436     return false;
00437 
00438   // Try to find a valid insertion point for the speculated instructions in the
00439   // head basic block.
00440   if (!findInsertionPoint())
00441     return false;
00442 
00443   if (isTriangle())
00444     ++NumTrianglesSeen;
00445   else
00446     ++NumDiamondsSeen;
00447   return true;
00448 }
00449 
00450 /// replacePHIInstrs - Completely replace PHI instructions with selects.
00451 /// This is possible when the only Tail predecessors are the if-converted
00452 /// blocks.
00453 void SSAIfConv::replacePHIInstrs() {
00454   assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
00455   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
00456   assert(FirstTerm != Head->end() && "No terminators");
00457   DebugLoc HeadDL = FirstTerm->getDebugLoc();
00458 
00459   // Convert all PHIs to select instructions inserted before FirstTerm.
00460   for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
00461     PHIInfo &PI = PHIs[i];
00462     DEBUG(dbgs() << "If-converting " << *PI.PHI);
00463     unsigned DstReg = PI.PHI->getOperand(0).getReg();
00464     TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
00465     DEBUG(dbgs() << "          --> " << *std::prev(FirstTerm));
00466     PI.PHI->eraseFromParent();
00467     PI.PHI = nullptr;
00468   }
00469 }
00470 
00471 /// rewritePHIOperands - When there are additional Tail predecessors, insert
00472 /// select instructions in Head and rewrite PHI operands to use the selects.
00473 /// Keep the PHI instructions in Tail to handle the other predecessors.
00474 void SSAIfConv::rewritePHIOperands() {
00475   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
00476   assert(FirstTerm != Head->end() && "No terminators");
00477   DebugLoc HeadDL = FirstTerm->getDebugLoc();
00478 
00479   // Convert all PHIs to select instructions inserted before FirstTerm.
00480   for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
00481     PHIInfo &PI = PHIs[i];
00482     DEBUG(dbgs() << "If-converting " << *PI.PHI);
00483     unsigned PHIDst = PI.PHI->getOperand(0).getReg();
00484     unsigned DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
00485     TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
00486     DEBUG(dbgs() << "          --> " << *std::prev(FirstTerm));
00487 
00488     // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
00489     for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
00490       MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
00491       if (MBB == getTPred()) {
00492         PI.PHI->getOperand(i-1).setMBB(Head);
00493         PI.PHI->getOperand(i-2).setReg(DstReg);
00494       } else if (MBB == getFPred()) {
00495         PI.PHI->RemoveOperand(i-1);
00496         PI.PHI->RemoveOperand(i-2);
00497       }
00498     }
00499     DEBUG(dbgs() << "          --> " << *PI.PHI);
00500   }
00501 }
00502 
00503 /// convertIf - Execute the if conversion after canConvertIf has determined the
00504 /// feasibility.
00505 ///
00506 /// Any basic blocks erased will be added to RemovedBlocks.
00507 ///
00508 void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
00509   assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
00510 
00511   // Update statistics.
00512   if (isTriangle())
00513     ++NumTrianglesConv;
00514   else
00515     ++NumDiamondsConv;
00516 
00517   // Move all instructions into Head, except for the terminators.
00518   if (TBB != Tail)
00519     Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
00520   if (FBB != Tail)
00521     Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
00522 
00523   // Are there extra Tail predecessors?
00524   bool ExtraPreds = Tail->pred_size() != 2;
00525   if (ExtraPreds)
00526     rewritePHIOperands();
00527   else
00528     replacePHIInstrs();
00529 
00530   // Fix up the CFG, temporarily leave Head without any successors.
00531   Head->removeSuccessor(TBB);
00532   Head->removeSuccessor(FBB);
00533   if (TBB != Tail)
00534     TBB->removeSuccessor(Tail);
00535   if (FBB != Tail)
00536     FBB->removeSuccessor(Tail);
00537 
00538   // Fix up Head's terminators.
00539   // It should become a single branch or a fallthrough.
00540   DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
00541   TII->RemoveBranch(*Head);
00542 
00543   // Erase the now empty conditional blocks. It is likely that Head can fall
00544   // through to Tail, and we can join the two blocks.
00545   if (TBB != Tail) {
00546     RemovedBlocks.push_back(TBB);
00547     TBB->eraseFromParent();
00548   }
00549   if (FBB != Tail) {
00550     RemovedBlocks.push_back(FBB);
00551     FBB->eraseFromParent();
00552   }
00553 
00554   assert(Head->succ_empty() && "Additional head successors?");
00555   if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
00556     // Splice Tail onto the end of Head.
00557     DEBUG(dbgs() << "Joining tail BB#" << Tail->getNumber()
00558                  << " into head BB#" << Head->getNumber() << '\n');
00559     Head->splice(Head->end(), Tail,
00560                      Tail->begin(), Tail->end());
00561     Head->transferSuccessorsAndUpdatePHIs(Tail);
00562     RemovedBlocks.push_back(Tail);
00563     Tail->eraseFromParent();
00564   } else {
00565     // We need a branch to Tail, let code placement work it out later.
00566     DEBUG(dbgs() << "Converting to unconditional branch.\n");
00567     SmallVector<MachineOperand, 0> EmptyCond;
00568     TII->InsertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
00569     Head->addSuccessor(Tail);
00570   }
00571   DEBUG(dbgs() << *Head);
00572 }
00573 
00574 
00575 //===----------------------------------------------------------------------===//
00576 //                           EarlyIfConverter Pass
00577 //===----------------------------------------------------------------------===//
00578 
00579 namespace {
00580 class EarlyIfConverter : public MachineFunctionPass {
00581   const TargetInstrInfo *TII;
00582   const TargetRegisterInfo *TRI;
00583   MCSchedModel SchedModel;
00584   MachineRegisterInfo *MRI;
00585   MachineDominatorTree *DomTree;
00586   MachineLoopInfo *Loops;
00587   MachineTraceMetrics *Traces;
00588   MachineTraceMetrics::Ensemble *MinInstr;
00589   SSAIfConv IfConv;
00590 
00591 public:
00592   static char ID;
00593   EarlyIfConverter() : MachineFunctionPass(ID) {}
00594   void getAnalysisUsage(AnalysisUsage &AU) const override;
00595   bool runOnMachineFunction(MachineFunction &MF) override;
00596   const char *getPassName() const override { return "Early If-Conversion"; }
00597 
00598 private:
00599   bool tryConvertIf(MachineBasicBlock*);
00600   void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
00601   void updateLoops(ArrayRef<MachineBasicBlock*> Removed);
00602   void invalidateTraces();
00603   bool shouldConvertIf();
00604 };
00605 } // end anonymous namespace
00606 
00607 char EarlyIfConverter::ID = 0;
00608 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
00609 
00610 INITIALIZE_PASS_BEGIN(EarlyIfConverter,
00611                       "early-ifcvt", "Early If Converter", false, false)
00612 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
00613 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
00614 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
00615 INITIALIZE_PASS_END(EarlyIfConverter,
00616                       "early-ifcvt", "Early If Converter", false, false)
00617 
00618 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
00619   AU.addRequired<MachineBranchProbabilityInfo>();
00620   AU.addRequired<MachineDominatorTree>();
00621   AU.addPreserved<MachineDominatorTree>();
00622   AU.addRequired<MachineLoopInfo>();
00623   AU.addPreserved<MachineLoopInfo>();
00624   AU.addRequired<MachineTraceMetrics>();
00625   AU.addPreserved<MachineTraceMetrics>();
00626   MachineFunctionPass::getAnalysisUsage(AU);
00627 }
00628 
00629 /// Update the dominator tree after if-conversion erased some blocks.
00630 void EarlyIfConverter::updateDomTree(ArrayRef<MachineBasicBlock*> Removed) {
00631   // convertIf can remove TBB, FBB, and Tail can be merged into Head.
00632   // TBB and FBB should not dominate any blocks.
00633   // Tail children should be transferred to Head.
00634   MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
00635   for (unsigned i = 0, e = Removed.size(); i != e; ++i) {
00636     MachineDomTreeNode *Node = DomTree->getNode(Removed[i]);
00637     assert(Node != HeadNode && "Cannot erase the head node");
00638     while (Node->getNumChildren()) {
00639       assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
00640       DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
00641     }
00642     DomTree->eraseNode(Removed[i]);
00643   }
00644 }
00645 
00646 /// Update LoopInfo after if-conversion.
00647 void EarlyIfConverter::updateLoops(ArrayRef<MachineBasicBlock*> Removed) {
00648   if (!Loops)
00649     return;
00650   // If-conversion doesn't change loop structure, and it doesn't mess with back
00651   // edges, so updating LoopInfo is simply removing the dead blocks.
00652   for (unsigned i = 0, e = Removed.size(); i != e; ++i)
00653     Loops->removeBlock(Removed[i]);
00654 }
00655 
00656 /// Invalidate MachineTraceMetrics before if-conversion.
00657 void EarlyIfConverter::invalidateTraces() {
00658   Traces->verifyAnalysis();
00659   Traces->invalidate(IfConv.Head);
00660   Traces->invalidate(IfConv.Tail);
00661   Traces->invalidate(IfConv.TBB);
00662   Traces->invalidate(IfConv.FBB);
00663   Traces->verifyAnalysis();
00664 }
00665 
00666 // Adjust cycles with downward saturation.
00667 static unsigned adjCycles(unsigned Cyc, int Delta) {
00668   if (Delta < 0 && Cyc + Delta > Cyc)
00669     return 0;
00670   return Cyc + Delta;
00671 }
00672 
00673 /// Apply cost model and heuristics to the if-conversion in IfConv.
00674 /// Return true if the conversion is a good idea.
00675 ///
00676 bool EarlyIfConverter::shouldConvertIf() {
00677   // Stress testing mode disables all cost considerations.
00678   if (Stress)
00679     return true;
00680 
00681   if (!MinInstr)
00682     MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
00683 
00684   MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
00685   MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
00686   DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
00687   unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
00688                               FBBTrace.getCriticalPath());
00689 
00690   // Set a somewhat arbitrary limit on the critical path extension we accept.
00691   unsigned CritLimit = SchedModel.MispredictPenalty/2;
00692 
00693   // If-conversion only makes sense when there is unexploited ILP. Compute the
00694   // maximum-ILP resource length of the trace after if-conversion. Compare it
00695   // to the shortest critical path.
00696   SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
00697   if (IfConv.TBB != IfConv.Tail)
00698     ExtraBlocks.push_back(IfConv.TBB);
00699   unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
00700   DEBUG(dbgs() << "Resource length " << ResLength
00701                << ", minimal critical path " << MinCrit << '\n');
00702   if (ResLength > MinCrit + CritLimit) {
00703     DEBUG(dbgs() << "Not enough available ILP.\n");
00704     return false;
00705   }
00706 
00707   // Assume that the depth of the first head terminator will also be the depth
00708   // of the select instruction inserted, as determined by the flag dependency.
00709   // TBB / FBB data dependencies may delay the select even more.
00710   MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
00711   unsigned BranchDepth =
00712     HeadTrace.getInstrCycles(IfConv.Head->getFirstTerminator()).Depth;
00713   DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
00714 
00715   // Look at all the tail phis, and compute the critical path extension caused
00716   // by inserting select instructions.
00717   MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
00718   for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
00719     SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
00720     unsigned Slack = TailTrace.getInstrSlack(PI.PHI);
00721     unsigned MaxDepth = Slack + TailTrace.getInstrCycles(PI.PHI).Depth;
00722     DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
00723 
00724     // The condition is pulled into the critical path.
00725     unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
00726     if (CondDepth > MaxDepth) {
00727       unsigned Extra = CondDepth - MaxDepth;
00728       DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
00729       if (Extra > CritLimit) {
00730         DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
00731         return false;
00732       }
00733     }
00734 
00735     // The TBB value is pulled into the critical path.
00736     unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(PI.PHI), PI.TCycles);
00737     if (TDepth > MaxDepth) {
00738       unsigned Extra = TDepth - MaxDepth;
00739       DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
00740       if (Extra > CritLimit) {
00741         DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
00742         return false;
00743       }
00744     }
00745 
00746     // The FBB value is pulled into the critical path.
00747     unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(PI.PHI), PI.FCycles);
00748     if (FDepth > MaxDepth) {
00749       unsigned Extra = FDepth - MaxDepth;
00750       DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
00751       if (Extra > CritLimit) {
00752         DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
00753         return false;
00754       }
00755     }
00756   }
00757   return true;
00758 }
00759 
00760 /// Attempt repeated if-conversion on MBB, return true if successful.
00761 ///
00762 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
00763   bool Changed = false;
00764   while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
00765     // If-convert MBB and update analyses.
00766     invalidateTraces();
00767     SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
00768     IfConv.convertIf(RemovedBlocks);
00769     Changed = true;
00770     updateDomTree(RemovedBlocks);
00771     updateLoops(RemovedBlocks);
00772   }
00773   return Changed;
00774 }
00775 
00776 bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
00777   DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
00778                << "********** Function: " << MF.getName() << '\n');
00779   // Only run if conversion if the target wants it.
00780   if (!MF.getTarget()
00781            .getSubtarget<TargetSubtargetInfo>()
00782            .enableEarlyIfConversion())
00783     return false;
00784 
00785   TII = MF.getSubtarget().getInstrInfo();
00786   TRI = MF.getSubtarget().getRegisterInfo();
00787   SchedModel =
00788     MF.getTarget().getSubtarget<TargetSubtargetInfo>().getSchedModel();
00789   MRI = &MF.getRegInfo();
00790   DomTree = &getAnalysis<MachineDominatorTree>();
00791   Loops = getAnalysisIfAvailable<MachineLoopInfo>();
00792   Traces = &getAnalysis<MachineTraceMetrics>();
00793   MinInstr = nullptr;
00794 
00795   bool Changed = false;
00796   IfConv.runOnMachineFunction(MF);
00797 
00798   // Visit blocks in dominator tree post-order. The post-order enables nested
00799   // if-conversion in a single pass. The tryConvertIf() function may erase
00800   // blocks, but only blocks dominated by the head block. This makes it safe to
00801   // update the dominator tree while the post-order iterator is still active.
00802   for (po_iterator<MachineDominatorTree*>
00803        I = po_begin(DomTree), E = po_end(DomTree); I != E; ++I)
00804     if (tryConvertIf(I->getBlock()))
00805       Changed = true;
00806 
00807   return Changed;
00808 }