| //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===// |
| // |
| // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| // See https://llvm.org/LICENSE.txt for license information. |
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| // |
| //===----------------------------------------------------------------------===// |
| // |
| // Peephole optimize the CFG. |
| // |
| //===----------------------------------------------------------------------===// |
| |
| #include "llvm/ADT/APInt.h" |
| #include "llvm/ADT/ArrayRef.h" |
| #include "llvm/ADT/DenseMap.h" |
| #include "llvm/ADT/Optional.h" |
| #include "llvm/ADT/STLExtras.h" |
| #include "llvm/ADT/SetOperations.h" |
| #include "llvm/ADT/SetVector.h" |
| #include "llvm/ADT/SmallPtrSet.h" |
| #include "llvm/ADT/SmallVector.h" |
| #include "llvm/ADT/Statistic.h" |
| #include "llvm/ADT/StringRef.h" |
| #include "llvm/Analysis/AssumptionCache.h" |
| #include "llvm/Analysis/ConstantFolding.h" |
| #include "llvm/Analysis/EHPersonalities.h" |
| #include "llvm/Analysis/InstructionSimplify.h" |
| #include "llvm/Analysis/TargetTransformInfo.h" |
| #include "llvm/Transforms/Utils/Local.h" |
| #include "llvm/Analysis/ValueTracking.h" |
| #include "llvm/IR/Attributes.h" |
| #include "llvm/IR/BasicBlock.h" |
| #include "llvm/IR/CFG.h" |
| #include "llvm/IR/CallSite.h" |
| #include "llvm/IR/Constant.h" |
| #include "llvm/IR/ConstantRange.h" |
| #include "llvm/IR/Constants.h" |
| #include "llvm/IR/DataLayout.h" |
| #include "llvm/IR/DerivedTypes.h" |
| #include "llvm/IR/Function.h" |
| #include "llvm/IR/GlobalValue.h" |
| #include "llvm/IR/GlobalVariable.h" |
| #include "llvm/IR/IRBuilder.h" |
| #include "llvm/IR/InstrTypes.h" |
| #include "llvm/IR/Instruction.h" |
| #include "llvm/IR/Instructions.h" |
| #include "llvm/IR/IntrinsicInst.h" |
| #include "llvm/IR/Intrinsics.h" |
| #include "llvm/IR/LLVMContext.h" |
| #include "llvm/IR/MDBuilder.h" |
| #include "llvm/IR/Metadata.h" |
| #include "llvm/IR/Module.h" |
| #include "llvm/IR/NoFolder.h" |
| #include "llvm/IR/Operator.h" |
| #include "llvm/IR/PatternMatch.h" |
| #include "llvm/IR/Type.h" |
| #include "llvm/IR/Use.h" |
| #include "llvm/IR/User.h" |
| #include "llvm/IR/Value.h" |
| #include "llvm/Support/Casting.h" |
| #include "llvm/Support/CommandLine.h" |
| #include "llvm/Support/Debug.h" |
| #include "llvm/Support/ErrorHandling.h" |
| #include "llvm/Support/KnownBits.h" |
| #include "llvm/Support/MathExtras.h" |
| #include "llvm/Support/raw_ostream.h" |
| #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| #include "llvm/Transforms/Utils/ValueMapper.h" |
| #include <algorithm> |
| #include <cassert> |
| #include <climits> |
| #include <cstddef> |
| #include <cstdint> |
| #include <iterator> |
| #include <map> |
| #include <set> |
| #include <tuple> |
| #include <utility> |
| #include <vector> |
| |
| using namespace llvm; |
| using namespace PatternMatch; |
| |
| #define DEBUG_TYPE "simplifycfg" |
| |
| // Chosen as 2 so as to be cheap, but still to have enough power to fold |
| // a select, so the "clamp" idiom (of a min followed by a max) will be caught. |
| // To catch this, we need to fold a compare and a select, hence '2' being the |
| // minimum reasonable default. |
| static cl::opt<unsigned> PHINodeFoldingThreshold( |
| "phi-node-folding-threshold", cl::Hidden, cl::init(2), |
| cl::desc( |
| "Control the amount of phi node folding to perform (default = 2)")); |
| |
| static cl::opt<bool> DupRet( |
| "simplifycfg-dup-ret", cl::Hidden, cl::init(false), |
| cl::desc("Duplicate return instructions into unconditional branches")); |
| |
| static cl::opt<bool> |
| SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), |
| cl::desc("Sink common instructions down to the end block")); |
| |
| static cl::opt<bool> HoistCondStores( |
| "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), |
| cl::desc("Hoist conditional stores if an unconditional store precedes")); |
| |
| static cl::opt<bool> MergeCondStores( |
| "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), |
| cl::desc("Hoist conditional stores even if an unconditional store does not " |
| "precede - hoist multiple conditional stores into a single " |
| "predicated store")); |
| |
| static cl::opt<bool> MergeCondStoresAggressively( |
| "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), |
| cl::desc("When merging conditional stores, do so even if the resultant " |
| "basic blocks are unlikely to be if-converted as a result")); |
| |
| static cl::opt<bool> SpeculateOneExpensiveInst( |
| "speculate-one-expensive-inst", cl::Hidden, cl::init(true), |
| cl::desc("Allow exactly one expensive instruction to be speculatively " |
| "executed")); |
| |
| static cl::opt<unsigned> MaxSpeculationDepth( |
| "max-speculation-depth", cl::Hidden, cl::init(10), |
| cl::desc("Limit maximum recursion depth when calculating costs of " |
| "speculatively executed instructions")); |
| |
| STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps"); |
| STATISTIC(NumLinearMaps, |
| "Number of switch instructions turned into linear mapping"); |
| STATISTIC(NumLookupTables, |
| "Number of switch instructions turned into lookup tables"); |
| STATISTIC( |
| NumLookupTablesHoles, |
| "Number of switch instructions turned into lookup tables (holes checked)"); |
| STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares"); |
| STATISTIC(NumSinkCommons, |
| "Number of common instructions sunk down to the end block"); |
| STATISTIC(NumSpeculations, "Number of speculative executed instructions"); |
| |
| namespace { |
| |
| // The first field contains the value that the switch produces when a certain |
| // case group is selected, and the second field is a vector containing the |
| // cases composing the case group. |
| using SwitchCaseResultVectorTy = |
| SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>; |
| |
| // The first field contains the phi node that generates a result of the switch |
| // and the second field contains the value generated for a certain case in the |
| // switch for that PHI. |
| using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>; |
| |
| /// ValueEqualityComparisonCase - Represents a case of a switch. |
| struct ValueEqualityComparisonCase { |
| ConstantInt *Value; |
| BasicBlock *Dest; |
| |
| ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest) |
| : Value(Value), Dest(Dest) {} |
| |
| bool operator<(ValueEqualityComparisonCase RHS) const { |
| // Comparing pointers is ok as we only rely on the order for uniquing. |
| return Value < RHS.Value; |
| } |
| |
| bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; } |
| }; |
| |
| class SimplifyCFGOpt { |
| const TargetTransformInfo &TTI; |
| const DataLayout &DL; |
| SmallPtrSetImpl<BasicBlock *> *LoopHeaders; |
| const SimplifyCFGOptions &Options; |
| bool Resimplify; |
| |
| Value *isValueEqualityComparison(Instruction *TI); |
| BasicBlock *GetValueEqualityComparisonCases( |
| Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases); |
| bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI, |
| BasicBlock *Pred, |
| IRBuilder<> &Builder); |
| bool FoldValueComparisonIntoPredecessors(Instruction *TI, |
| IRBuilder<> &Builder); |
| |
| bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder); |
| bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder); |
| bool SimplifySingleResume(ResumeInst *RI); |
| bool SimplifyCommonResume(ResumeInst *RI); |
| bool SimplifyCleanupReturn(CleanupReturnInst *RI); |
| bool SimplifyUnreachable(UnreachableInst *UI); |
| bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder); |
| bool SimplifyIndirectBr(IndirectBrInst *IBI); |
| bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder); |
| bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder); |
| |
| bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI, |
| IRBuilder<> &Builder); |
| |
| public: |
| SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL, |
| SmallPtrSetImpl<BasicBlock *> *LoopHeaders, |
| const SimplifyCFGOptions &Opts) |
| : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {} |
| |
| bool run(BasicBlock *BB); |
| bool simplifyOnce(BasicBlock *BB); |
| |
| // Helper to set Resimplify and return change indication. |
| bool requestResimplify() { |
| Resimplify = true; |
| return true; |
| } |
| }; |
| |
| } // end anonymous namespace |
| |
| /// Return true if it is safe to merge these two |
| /// terminator instructions together. |
| static bool |
| SafeToMergeTerminators(Instruction *SI1, Instruction *SI2, |
| SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) { |
| if (SI1 == SI2) |
| return false; // Can't merge with self! |
| |
| // It is not safe to merge these two switch instructions if they have a common |
| // successor, and if that successor has a PHI node, and if *that* PHI node has |
| // conflicting incoming values from the two switch blocks. |
| BasicBlock *SI1BB = SI1->getParent(); |
| BasicBlock *SI2BB = SI2->getParent(); |
| |
| SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
| bool Fail = false; |
| for (BasicBlock *Succ : successors(SI2BB)) |
| if (SI1Succs.count(Succ)) |
| for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) { |
| PHINode *PN = cast<PHINode>(BBI); |
| if (PN->getIncomingValueForBlock(SI1BB) != |
| PN->getIncomingValueForBlock(SI2BB)) { |
| if (FailBlocks) |
| FailBlocks->insert(Succ); |
| Fail = true; |
| } |
| } |
| |
| return !Fail; |
| } |
| |
| /// Return true if it is safe and profitable to merge these two terminator |
| /// instructions together, where SI1 is an unconditional branch. PhiNodes will |
| /// store all PHI nodes in common successors. |
| static bool |
| isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2, |
| Instruction *Cond, |
| SmallVectorImpl<PHINode *> &PhiNodes) { |
| if (SI1 == SI2) |
| return false; // Can't merge with self! |
| assert(SI1->isUnconditional() && SI2->isConditional()); |
| |
| // We fold the unconditional branch if we can easily update all PHI nodes in |
| // common successors: |
| // 1> We have a constant incoming value for the conditional branch; |
| // 2> We have "Cond" as the incoming value for the unconditional branch; |
| // 3> SI2->getCondition() and Cond have same operands. |
| CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition()); |
| if (!Ci2) |
| return false; |
| if (!(Cond->getOperand(0) == Ci2->getOperand(0) && |
| Cond->getOperand(1) == Ci2->getOperand(1)) && |
| !(Cond->getOperand(0) == Ci2->getOperand(1) && |
| Cond->getOperand(1) == Ci2->getOperand(0))) |
| return false; |
| |
| BasicBlock *SI1BB = SI1->getParent(); |
| BasicBlock *SI2BB = SI2->getParent(); |
| SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
| for (BasicBlock *Succ : successors(SI2BB)) |
| if (SI1Succs.count(Succ)) |
| for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) { |
| PHINode *PN = cast<PHINode>(BBI); |
| if (PN->getIncomingValueForBlock(SI1BB) != Cond || |
| !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB))) |
| return false; |
| PhiNodes.push_back(PN); |
| } |
| return true; |
| } |
| |
| /// Update PHI nodes in Succ to indicate that there will now be entries in it |
| /// from the 'NewPred' block. The values that will be flowing into the PHI nodes |
| /// will be the same as those coming in from ExistPred, an existing predecessor |
| /// of Succ. |
| static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, |
| BasicBlock *ExistPred) { |
| for (PHINode &PN : Succ->phis()) |
| PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred); |
| } |
| |
| /// Compute an abstract "cost" of speculating the given instruction, |
| /// which is assumed to be safe to speculate. TCC_Free means cheap, |
| /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively |
| /// expensive. |
| static unsigned ComputeSpeculationCost(const User *I, |
| const TargetTransformInfo &TTI) { |
| assert(isSafeToSpeculativelyExecute(I) && |
| "Instruction is not safe to speculatively execute!"); |
| return TTI.getUserCost(I); |
| } |
| |
| /// If we have a merge point of an "if condition" as accepted above, |
| /// return true if the specified value dominates the block. We |
| /// don't handle the true generality of domination here, just a special case |
| /// which works well enough for us. |
| /// |
| /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to |
| /// see if V (which must be an instruction) and its recursive operands |
| /// that do not dominate BB have a combined cost lower than CostRemaining and |
| /// are non-trapping. If both are true, the instruction is inserted into the |
| /// set and true is returned. |
| /// |
| /// The cost for most non-trapping instructions is defined as 1 except for |
| /// Select whose cost is 2. |
| /// |
| /// After this function returns, CostRemaining is decreased by the cost of |
| /// V plus its non-dominating operands. If that cost is greater than |
| /// CostRemaining, false is returned and CostRemaining is undefined. |
| static bool DominatesMergePoint(Value *V, BasicBlock *BB, |
| SmallPtrSetImpl<Instruction *> &AggressiveInsts, |
| unsigned &CostRemaining, |
| const TargetTransformInfo &TTI, |
| unsigned Depth = 0) { |
| // It is possible to hit a zero-cost cycle (phi/gep instructions for example), |
| // so limit the recursion depth. |
| // TODO: While this recursion limit does prevent pathological behavior, it |
| // would be better to track visited instructions to avoid cycles. |
| if (Depth == MaxSpeculationDepth) |
| return false; |
| |
| Instruction *I = dyn_cast<Instruction>(V); |
| if (!I) { |
| // Non-instructions all dominate instructions, but not all constantexprs |
| // can be executed unconditionally. |
| if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) |
| if (C->canTrap()) |
| return false; |
| return true; |
| } |
| BasicBlock *PBB = I->getParent(); |
| |
| // We don't want to allow weird loops that might have the "if condition" in |
| // the bottom of this block. |
| if (PBB == BB) |
| return false; |
| |
| // If this instruction is defined in a block that contains an unconditional |
| // branch to BB, then it must be in the 'conditional' part of the "if |
| // statement". If not, it definitely dominates the region. |
| BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()); |
| if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB) |
| return true; |
| |
| // If we have seen this instruction before, don't count it again. |
| if (AggressiveInsts.count(I)) |
| return true; |
| |
| // Okay, it looks like the instruction IS in the "condition". Check to |
| // see if it's a cheap instruction to unconditionally compute, and if it |
| // only uses stuff defined outside of the condition. If so, hoist it out. |
| if (!isSafeToSpeculativelyExecute(I)) |
| return false; |
| |
| unsigned Cost = ComputeSpeculationCost(I, TTI); |
| |
| // Allow exactly one instruction to be speculated regardless of its cost |
| // (as long as it is safe to do so). |
| // This is intended to flatten the CFG even if the instruction is a division |
| // or other expensive operation. The speculation of an expensive instruction |
| // is expected to be undone in CodeGenPrepare if the speculation has not |
| // enabled further IR optimizations. |
| if (Cost > CostRemaining && |
| (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0)) |
| return false; |
| |
| // Avoid unsigned wrap. |
| CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost; |
| |
| // Okay, we can only really hoist these out if their operands do |
| // not take us over the cost threshold. |
| for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) |
| if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI, |
| Depth + 1)) |
| return false; |
| // Okay, it's safe to do this! Remember this instruction. |
| AggressiveInsts.insert(I); |
| return true; |
| } |
| |
| /// Extract ConstantInt from value, looking through IntToPtr |
| /// and PointerNullValue. Return NULL if value is not a constant int. |
| static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) { |
| // Normal constant int. |
| ConstantInt *CI = dyn_cast<ConstantInt>(V); |
| if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy()) |
| return CI; |
| |
| // This is some kind of pointer constant. Turn it into a pointer-sized |
| // ConstantInt if possible. |
| IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType())); |
| |
| // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*). |
| if (isa<ConstantPointerNull>(V)) |
| return ConstantInt::get(PtrTy, 0); |
| |
| // IntToPtr const int. |
| if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
| if (CE->getOpcode() == Instruction::IntToPtr) |
| if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) { |
| // The constant is very likely to have the right type already. |
| if (CI->getType() == PtrTy) |
| return CI; |
| else |
| return cast<ConstantInt>( |
| ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false)); |
| } |
| return nullptr; |
| } |
| |
| namespace { |
| |
| /// Given a chain of or (||) or and (&&) comparison of a value against a |
| /// constant, this will try to recover the information required for a switch |
| /// structure. |
| /// It will depth-first traverse the chain of comparison, seeking for patterns |
| /// like %a == 12 or %a < 4 and combine them to produce a set of integer |
| /// representing the different cases for the switch. |
| /// Note that if the chain is composed of '||' it will build the set of elements |
| /// that matches the comparisons (i.e. any of this value validate the chain) |
| /// while for a chain of '&&' it will build the set elements that make the test |
| /// fail. |
| struct ConstantComparesGatherer { |
| const DataLayout &DL; |
| |
| /// Value found for the switch comparison |
| Value *CompValue = nullptr; |
| |
| /// Extra clause to be checked before the switch |
| Value *Extra = nullptr; |
| |
| /// Set of integers to match in switch |
| SmallVector<ConstantInt *, 8> Vals; |
| |
| /// Number of comparisons matched in the and/or chain |
| unsigned UsedICmps = 0; |
| |
| /// Construct and compute the result for the comparison instruction Cond |
| ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) { |
| gather(Cond); |
| } |
| |
| ConstantComparesGatherer(const ConstantComparesGatherer &) = delete; |
| ConstantComparesGatherer & |
| operator=(const ConstantComparesGatherer &) = delete; |
| |
| private: |
| /// Try to set the current value used for the comparison, it succeeds only if |
| /// it wasn't set before or if the new value is the same as the old one |
| bool setValueOnce(Value *NewVal) { |
| if (CompValue && CompValue != NewVal) |
| return false; |
| CompValue = NewVal; |
| return (CompValue != nullptr); |
| } |
| |
| /// Try to match Instruction "I" as a comparison against a constant and |
| /// populates the array Vals with the set of values that match (or do not |
| /// match depending on isEQ). |
| /// Return false on failure. On success, the Value the comparison matched |
| /// against is placed in CompValue. |
| /// If CompValue is already set, the function is expected to fail if a match |
| /// is found but the value compared to is different. |
| bool matchInstruction(Instruction *I, bool isEQ) { |
| // If this is an icmp against a constant, handle this as one of the cases. |
| ICmpInst *ICI; |
| ConstantInt *C; |
| if (!((ICI = dyn_cast<ICmpInst>(I)) && |
| (C = GetConstantInt(I->getOperand(1), DL)))) { |
| return false; |
| } |
| |
| Value *RHSVal; |
| const APInt *RHSC; |
| |
| // Pattern match a special case |
| // (x & ~2^z) == y --> x == y || x == y|2^z |
| // This undoes a transformation done by instcombine to fuse 2 compares. |
| if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) { |
| // It's a little bit hard to see why the following transformations are |
| // correct. Here is a CVC3 program to verify them for 64-bit values: |
| |
| /* |
| ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63); |
| x : BITVECTOR(64); |
| y : BITVECTOR(64); |
| z : BITVECTOR(64); |
| mask : BITVECTOR(64) = BVSHL(ONE, z); |
| QUERY( (y & ~mask = y) => |
| ((x & ~mask = y) <=> (x = y OR x = (y | mask))) |
| ); |
| QUERY( (y | mask = y) => |
| ((x | mask = y) <=> (x = y OR x = (y & ~mask))) |
| ); |
| */ |
| |
| // Please note that each pattern must be a dual implication (<--> or |
| // iff). One directional implication can create spurious matches. If the |
| // implication is only one-way, an unsatisfiable condition on the left |
| // side can imply a satisfiable condition on the right side. Dual |
| // implication ensures that satisfiable conditions are transformed to |
| // other satisfiable conditions and unsatisfiable conditions are |
| // transformed to other unsatisfiable conditions. |
| |
| // Here is a concrete example of a unsatisfiable condition on the left |
| // implying a satisfiable condition on the right: |
| // |
| // mask = (1 << z) |
| // (x & ~mask) == y --> (x == y || x == (y | mask)) |
| // |
| // Substituting y = 3, z = 0 yields: |
| // (x & -2) == 3 --> (x == 3 || x == 2) |
| |
| // Pattern match a special case: |
| /* |
| QUERY( (y & ~mask = y) => |
| ((x & ~mask = y) <=> (x = y OR x = (y | mask))) |
| ); |
| */ |
| if (match(ICI->getOperand(0), |
| m_And(m_Value(RHSVal), m_APInt(RHSC)))) { |
| APInt Mask = ~*RHSC; |
| if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) { |
| // If we already have a value for the switch, it has to match! |
| if (!setValueOnce(RHSVal)) |
| return false; |
| |
| Vals.push_back(C); |
| Vals.push_back( |
| ConstantInt::get(C->getContext(), |
| C->getValue() | Mask)); |
| UsedICmps++; |
| return true; |
| } |
| } |
| |
| // Pattern match a special case: |
| /* |
| QUERY( (y | mask = y) => |
| ((x | mask = y) <=> (x = y OR x = (y & ~mask))) |
| ); |
| */ |
| if (match(ICI->getOperand(0), |
| m_Or(m_Value(RHSVal), m_APInt(RHSC)))) { |
| APInt Mask = *RHSC; |
| if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) { |
| // If we already have a value for the switch, it has to match! |
| if (!setValueOnce(RHSVal)) |
| return false; |
| |
| Vals.push_back(C); |
| Vals.push_back(ConstantInt::get(C->getContext(), |
| C->getValue() & ~Mask)); |
| UsedICmps++; |
| return true; |
| } |
| } |
| |
| // If we already have a value for the switch, it has to match! |
| if (!setValueOnce(ICI->getOperand(0))) |
| return false; |
| |
| UsedICmps++; |
| Vals.push_back(C); |
| return ICI->getOperand(0); |
| } |
| |
| // If we have "x ult 3", for example, then we can add 0,1,2 to the set. |
| ConstantRange Span = ConstantRange::makeAllowedICmpRegion( |
| ICI->getPredicate(), C->getValue()); |
| |
| // Shift the range if the compare is fed by an add. This is the range |
| // compare idiom as emitted by instcombine. |
| Value *CandidateVal = I->getOperand(0); |
| if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) { |
| Span = Span.subtract(*RHSC); |
| CandidateVal = RHSVal; |
| } |
| |
| // If this is an and/!= check, then we are looking to build the set of |
| // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into |
| // x != 0 && x != 1. |
| if (!isEQ) |
| Span = Span.inverse(); |
| |
| // If there are a ton of values, we don't want to make a ginormous switch. |
| if (Span.isSizeLargerThan(8) || Span.isEmptySet()) { |
| return false; |
| } |
| |
| // If we already have a value for the switch, it has to match! |
| if (!setValueOnce(CandidateVal)) |
| return false; |
| |
| // Add all values from the range to the set |
| for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp) |
| Vals.push_back(ConstantInt::get(I->getContext(), Tmp)); |
| |
| UsedICmps++; |
| return true; |
| } |
| |
| /// Given a potentially 'or'd or 'and'd together collection of icmp |
| /// eq/ne/lt/gt instructions that compare a value against a constant, extract |
| /// the value being compared, and stick the list constants into the Vals |
| /// vector. |
| /// One "Extra" case is allowed to differ from the other. |
| void gather(Value *V) { |
| Instruction *I = dyn_cast<Instruction>(V); |
| bool isEQ = (I->getOpcode() == Instruction::Or); |
| |
| // Keep a stack (SmallVector for efficiency) for depth-first traversal |
| SmallVector<Value *, 8> DFT; |
| SmallPtrSet<Value *, 8> Visited; |
| |
| // Initialize |
| Visited.insert(V); |
| DFT.push_back(V); |
| |
| while (!DFT.empty()) { |
| V = DFT.pop_back_val(); |
| |
| if (Instruction *I = dyn_cast<Instruction>(V)) { |
| // If it is a || (or && depending on isEQ), process the operands. |
| if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) { |
| if (Visited.insert(I->getOperand(1)).second) |
| DFT.push_back(I->getOperand(1)); |
| if (Visited.insert(I->getOperand(0)).second) |
| DFT.push_back(I->getOperand(0)); |
| continue; |
| } |
| |
| // Try to match the current instruction |
| if (matchInstruction(I, isEQ)) |
| // Match succeed, continue the loop |
| continue; |
| } |
| |
| // One element of the sequence of || (or &&) could not be match as a |
| // comparison against the same value as the others. |
| // We allow only one "Extra" case to be checked before the switch |
| if (!Extra) { |
| Extra = V; |
| continue; |
| } |
| // Failed to parse a proper sequence, abort now |
| CompValue = nullptr; |
| break; |
| } |
| } |
| }; |
| |
| } // end anonymous namespace |
| |
| static void EraseTerminatorAndDCECond(Instruction *TI) { |
| Instruction *Cond = nullptr; |
| if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| Cond = dyn_cast<Instruction>(SI->getCondition()); |
| } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| if (BI->isConditional()) |
| Cond = dyn_cast<Instruction>(BI->getCondition()); |
| } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { |
| Cond = dyn_cast<Instruction>(IBI->getAddress()); |
| } |
| |
| TI->eraseFromParent(); |
| if (Cond) |
| RecursivelyDeleteTriviallyDeadInstructions(Cond); |
| } |
| |
| /// Return true if the specified terminator checks |
| /// to see if a value is equal to constant integer value. |
| Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) { |
| Value *CV = nullptr; |
| if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| // Do not permit merging of large switch instructions into their |
| // predecessors unless there is only one predecessor. |
| if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors())) |
| CV = SI->getCondition(); |
| } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) |
| if (BI->isConditional() && BI->getCondition()->hasOneUse()) |
| if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) { |
| if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL)) |
| CV = ICI->getOperand(0); |
| } |
| |
| // Unwrap any lossless ptrtoint cast. |
| if (CV) { |
| if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) { |
| Value *Ptr = PTII->getPointerOperand(); |
| if (PTII->getType() == DL.getIntPtrType(Ptr->getType())) |
| CV = Ptr; |
| } |
| } |
| return CV; |
| } |
| |
| /// Given a value comparison instruction, |
| /// decode all of the 'cases' that it represents and return the 'default' block. |
| BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases( |
| Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) { |
| if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| Cases.reserve(SI->getNumCases()); |
| for (auto Case : SI->cases()) |
| Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(), |
| Case.getCaseSuccessor())); |
| return SI->getDefaultDest(); |
| } |
| |
| BranchInst *BI = cast<BranchInst>(TI); |
| ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
| BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE); |
| Cases.push_back(ValueEqualityComparisonCase( |
| GetConstantInt(ICI->getOperand(1), DL), Succ)); |
| return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ); |
| } |
| |
| /// Given a vector of bb/value pairs, remove any entries |
| /// in the list that match the specified block. |
| static void |
| EliminateBlockCases(BasicBlock *BB, |
| std::vector<ValueEqualityComparisonCase> &Cases) { |
| Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end()); |
| } |
| |
| /// Return true if there are any keys in C1 that exist in C2 as well. |
| static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1, |
| std::vector<ValueEqualityComparisonCase> &C2) { |
| std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2; |
| |
| // Make V1 be smaller than V2. |
| if (V1->size() > V2->size()) |
| std::swap(V1, V2); |
| |
| if (V1->empty()) |
| return false; |
| if (V1->size() == 1) { |
| // Just scan V2. |
| ConstantInt *TheVal = (*V1)[0].Value; |
| for (unsigned i = 0, e = V2->size(); i != e; ++i) |
| if (TheVal == (*V2)[i].Value) |
| return true; |
| } |
| |
| // Otherwise, just sort both lists and compare element by element. |
| array_pod_sort(V1->begin(), V1->end()); |
| array_pod_sort(V2->begin(), V2->end()); |
| unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); |
| while (i1 != e1 && i2 != e2) { |
| if ((*V1)[i1].Value == (*V2)[i2].Value) |
| return true; |
| if ((*V1)[i1].Value < (*V2)[i2].Value) |
| ++i1; |
| else |
| ++i2; |
| } |
| return false; |
| } |
| |
| // Set branch weights on SwitchInst. This sets the metadata if there is at |
| // least one non-zero weight. |
| static void setBranchWeights(SwitchInst *SI, ArrayRef<uint32_t> Weights) { |
| // Check that there is at least one non-zero weight. Otherwise, pass |
| // nullptr to setMetadata which will erase the existing metadata. |
| MDNode *N = nullptr; |
| if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; })) |
| N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights); |
| SI->setMetadata(LLVMContext::MD_prof, N); |
| } |
| |
| // Similar to the above, but for branch and select instructions that take |
| // exactly 2 weights. |
| static void setBranchWeights(Instruction *I, uint32_t TrueWeight, |
| uint32_t FalseWeight) { |
| assert(isa<BranchInst>(I) || isa<SelectInst>(I)); |
| // Check that there is at least one non-zero weight. Otherwise, pass |
| // nullptr to setMetadata which will erase the existing metadata. |
| MDNode *N = nullptr; |
| if (TrueWeight || FalseWeight) |
| N = MDBuilder(I->getParent()->getContext()) |
| .createBranchWeights(TrueWeight, FalseWeight); |
| I->setMetadata(LLVMContext::MD_prof, N); |
| } |
| |
| /// If TI is known to be a terminator instruction and its block is known to |
| /// only have a single predecessor block, check to see if that predecessor is |
| /// also a value comparison with the same value, and if that comparison |
| /// determines the outcome of this comparison. If so, simplify TI. This does a |
| /// very limited form of jump threading. |
| bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor( |
| Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) { |
| Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); |
| if (!PredVal) |
| return false; // Not a value comparison in predecessor. |
| |
| Value *ThisVal = isValueEqualityComparison(TI); |
| assert(ThisVal && "This isn't a value comparison!!"); |
| if (ThisVal != PredVal) |
| return false; // Different predicates. |
| |
| // TODO: Preserve branch weight metadata, similarly to how |
| // FoldValueComparisonIntoPredecessors preserves it. |
| |
| // Find out information about when control will move from Pred to TI's block. |
| std::vector<ValueEqualityComparisonCase> PredCases; |
| BasicBlock *PredDef = |
| GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases); |
| EliminateBlockCases(PredDef, PredCases); // Remove default from cases. |
| |
| // Find information about how control leaves this block. |
| std::vector<ValueEqualityComparisonCase> ThisCases; |
| BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); |
| EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. |
| |
| // If TI's block is the default block from Pred's comparison, potentially |
| // simplify TI based on this knowledge. |
| if (PredDef == TI->getParent()) { |
| // If we are here, we know that the value is none of those cases listed in |
| // PredCases. If there are any cases in ThisCases that are in PredCases, we |
| // can simplify TI. |
| if (!ValuesOverlap(PredCases, ThisCases)) |
| return false; |
| |
| if (isa<BranchInst>(TI)) { |
| // Okay, one of the successors of this condbr is dead. Convert it to a |
| // uncond br. |
| assert(ThisCases.size() == 1 && "Branch can only have one case!"); |
| // Insert the new branch. |
| Instruction *NI = Builder.CreateBr(ThisDef); |
| (void)NI; |
| |
| // Remove PHI node entries for the dead edge. |
| ThisCases[0].Dest->removePredecessor(TI->getParent()); |
| |
| LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
| << "Through successor TI: " << *TI << "Leaving: " << *NI |
| << "\n"); |
| |
| EraseTerminatorAndDCECond(TI); |
| return true; |
| } |
| |
| SwitchInst *SI = cast<SwitchInst>(TI); |
| // Okay, TI has cases that are statically dead, prune them away. |
| SmallPtrSet<Constant *, 16> DeadCases; |
| for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| DeadCases.insert(PredCases[i].Value); |
| |
| LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
| << "Through successor TI: " << *TI); |
| |
| // Collect branch weights into a vector. |
| SmallVector<uint32_t, 8> Weights; |
| MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); |
| bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases()); |
| if (HasWeight) |
| for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; |
| ++MD_i) { |
| ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i)); |
| Weights.push_back(CI->getValue().getZExtValue()); |
| } |
| for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) { |
| --i; |
| if (DeadCases.count(i->getCaseValue())) { |
| if (HasWeight) { |
| std::swap(Weights[i->getCaseIndex() + 1], Weights.back()); |
| Weights.pop_back(); |
| } |
| i->getCaseSuccessor()->removePredecessor(TI->getParent()); |
| SI->removeCase(i); |
| } |
| } |
| if (HasWeight && Weights.size() >= 2) |
| setBranchWeights(SI, Weights); |
| |
| LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n"); |
| return true; |
| } |
| |
| // Otherwise, TI's block must correspond to some matched value. Find out |
| // which value (or set of values) this is. |
| ConstantInt *TIV = nullptr; |
| BasicBlock *TIBB = TI->getParent(); |
| for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| if (PredCases[i].Dest == TIBB) { |
| if (TIV) |
| return false; // Cannot handle multiple values coming to this block. |
| TIV = PredCases[i].Value; |
| } |
| assert(TIV && "No edge from pred to succ?"); |
| |
| // Okay, we found the one constant that our value can be if we get into TI's |
| // BB. Find out which successor will unconditionally be branched to. |
| BasicBlock *TheRealDest = nullptr; |
| for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) |
| if (ThisCases[i].Value == TIV) { |
| TheRealDest = ThisCases[i].Dest; |
| break; |
| } |
| |
| // If not handled by any explicit cases, it is handled by the default case. |
| if (!TheRealDest) |
| TheRealDest = ThisDef; |
| |
| // Remove PHI node entries for dead edges. |
| BasicBlock *CheckEdge = TheRealDest; |
| for (BasicBlock *Succ : successors(TIBB)) |
| if (Succ != CheckEdge) |
| Succ->removePredecessor(TIBB); |
| else |
| CheckEdge = nullptr; |
| |
| // Insert the new branch. |
| Instruction *NI = Builder.CreateBr(TheRealDest); |
| (void)NI; |
| |
| LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
| << "Through successor TI: " << *TI << "Leaving: " << *NI |
| << "\n"); |
| |
| EraseTerminatorAndDCECond(TI); |
| return true; |
| } |
| |
| namespace { |
| |
| /// This class implements a stable ordering of constant |
| /// integers that does not depend on their address. This is important for |
| /// applications that sort ConstantInt's to ensure uniqueness. |
| struct ConstantIntOrdering { |
| bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { |
| return LHS->getValue().ult(RHS->getValue()); |
| } |
| }; |
| |
| } // end anonymous namespace |
| |
| static int ConstantIntSortPredicate(ConstantInt *const *P1, |
| ConstantInt *const *P2) { |
| const ConstantInt *LHS = *P1; |
| const ConstantInt *RHS = *P2; |
| if (LHS == RHS) |
| return 0; |
| return LHS->getValue().ult(RHS->getValue()) ? 1 : -1; |
| } |
| |
| static inline bool HasBranchWeights(const Instruction *I) { |
| MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof); |
| if (ProfMD && ProfMD->getOperand(0)) |
| if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0))) |
| return MDS->getString().equals("branch_weights"); |
| |
| return false; |
| } |
| |
| /// Get Weights of a given terminator, the default weight is at the front |
| /// of the vector. If TI is a conditional eq, we need to swap the branch-weight |
| /// metadata. |
| static void GetBranchWeights(Instruction *TI, |
| SmallVectorImpl<uint64_t> &Weights) { |
| MDNode *MD = TI->getMetadata(LLVMContext::MD_prof); |
| assert(MD); |
| for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) { |
| ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i)); |
| Weights.push_back(CI->getValue().getZExtValue()); |
| } |
| |
| // If TI is a conditional eq, the default case is the false case, |
| // and the corresponding branch-weight data is at index 2. We swap the |
| // default weight to be the first entry. |
| if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| assert(Weights.size() == 2); |
| ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
| if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| std::swap(Weights.front(), Weights.back()); |
| } |
| } |
| |
| /// Keep halving the weights until all can fit in uint32_t. |
| static void FitWeights(MutableArrayRef<uint64_t> Weights) { |
| uint64_t Max = *std::max_element(Weights.begin(), Weights.end()); |
| if (Max > UINT_MAX) { |
| unsigned Offset = 32 - countLeadingZeros(Max); |
| for (uint64_t &I : Weights) |
| I >>= Offset; |
| } |
| } |
| |
| /// The specified terminator is a value equality comparison instruction |
| /// (either a switch or a branch on "X == c"). |
| /// See if any of the predecessors of the terminator block are value comparisons |
| /// on the same value. If so, and if safe to do so, fold them together. |
| bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI, |
| IRBuilder<> &Builder) { |
| BasicBlock *BB = TI->getParent(); |
| Value *CV = isValueEqualityComparison(TI); // CondVal |
| assert(CV && "Not a comparison?"); |
| bool Changed = false; |
| |
| SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB)); |
| while (!Preds.empty()) { |
| BasicBlock *Pred = Preds.pop_back_val(); |
| |
| // See if the predecessor is a comparison with the same value. |
| Instruction *PTI = Pred->getTerminator(); |
| Value *PCV = isValueEqualityComparison(PTI); // PredCondVal |
| |
| if (PCV == CV && TI != PTI) { |
| SmallSetVector<BasicBlock*, 4> FailBlocks; |
| if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) { |
| for (auto *Succ : FailBlocks) { |
| if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split")) |
| return false; |
| } |
| } |
| |
| // Figure out which 'cases' to copy from SI to PSI. |
| std::vector<ValueEqualityComparisonCase> BBCases; |
| BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); |
| |
| std::vector<ValueEqualityComparisonCase> PredCases; |
| BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); |
| |
| // Based on whether the default edge from PTI goes to BB or not, fill in |
| // PredCases and PredDefault with the new switch cases we would like to |
| // build. |
| SmallVector<BasicBlock *, 8> NewSuccessors; |
| |
| // Update the branch weight metadata along the way |
| SmallVector<uint64_t, 8> Weights; |
| bool PredHasWeights = HasBranchWeights(PTI); |
| bool SuccHasWeights = HasBranchWeights(TI); |
| |
| if (PredHasWeights) { |
| GetBranchWeights(PTI, Weights); |
| // branch-weight metadata is inconsistent here. |
| if (Weights.size() != 1 + PredCases.size()) |
| PredHasWeights = SuccHasWeights = false; |
| } else if (SuccHasWeights) |
| // If there are no predecessor weights but there are successor weights, |
| // populate Weights with 1, which will later be scaled to the sum of |
| // successor's weights |
| Weights.assign(1 + PredCases.size(), 1); |
| |
| SmallVector<uint64_t, 8> SuccWeights; |
| if (SuccHasWeights) { |
| GetBranchWeights(TI, SuccWeights); |
| // branch-weight metadata is inconsistent here. |
| if (SuccWeights.size() != 1 + BBCases.size()) |
| PredHasWeights = SuccHasWeights = false; |
| } else if (PredHasWeights) |
| SuccWeights.assign(1 + BBCases.size(), 1); |
| |
| if (PredDefault == BB) { |
| // If this is the default destination from PTI, only the edges in TI |
| // that don't occur in PTI, or that branch to BB will be activated. |
| std::set<ConstantInt *, ConstantIntOrdering> PTIHandled; |
| for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| if (PredCases[i].Dest != BB) |
| PTIHandled.insert(PredCases[i].Value); |
| else { |
| // The default destination is BB, we don't need explicit targets. |
| std::swap(PredCases[i], PredCases.back()); |
| |
| if (PredHasWeights || SuccHasWeights) { |
| // Increase weight for the default case. |
| Weights[0] += Weights[i + 1]; |
| std::swap(Weights[i + 1], Weights.back()); |
| Weights.pop_back(); |
| } |
| |
| PredCases.pop_back(); |
| --i; |
| --e; |
| } |
| |
| // Reconstruct the new switch statement we will be building. |
| if (PredDefault != BBDefault) { |
| PredDefault->removePredecessor(Pred); |
| PredDefault = BBDefault; |
| NewSuccessors.push_back(BBDefault); |
| } |
| |
| unsigned CasesFromPred = Weights.size(); |
| uint64_t ValidTotalSuccWeight = 0; |
| for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| if (!PTIHandled.count(BBCases[i].Value) && |
| BBCases[i].Dest != BBDefault) { |
| PredCases.push_back(BBCases[i]); |
| NewSuccessors.push_back(BBCases[i].Dest); |
| if (SuccHasWeights || PredHasWeights) { |
| // The default weight is at index 0, so weight for the ith case |
| // should be at index i+1. Scale the cases from successor by |
| // PredDefaultWeight (Weights[0]). |
| Weights.push_back(Weights[0] * SuccWeights[i + 1]); |
| ValidTotalSuccWeight += SuccWeights[i + 1]; |
| } |
| } |
| |
| if (SuccHasWeights || PredHasWeights) { |
| ValidTotalSuccWeight += SuccWeights[0]; |
| // Scale the cases from predecessor by ValidTotalSuccWeight. |
| for (unsigned i = 1; i < CasesFromPred; ++i) |
| Weights[i] *= ValidTotalSuccWeight; |
| // Scale the default weight by SuccDefaultWeight (SuccWeights[0]). |
| Weights[0] *= SuccWeights[0]; |
| } |
| } else { |
| // If this is not the default destination from PSI, only the edges |
| // in SI that occur in PSI with a destination of BB will be |
| // activated. |
| std::set<ConstantInt *, ConstantIntOrdering> PTIHandled; |
| std::map<ConstantInt *, uint64_t> WeightsForHandled; |
| for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| if (PredCases[i].Dest == BB) { |
| PTIHandled.insert(PredCases[i].Value); |
| |
| if (PredHasWeights || SuccHasWeights) { |
| WeightsForHandled[PredCases[i].Value] = Weights[i + 1]; |
| std::swap(Weights[i + 1], Weights.back()); |
| Weights.pop_back(); |
| } |
| |
| std::swap(PredCases[i], PredCases.back()); |
| PredCases.pop_back(); |
| --i; |
| --e; |
| } |
| |
| // Okay, now we know which constants were sent to BB from the |
| // predecessor. Figure out where they will all go now. |
| for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| if (PTIHandled.count(BBCases[i].Value)) { |
| // If this is one we are capable of getting... |
| if (PredHasWeights || SuccHasWeights) |
| Weights.push_back(WeightsForHandled[BBCases[i].Value]); |
| PredCases.push_back(BBCases[i]); |
| NewSuccessors.push_back(BBCases[i].Dest); |
| PTIHandled.erase( |
| BBCases[i].Value); // This constant is taken care of |
| } |
| |
| // If there are any constants vectored to BB that TI doesn't handle, |
| // they must go to the default destination of TI. |
| for (ConstantInt *I : PTIHandled) { |
| if (PredHasWeights || SuccHasWeights) |
| Weights.push_back(WeightsForHandled[I]); |
| PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault)); |
| NewSuccessors.push_back(BBDefault); |
| } |
| } |
| |
| // Okay, at this point, we know which new successor Pred will get. Make |
| // sure we update the number of entries in the PHI nodes for these |
| // successors. |
| for (BasicBlock *NewSuccessor : NewSuccessors) |
| AddPredecessorToBlock(NewSuccessor, Pred, BB); |
| |
| Builder.SetInsertPoint(PTI); |
| // Convert pointer to int before we switch. |
| if (CV->getType()->isPointerTy()) { |
| CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), |
| "magicptr"); |
| } |
| |
| // Now that the successors are updated, create the new Switch instruction. |
| SwitchInst *NewSI = |
| Builder.CreateSwitch(CV, PredDefault, PredCases.size()); |
| NewSI->setDebugLoc(PTI->getDebugLoc()); |
| for (ValueEqualityComparisonCase &V : PredCases) |
| NewSI->addCase(V.Value, V.Dest); |
| |
| if (PredHasWeights || SuccHasWeights) { |
| // Halve the weights if any of them cannot fit in an uint32_t |
| FitWeights(Weights); |
| |
| SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| |
| setBranchWeights(NewSI, MDWeights); |
| } |
| |
| EraseTerminatorAndDCECond(PTI); |
| |
| // Okay, last check. If BB is still a successor of PSI, then we must |
| // have an infinite loop case. If so, add an infinitely looping block |
| // to handle the case to preserve the behavior of the code. |
| BasicBlock *InfLoopBlock = nullptr; |
| for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) |
| if (NewSI->getSuccessor(i) == BB) { |
| if (!InfLoopBlock) { |
| // Insert it at the end of the function, because it's either code, |
| // or it won't matter if it's hot. :) |
| InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop", |
| BB->getParent()); |
| BranchInst::Create(InfLoopBlock, InfLoopBlock); |
| } |
| NewSI->setSuccessor(i, InfLoopBlock); |
| } |
| |
| Changed = true; |
| } |
| } |
| return Changed; |
| } |
| |
| // If we would need to insert a select that uses the value of this invoke |
| // (comments in HoistThenElseCodeToIf explain why we would need to do this), we |
| // can't hoist the invoke, as there is nowhere to put the select in this case. |
| static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, |
| Instruction *I1, Instruction *I2) { |
| for (BasicBlock *Succ : successors(BB1)) { |
| for (const PHINode &PN : Succ->phis()) { |
| Value *BB1V = PN.getIncomingValueForBlock(BB1); |
| Value *BB2V = PN.getIncomingValueForBlock(BB2); |
| if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) { |
| return false; |
| } |
| } |
| } |
| return true; |
| } |
| |
| static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I); |
| |
| /// Given a conditional branch that goes to BB1 and BB2, hoist any common code |
| /// in the two blocks up into the branch block. The caller of this function |
| /// guarantees that BI's block dominates BB1 and BB2. |
| static bool HoistThenElseCodeToIf(BranchInst *BI, |
| const TargetTransformInfo &TTI) { |
| // This does very trivial matching, with limited scanning, to find identical |
| // instructions in the two blocks. In particular, we don't want to get into |
| // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As |
| // such, we currently just scan for obviously identical instructions in an |
| // identical order. |
| BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. |
| BasicBlock *BB2 = BI->getSuccessor(1); // The false destination |
| |
| BasicBlock::iterator BB1_Itr = BB1->begin(); |
| BasicBlock::iterator BB2_Itr = BB2->begin(); |
| |
| Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++; |
| // Skip debug info if it is not identical. |
| DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); |
| DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); |
| if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { |
| while (isa<DbgInfoIntrinsic>(I1)) |
| I1 = &*BB1_Itr++; |
| while (isa<DbgInfoIntrinsic>(I2)) |
| I2 = &*BB2_Itr++; |
| } |
| // FIXME: Can we define a safety predicate for CallBr? |
| if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) || |
| (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) || |
| isa<CallBrInst>(I1)) |
| return false; |
| |
| BasicBlock *BIParent = BI->getParent(); |
| |
| bool Changed = false; |
| do { |
| // If we are hoisting the terminator instruction, don't move one (making a |
| // broken BB), instead clone it, and remove BI. |
| if (I1->isTerminator()) |
| goto HoistTerminator; |
| |
| // If we're going to hoist a call, make sure that the two instructions we're |
| // commoning/hoisting are both marked with musttail, or neither of them is |
| // marked as such. Otherwise, we might end up in a situation where we hoist |
| // from a block where the terminator is a `ret` to a block where the terminator |
| // is a `br`, and `musttail` calls expect to be followed by a return. |
| auto *C1 = dyn_cast<CallInst>(I1); |
| auto *C2 = dyn_cast<CallInst>(I2); |
| if (C1 && C2) |
| if (C1->isMustTailCall() != C2->isMustTailCall()) |
| return Changed; |
| |
| if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2)) |
| return Changed; |
| |
| if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) { |
| assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2)); |
| // The debug location is an integral part of a debug info intrinsic |
| // and can't be separated from it or replaced. Instead of attempting |
| // to merge locations, simply hoist both copies of the intrinsic. |
| BIParent->getInstList().splice(BI->getIterator(), |
| BB1->getInstList(), I1); |
| BIParent->getInstList().splice(BI->getIterator(), |
| BB2->getInstList(), I2); |
| Changed = true; |
| } else { |
| // For a normal instruction, we just move one to right before the branch, |
| // then replace all uses of the other with the first. Finally, we remove |
| // the now redundant second instruction. |
| BIParent->getInstList().splice(BI->getIterator(), |
| BB1->getInstList(), I1); |
| if (!I2->use_empty()) |
| I2->replaceAllUsesWith(I1); |
| I1->andIRFlags(I2); |
| unsigned KnownIDs[] = {LLVMContext::MD_tbaa, |
| LLVMContext::MD_range, |
| LLVMContext::MD_fpmath, |
| LLVMContext::MD_invariant_load, |
| LLVMContext::MD_nonnull, |
| LLVMContext::MD_invariant_group, |
| LLVMContext::MD_align, |
| LLVMContext::MD_dereferenceable, |
| LLVMContext::MD_dereferenceable_or_null, |
| LLVMContext::MD_mem_parallel_loop_access, |
| LLVMContext::MD_access_group}; |
| combineMetadata(I1, I2, KnownIDs, true); |
| |
| // I1 and I2 are being combined into a single instruction. Its debug |
| // location is the merged locations of the original instructions. |
| I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc()); |
| |
| I2->eraseFromParent(); |
| Changed = true; |
| } |
| |
| I1 = &*BB1_Itr++; |
| I2 = &*BB2_Itr++; |
| // Skip debug info if it is not identical. |
| DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); |
| DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); |
| if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { |
| while (isa<DbgInfoIntrinsic>(I1)) |
| I1 = &*BB1_Itr++; |
| while (isa<DbgInfoIntrinsic>(I2)) |
| I2 = &*BB2_Itr++; |
| } |
| } while (I1->isIdenticalToWhenDefined(I2)); |
| |
| return true; |
| |
| HoistTerminator: |
| // It may not be possible to hoist an invoke. |
| // FIXME: Can we define a safety predicate for CallBr? |
| if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) |
| return Changed; |
| |
| // TODO: callbr hoisting currently disabled pending further study. |
| if (isa<CallBrInst>(I1)) |
| return Changed; |
| |
| for (BasicBlock *Succ : successors(BB1)) { |
| for (PHINode &PN : Succ->phis()) { |
| Value *BB1V = PN.getIncomingValueForBlock(BB1); |
| Value *BB2V = PN.getIncomingValueForBlock(BB2); |
| if (BB1V == BB2V) |
| continue; |
| |
| // Check for passingValueIsAlwaysUndefined here because we would rather |
| // eliminate undefined control flow then converting it to a select. |
| if (passingValueIsAlwaysUndefined(BB1V, &PN) || |
| passingValueIsAlwaysUndefined(BB2V, &PN)) |
| return Changed; |
| |
| if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V)) |
| return Changed; |
| if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V)) |
| return Changed; |
| } |
| } |
| |
| // Okay, it is safe to hoist the terminator. |
| Instruction *NT = I1->clone(); |
| BIParent->getInstList().insert(BI->getIterator(), NT); |
| if (!NT->getType()->isVoidTy()) { |
| I1->replaceAllUsesWith(NT); |
| I2->replaceAllUsesWith(NT); |
| NT->takeName(I1); |
| } |
| |
| // Ensure terminator gets a debug location, even an unknown one, in case |
| // it involves inlinable calls. |
| NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc()); |
| |
| // PHIs created below will adopt NT's merged DebugLoc. |
| IRBuilder<NoFolder> Builder(NT); |
| |
| // Hoisting one of the terminators from our successor is a great thing. |
| // Unfortunately, the successors of the if/else blocks may have PHI nodes in |
| // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI |
| // nodes, so we insert select instruction to compute the final result. |
| std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects; |
| for (BasicBlock *Succ : successors(BB1)) { |
| for (PHINode &PN : Succ->phis()) { |
| Value *BB1V = PN.getIncomingValueForBlock(BB1); |
| Value *BB2V = PN.getIncomingValueForBlock(BB2); |
| if (BB1V == BB2V) |
| continue; |
| |
| // These values do not agree. Insert a select instruction before NT |
| // that determines the right value. |
| SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; |
| if (!SI) |
| SI = cast<SelectInst>( |
| Builder.CreateSelect(BI->getCondition(), BB1V, BB2V, |
| BB1V->getName() + "." + BB2V->getName(), BI)); |
| |
| // Make the PHI node use the select for all incoming values for BB1/BB2 |
| for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) |
| if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2) |
| PN.setIncomingValue(i, SI); |
| } |
| } |
| |
| // Update any PHI nodes in our new successors. |
| for (BasicBlock *Succ : successors(BB1)) |
| AddPredecessorToBlock(Succ, BIParent, BB1); |
| |
| EraseTerminatorAndDCECond(BI); |
| return true; |
| } |
| |
| // All instructions in Insts belong to different blocks that all unconditionally |
| // branch to a common successor. Analyze each instruction and return true if it |
| // would be possible to sink them into their successor, creating one common |
| // instruction instead. For every value that would be required to be provided by |
| // PHI node (because an operand varies in each input block), add to PHIOperands. |
| static bool canSinkInstructions( |
| ArrayRef<Instruction *> Insts, |
| DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) { |
| // Prune out obviously bad instructions to move. Any non-store instruction |
| // must have exactly one use, and we check later that use is by a single, |
| // common PHI instruction in the successor. |
| for (auto *I : Insts) { |
| // These instructions may change or break semantics if moved. |
| if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) || |
| I->getType()->isTokenTy()) |
| return false; |
| |
| // Conservatively return false if I is an inline-asm instruction. Sinking |
| // and merging inline-asm instructions can potentially create arguments |
| // that cannot satisfy the inline-asm constraints. |
| if (const auto *C = dyn_cast<CallBase>(I)) |
| if (C->isInlineAsm()) |
| return false; |
| |
| // Everything must have only one use too, apart from stores which |
| // have no uses. |
| if (!isa<StoreInst>(I) && !I->hasOneUse()) |
| return false; |
| } |
| |
| const Instruction *I0 = Insts.front(); |
| for (auto *I : Insts) |
| if (!I->isSameOperationAs(I0)) |
| return false; |
| |
| // All instructions in Insts are known to be the same opcode. If they aren't |
| // stores, check the only user of each is a PHI or in the same block as the |
| // instruction, because if a user is in the same block as an instruction |
| // we're contemplating sinking, it must already be determined to be sinkable. |
| if (!isa<StoreInst>(I0)) { |
| auto *PNUse = dyn_cast<PHINode>(*I0->user_begin()); |
| auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0); |
| if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool { |
| auto *U = cast<Instruction>(*I->user_begin()); |
| return (PNUse && |
| PNUse->getParent() == Succ && |
| PNUse->getIncomingValueForBlock(I->getParent()) == I) || |
| U->getParent() == I->getParent(); |
| })) |
| return false; |
| } |
| |
| // Because SROA can't handle speculating stores of selects, try not |
| // to sink loads or stores of allocas when we'd have to create a PHI for |
| // the address operand. Also, because it is likely that loads or stores |
| // of allocas will disappear when Mem2Reg/SROA is run, don't sink them. |
| // This can cause code churn which can have unintended consequences down |
| // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244. |
| // FIXME: This is a workaround for a deficiency in SROA - see |
| // https://llvm.org/bugs/show_bug.cgi?id=30188 |
| if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) { |
| return isa<AllocaInst>(I->getOperand(1)); |
| })) |
| return false; |
| if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) { |
| return isa<AllocaInst>(I->getOperand(0)); |
| })) |
| return false; |
| |
| for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) { |
| if (I0->getOperand(OI)->getType()->isTokenTy()) |
| // Don't touch any operand of token type. |
| return false; |
| |
| auto SameAsI0 = [&I0, OI](const Instruction *I) { |
| assert(I->getNumOperands() == I0->getNumOperands()); |
| return I->getOperand(OI) == I0->getOperand(OI); |
| }; |
| if (!all_of(Insts, SameAsI0)) { |
| if (!canReplaceOperandWithVariable(I0, OI)) |
| // We can't create a PHI from this GEP. |
| return false; |
| // Don't create indirect calls! The called value is the final operand. |
| if (isa<CallBase>(I0) && OI == OE - 1) { |
| // FIXME: if the call was *already* indirect, we should do this. |
| return false; |
| } |
| for (auto *I : Insts) |
| PHIOperands[I].push_back(I->getOperand(OI)); |
| } |
| } |
| return true; |
| } |
| |
| // Assuming canSinkLastInstruction(Blocks) has returned true, sink the last |
| // instruction of every block in Blocks to their common successor, commoning |
| // into one instruction. |
| static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) { |
| auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0); |
| |
| // canSinkLastInstruction returning true guarantees that every block has at |
| // least one non-terminator instruction. |
| SmallVector<Instruction*,4> Insts; |
| for (auto *BB : Blocks) { |
| Instruction *I = BB->getTerminator(); |
| do { |
| I = I->getPrevNode(); |
| } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front()); |
| if (!isa<DbgInfoIntrinsic>(I)) |
| Insts.push_back(I); |
| } |
| |
| // The only checking we need to do now is that all users of all instructions |
| // are the same PHI node. canSinkLastInstruction should have checked this but |
| // it is slightly over-aggressive - it gets confused by commutative instructions |
| // so double-check it here. |
| Instruction *I0 = Insts.front(); |
| if (!isa<StoreInst>(I0)) { |
| auto *PNUse = dyn_cast<PHINode>(*I0->user_begin()); |
| if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool { |
| auto *U = cast<Instruction>(*I->user_begin()); |
| return U == PNUse; |
| })) |
| return false; |
| } |
| |
| // We don't need to do any more checking here; canSinkLastInstruction should |
| // have done it all for us. |
| SmallVector<Value*, 4> NewOperands; |
| for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) { |
| // This check is different to that in canSinkLastInstruction. There, we |
| // cared about the global view once simplifycfg (and instcombine) have |
| // completed - it takes into account PHIs that become trivially |
| // simplifiable. However here we need a more local view; if an operand |
| // differs we create a PHI and rely on instcombine to clean up the very |
| // small mess we may make. |
| bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) { |
| return I->getOperand(O) != I0->getOperand(O); |
| }); |
| if (!NeedPHI) { |
| NewOperands.push_back(I0->getOperand(O)); |
| continue; |
| } |
| |
| // Create a new PHI in the successor block and populate it. |
| auto *Op = I0->getOperand(O); |
| assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!"); |
| auto *PN = PHINode::Create(Op->getType(), Insts.size(), |
| Op->getName() + ".sink", &BBEnd->front()); |
| for (auto *I : Insts) |
| PN->addIncoming(I->getOperand(O), I->getParent()); |
| NewOperands.push_back(PN); |
| } |
| |
| // Arbitrarily use I0 as the new "common" instruction; remap its operands |
| // and move it to the start of the successor block. |
| for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) |
| I0->getOperandUse(O).set(NewOperands[O]); |
| I0->moveBefore(&*BBEnd->getFirstInsertionPt()); |
| |
| // Update metadata and IR flags, and merge debug locations. |
| for (auto *I : Insts) |
| if (I != I0) { |
| // The debug location for the "common" instruction is the merged locations |
| // of all the commoned instructions. We start with the original location |
| // of the "common" instruction and iteratively merge each location in the |
| // loop below. |
| // This is an N-way merge, which will be inefficient if I0 is a CallInst. |
| // However, as N-way merge for CallInst is rare, so we use simplified API |
| // instead of using complex API for N-way merge. |
| I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc()); |
| combineMetadataForCSE(I0, I, true); |
| I0->andIRFlags(I); |
| } |
| |
| if (!isa<StoreInst>(I0)) { |
| // canSinkLastInstruction checked that all instructions were used by |
| // one and only one PHI node. Find that now, RAUW it to our common |
| // instruction and nuke it. |
| assert(I0->hasOneUse()); |
| auto *PN = cast<PHINode>(*I0->user_begin()); |
| PN->replaceAllUsesWith(I0); |
| PN->eraseFromParent(); |
| } |
| |
| // Finally nuke all instructions apart from the common instruction. |
| for (auto *I : Insts) |
| if (I != I0) |
| I->eraseFromParent(); |
| |
| return true; |
| } |
| |
| namespace { |
| |
| // LockstepReverseIterator - Iterates through instructions |
| // in a set of blocks in reverse order from the first non-terminator. |
| // For example (assume all blocks have size n): |
| // LockstepReverseIterator I([B1, B2, B3]); |
| // *I-- = [B1[n], B2[n], B3[n]]; |
| // *I-- = [B1[n-1], B2[n-1], B3[n-1]]; |
| // *I-- = [B1[n-2], B2[n-2], B3[n-2]]; |
| // ... |
| class LockstepReverseIterator { |
| ArrayRef<BasicBlock*> Blocks; |
| SmallVector<Instruction*,4> Insts; |
| bool Fail; |
| |
| public: |
| LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) { |
| reset(); |
| } |
| |
| void reset() { |
| Fail = false; |
| Insts.clear(); |
| for (auto *BB : Blocks) { |
| Instruction *Inst = BB->getTerminator(); |
| for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);) |
| Inst = Inst->getPrevNode(); |
| if (!Inst) { |
| // Block wasn't big enough. |
| Fail = true; |
| return; |
| } |
| Insts.push_back(Inst); |
| } |
| } |
| |
| bool isValid() const { |
| return !Fail; |
| } |
| |
| void operator--() { |
| if (Fail) |
| return; |
| for (auto *&Inst : Insts) { |
| for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);) |
| Inst = Inst->getPrevNode(); |
| // Already at beginning of block. |
| if (!Inst) { |
| Fail = true; |
| return; |
| } |
| } |
| } |
| |
| ArrayRef<Instruction*> operator * () const { |
| return Insts; |
| } |
| }; |
| |
| } // end anonymous namespace |
| |
| /// Check whether BB's predecessors end with unconditional branches. If it is |
| /// true, sink any common code from the predecessors to BB. |
| /// We also allow one predecessor to end with conditional branch (but no more |
| /// than one). |
| static bool SinkCommonCodeFromPredecessors(BasicBlock *BB) { |
| // We support two situations: |
| // (1) all incoming arcs are unconditional |
| // (2) one incoming arc is conditional |
| // |
| // (2) is very common in switch defaults and |
| // else-if patterns; |
| // |
| // if (a) f(1); |
| // else if (b) f(2); |
| // |
| // produces: |
| // |
| // [if] |
| // / \ |
| // [f(1)] [if] |
| // | | \ |
| // | | | |
| // | [f(2)]| |
| // \ | / |
| // [ end ] |
| // |
| // [end] has two unconditional predecessor arcs and one conditional. The |
| // conditional refers to the implicit empty 'else' arc. This conditional |
| // arc can also be caused by an empty default block in a switch. |
| // |
| // In this case, we attempt to sink code from all *unconditional* arcs. |
| // If we can sink instructions from these arcs (determined during the scan |
| // phase below) we insert a common successor for all unconditional arcs and |
| // connect that to [end], to enable sinking: |
| // |
| // [if] |
| // / \ |
| // [x(1)] [if] |
| // | | \ |
| // | | \ |
| // | [x(2)] | |
| // \ / | |
| // [sink.split] | |
| // \ / |
| // [ end ] |
| // |
| SmallVector<BasicBlock*,4> UnconditionalPreds; |
| Instruction *Cond = nullptr; |
| for (auto *B : predecessors(BB)) { |
| auto *T = B->getTerminator(); |
| if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional()) |
| UnconditionalPreds.push_back(B); |
| else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond) |
| Cond = T; |
| else |
| return false; |
| } |
| if (UnconditionalPreds.size() < 2) |
| return false; |
| |
| bool Changed = false; |
| // We take a two-step approach to tail sinking. First we scan from the end of |
| // each block upwards in lockstep. If the n'th instruction from the end of each |
| // block can be sunk, those instructions are added to ValuesToSink and we |
| // carry on. If we can sink an instruction but need to PHI-merge some operands |
| // (because they're not identical in each instruction) we add these to |
| // PHIOperands. |
| unsigned ScanIdx = 0; |
| SmallPtrSet<Value*,4> InstructionsToSink; |
| DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands; |
| LockstepReverseIterator LRI(UnconditionalPreds); |
| while (LRI.isValid() && |
| canSinkInstructions(*LRI, PHIOperands)) { |
| LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0] |
| << "\n"); |
| InstructionsToSink.insert((*LRI).begin(), (*LRI).end()); |
| ++ScanIdx; |
| --LRI; |
| } |
| |
| auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) { |
| unsigned NumPHIdValues = 0; |
| for (auto *I : *LRI) |
| for (auto *V : PHIOperands[I]) |
| if (InstructionsToSink.count(V) == 0) |
| ++NumPHIdValues; |
| LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n"); |
| unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size(); |
| if ((NumPHIdValues % UnconditionalPreds.size()) != 0) |
| NumPHIInsts++; |
| |
| return NumPHIInsts <= 1; |
| }; |
| |
| if (ScanIdx > 0 && Cond) { |
| // Check if we would actually sink anything first! This mutates the CFG and |
| // adds an extra block. The goal in doing this is to allow instructions that |
| // couldn't be sunk before to be sunk - obviously, speculatable instructions |
| // (such as trunc, add) can be sunk and predicated already. So we check that |
| // we're going to sink at least one non-speculatable instruction. |
| LRI.reset(); |
| unsigned Idx = 0; |
| bool Profitable = false; |
| while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) { |
| if (!isSafeToSpeculativelyExecute((*LRI)[0])) { |
| Profitable = true; |
| break; |
| } |
| --LRI; |
| ++Idx; |
| } |
| if (!Profitable) |
| return false; |
| |
| LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n"); |
| // We have a conditional edge and we're going to sink some instructions. |
| // Insert a new block postdominating all blocks we're going to sink from. |
| if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split")) |
| // Edges couldn't be split. |
| return false; |
| Changed = true; |
| } |
| |
| // Now that we've analyzed all potential sinking candidates, perform the |
| // actual sink. We iteratively sink the last non-terminator of the source |
| // blocks into their common successor unless doing so would require too |
| // many PHI instructions to be generated (currently only one PHI is allowed |
| // per sunk instruction). |
| // |
| // We can use InstructionsToSink to discount values needing PHI-merging that will |
| // actually be sunk in a later iteration. This allows us to be more |
| // aggressive in what we sink. This does allow a false positive where we |
| // sink presuming a later value will also be sunk, but stop half way through |
| // and never actually sink it which means we produce more PHIs than intended. |
| // This is unlikely in practice though. |
| for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) { |
| LLVM_DEBUG(dbgs() << "SINK: Sink: " |
| << *UnconditionalPreds[0]->getTerminator()->getPrevNode() |
| << "\n"); |
| |
| // Because we've sunk every instruction in turn, the current instruction to |
| // sink is always at index 0. |
| LRI.reset(); |
| if (!ProfitableToSinkInstruction(LRI)) { |
| // Too many PHIs would be created. |
| LLVM_DEBUG( |
| dbgs() << "SINK: stopping here, too many PHIs would be created!\n"); |
| break; |
| } |
| |
| if (!sinkLastInstruction(UnconditionalPreds)) |
| return Changed; |
| NumSinkCommons++; |
| Changed = true; |
| } |
| return Changed; |
| } |
| |
| /// Determine if we can hoist sink a sole store instruction out of a |
| /// conditional block. |
| /// |
| /// We are looking for code like the following: |
| /// BrBB: |
| /// store i32 %add, i32* %arrayidx2 |
| /// ... // No other stores or function calls (we could be calling a memory |
| /// ... // function). |
| /// %cmp = icmp ult %x, %y |
| /// br i1 %cmp, label %EndBB, label %ThenBB |
| /// ThenBB: |
| /// store i32 %add5, i32* %arrayidx2 |
| /// br label EndBB |
| /// EndBB: |
| /// ... |
| /// We are going to transform this into: |
| /// BrBB: |
| /// store i32 %add, i32* %arrayidx2 |
| /// ... // |
| /// %cmp = icmp ult %x, %y |
| /// %add.add5 = select i1 %cmp, i32 %add, %add5 |
| /// store i32 %add.add5, i32* %arrayidx2 |
| /// ... |
| /// |
| /// \return The pointer to the value of the previous store if the store can be |
| /// hoisted into the predecessor block. 0 otherwise. |
| static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, |
| BasicBlock *StoreBB, BasicBlock *EndBB) { |
| StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); |
| if (!StoreToHoist) |
| return nullptr; |
| |
| // Volatile or atomic. |
| if (!StoreToHoist->isSimple()) |
| return nullptr; |
| |
| Value *StorePtr = StoreToHoist->getPointerOperand(); |
| |
| // Look for a store to the same pointer in BrBB. |
| unsigned MaxNumInstToLookAt = 9; |
| for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug())) { |
| if (!MaxNumInstToLookAt) |
| break; |
| --MaxNumInstToLookAt; |
| |
| // Could be calling an instruction that affects memory like free(). |
| if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI)) |
| return nullptr; |
| |
| if (auto *SI = dyn_cast<StoreInst>(&CurI)) { |
| // Found the previous store make sure it stores to the same location. |
| if (SI->getPointerOperand() == StorePtr) |
| // Found the previous store, return its value operand. |
| return SI->getValueOperand(); |
| return nullptr; // Unknown store. |
| } |
| } |
| |
| return nullptr; |
| } |
| |
| /// Speculate a conditional basic block flattening the CFG. |
| /// |
| /// Note that this is a very risky transform currently. Speculating |
| /// instructions like this is most often not desirable. Instead, there is an MI |
| /// pass which can do it with full awareness of the resource constraints. |
| /// However, some cases are "obvious" and we should do directly. An example of |
| /// this is speculating a single, reasonably cheap instruction. |
| /// |
| /// There is only one distinct advantage to flattening the CFG at the IR level: |
| /// it makes very common but simplistic optimizations such as are common in |
| /// instcombine and the DAG combiner more powerful by removing CFG edges and |
| /// modeling their effects with easier to reason about SSA value graphs. |
| /// |
| /// |
| /// An illustration of this transform is turning this IR: |
| /// \code |
| /// BB: |
| /// %cmp = icmp ult %x, %y |
| /// br i1 %cmp, label %EndBB, label %ThenBB |
| /// ThenBB: |
| /// %sub = sub %x, %y |
| /// br label BB2 |
| /// EndBB: |
| /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] |
| /// ... |
| /// \endcode |
| /// |
| /// Into this IR: |
| /// \code |
| /// BB: |
| /// %cmp = icmp ult %x, %y |
| /// %sub = sub %x, %y |
| /// %cond = select i1 %cmp, 0, %sub |
| /// ... |
| /// \endcode |
| /// |
| /// \returns true if the conditional block is removed. |
| static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, |
| const TargetTransformInfo &TTI) { |
| // Be conservative for now. FP select instruction can often be expensive. |
| Value *BrCond = BI->getCondition(); |
| if (isa<FCmpInst>(BrCond)) |
| return false; |
| |
| BasicBlock *BB = BI->getParent(); |
| BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); |
| |
| // If ThenBB is actually on the false edge of the conditional branch, remember |
| // to swap the select operands later. |
| bool Invert = false; |
| if (ThenBB != BI->getSuccessor(0)) { |
| assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); |
| Invert = true; |
| } |
| assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); |
| |
| // Keep a count of how many times instructions are used within ThenBB when |
| // they are candidates for sinking into ThenBB. Specifically: |
| // - They are defined in BB, and |
| // - They have no side effects, and |
| // - All of their uses are in ThenBB. |
| SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; |
| |
| SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics; |
| |
| unsigned SpeculationCost = 0; |
| Value *SpeculatedStoreValue = nullptr; |
| StoreInst *SpeculatedStore = nullptr; |
| for (BasicBlock::iterator BBI = ThenBB->begin(), |
| BBE = std::prev(ThenBB->end()); |
| BBI != BBE; ++BBI) { |
| Instruction *I = &*BBI; |
| // Skip debug info. |
| if (isa<DbgInfoIntrinsic>(I)) { |
| SpeculatedDbgIntrinsics.push_back(I); |
| continue; |
| } |
| |
| // Only speculatively execute a single instruction (not counting the |
| // terminator) for now. |
| ++SpeculationCost; |
| if (SpeculationCost > 1) |
| return false; |
| |
| // Don't hoist the instruction if it's unsafe or expensive. |
| if (!isSafeToSpeculativelyExecute(I) && |
| !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore( |
| I, BB, ThenBB, EndBB)))) |
| return false; |
| if (!SpeculatedStoreValue && |
| ComputeSpeculationCost(I, TTI) > |
| PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic) |
| return false; |
| |
| // Store the store speculation candidate. |
| if (SpeculatedStoreValue) |
| SpeculatedStore = cast<StoreInst>(I); |
| |
| // Do not hoist the instruction if any of its operands are defined but not |
| // used in BB. The transformation will prevent the operand from |
| // being sunk into the use block. |
| for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) { |
| Instruction *OpI = dyn_cast<Instruction>(*i); |
| if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects()) |
| continue; // Not a candidate for sinking. |
| |
| ++SinkCandidateUseCounts[OpI]; |
| } |
| } |
| |
| // Consider any sink candidates which are only used in ThenBB as costs for |
| // speculation. Note, while we iterate over a DenseMap here, we are summing |
| // and so iteration order isn't significant. |
| for (SmallDenseMap<Instruction *, unsigned, 4>::iterator |
| I = SinkCandidateUseCounts.begin(), |
| E = SinkCandidateUseCounts.end(); |
| I != E; ++I) |
| if (I->first->hasNUses(I->second)) { |
| ++SpeculationCost; |
| if (SpeculationCost > 1) |
| return false; |
| } |
| |
| // Check that the PHI nodes can be converted to selects. |
| bool HaveRewritablePHIs = false; |
| for (PHINode &PN : EndBB->phis()) { |
| Value *OrigV = PN.getIncomingValueForBlock(BB); |
| Value *ThenV = PN.getIncomingValueForBlock(ThenBB); |
| |
| // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf. |
| // Skip PHIs which are trivial. |
| if (ThenV == OrigV) |
| continue; |
| |
| // Don't convert to selects if we could remove undefined behavior instead. |
| if (passingValueIsAlwaysUndefined(OrigV, &PN) || |
| passingValueIsAlwaysUndefined(ThenV, &PN)) |
| return false; |
| |
| HaveRewritablePHIs = true; |
| ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV); |
| ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV); |
| if (!OrigCE && !ThenCE) |
| continue; // Known safe and cheap. |
| |
| if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) || |
| (OrigCE && !isSafeToSpeculativelyExecute(OrigCE))) |
| return false; |
| unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0; |
| unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0; |
| unsigned MaxCost = |
| 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; |
| if (OrigCost + ThenCost > MaxCost) |
| return false; |
| |
| // Account for the cost of an unfolded ConstantExpr which could end up |
| // getting expanded into Instructions. |
| // FIXME: This doesn't account for how many operations are combined in the |
| // constant expression. |
| ++SpeculationCost; |
| if (SpeculationCost > 1) |
| return false; |
| } |
| |
| // If there are no PHIs to process, bail early. This helps ensure idempotence |
| // as well. |
| if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue)) |
| return false; |
| |
| // If we get here, we can hoist the instruction and if-convert. |
| LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); |
| |
| // Insert a select of the value of the speculated store. |
| if (SpeculatedStoreValue) { |
| IRBuilder<NoFolder> Builder(BI); |
| Value *TrueV = SpeculatedStore->getValueOperand(); |
| Value *FalseV = SpeculatedStoreValue; |
| if (Invert) |
| std::swap(TrueV, FalseV); |
| Value *S = Builder.CreateSelect( |
| BrCond, TrueV, FalseV, "spec.store.select", BI); |
| SpeculatedStore->setOperand(0, S); |
| SpeculatedStore->applyMergedLocation(BI->getDebugLoc(), |
| SpeculatedStore->getDebugLoc()); |
| } |
| |
| // Metadata can be dependent on the condition we are hoisting above. |
| // Conservatively strip all metadata on the instruction. |
| for (auto &I : *ThenBB) |
| I.dropUnknownNonDebugMetadata(); |
| |
| // Hoist the instructions. |
| BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(), |
| ThenBB->begin(), std::prev(ThenBB->end())); |
| |
| // Insert selects and rewrite the PHI operands. |
| IRBuilder<NoFolder> Builder(BI); |
| for (PHINode &PN : EndBB->phis()) { |
| unsigned OrigI = PN.getBasicBlockIndex(BB); |
| unsigned ThenI = PN.getBasicBlockIndex(ThenBB); |
| Value *OrigV = PN.getIncomingValue(OrigI); |
| Value *ThenV = PN.getIncomingValue(ThenI); |
| |
| // Skip PHIs which are trivial. |
| if (OrigV == ThenV) |
| continue; |
| |
| // Create a select whose true value is the speculatively executed value and |
| // false value is the preexisting value. Swap them if the branch |
| // destinations were inverted. |
| Value *TrueV = ThenV, *FalseV = OrigV; |
| if (Invert) |
| std::swap(TrueV, FalseV); |
| Value *V = Builder.CreateSelect( |
| BrCond, TrueV, FalseV, "spec.select", BI); |
| PN.setIncomingValue(OrigI, V); |
| PN.setIncomingValue(ThenI, V); |
| } |
| |
| // Remove speculated dbg intrinsics. |
| // FIXME: Is it possible to do this in a more elegant way? Moving/merging the |
| // dbg value for the different flows and inserting it after the select. |
| for (Instruction *I : SpeculatedDbgIntrinsics) |
| I->eraseFromParent(); |
| |
| ++NumSpeculations; |
| return true; |
| } |
| |
| /// Return true if we can thread a branch across this block. |
| static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { |
| unsigned Size = 0; |
| |
| for (Instruction &I : BB->instructionsWithoutDebug()) { |
| if (Size > 10) |
| return false; // Don't clone large BB's. |
| ++Size; |
| |
| // We can only support instructions that do not define values that are |
| // live outside of the current basic block. |
| for (User *U : I.users()) { |
| Instruction *UI = cast<Instruction>(U); |
| if (UI->getParent() != BB || isa<PHINode>(UI)) |
| return false; |
| } |
| |
| // Looks ok, continue checking. |
| } |
| |
| return true; |
| } |
| |
| /// If we have a conditional branch on a PHI node value that is defined in the |
| /// same block as the branch and if any PHI entries are constants, thread edges |
| /// corresponding to that entry to be branches to their ultimate destination. |
| static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL, |
| AssumptionCache *AC) { |
| BasicBlock *BB = BI->getParent(); |
| PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); |
| // NOTE: we currently cannot transform this case if the PHI node is used |
| // outside of the block. |
| if (!PN || PN->getParent() != BB || !PN->hasOneUse()) |
| return false; |
| |
| // Degenerate case of a single entry PHI. |
| if (PN->getNumIncomingValues() == 1) { |
| FoldSingleEntryPHINodes(PN->getParent()); |
| return true; |
| } |
| |
| // Now we know that this block has multiple preds and two succs. |
| if (!BlockIsSimpleEnoughToThreadThrough(BB)) |
| return false; |
| |
| // Can't fold blocks that contain noduplicate or convergent calls. |
| if (any_of(*BB, [](const Instruction &I) { |
| const CallInst *CI = dyn_cast<CallInst>(&I); |
| return CI && (CI->cannotDuplicate() || CI->isConvergent()); |
| })) |
| return false; |
| |
| // Okay, this is a simple enough basic block. See if any phi values are |
| // constants. |
| for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); |
| if (!CB || !CB->getType()->isIntegerTy(1)) |
| continue; |
| |
| // Okay, we now know that all edges from PredBB should be revectored to |
| // branch to RealDest. |
| BasicBlock *PredBB = PN->getIncomingBlock(i); |
| BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); |
| |
| if (RealDest == BB) |
| continue; // Skip self loops. |
| // Skip if the predecessor's terminator is an indirect branch. |
| if (isa<IndirectBrInst>(PredBB->getTerminator())) |
| continue; |
| |
| // The dest block might have PHI nodes, other predecessors and other |
| // difficult cases. Instead of being smart about this, just insert a new |
| // block that jumps to the destination block, effectively splitting |
| // the edge we are about to create. |
| BasicBlock *EdgeBB = |
| BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge", |
| RealDest->getParent(), RealDest); |
| BranchInst::Create(RealDest, EdgeBB); |
| |
| // Update PHI nodes. |
| AddPredecessorToBlock(RealDest, EdgeBB, BB); |
| |
| // BB may have instructions that are being threaded over. Clone these |
| // instructions into EdgeBB. We know that there will be no uses of the |
| // cloned instructions outside of EdgeBB. |
| BasicBlock::iterator InsertPt = EdgeBB->begin(); |
| DenseMap<Value *, Value *> TranslateMap; // Track translated values. |
| for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { |
| if (PHINode *PN = dyn_cast<PHINode>(BBI)) { |
| TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); |
| continue; |
| } |
| // Clone the instruction. |
| Instruction *N = BBI->clone(); |
| if (BBI->hasName()) |
| N->setName(BBI->getName() + ".c"); |
| |
| // Update operands due to translation. |
| for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) { |
| DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i); |
| if (PI != TranslateMap.end()) |
| *i = PI->second; |
| } |
| |
| // Check for trivial simplification. |
| if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) { |
| if (!BBI->use_empty()) |
| TranslateMap[&*BBI] = V; |
| if (!N->mayHaveSideEffects()) { |
| N->deleteValue(); // Instruction folded away, don't need actual inst |
| N = nullptr; |
| } |
| } else { |
| if (!BBI->use_empty()) |
| TranslateMap[&*BBI] = N; |
| } |
| // Insert the new instruction into its new home. |
| if (N) |
| EdgeBB->getInstList().insert(InsertPt, N); |
| |
| // Register the new instruction with the assumption cache if necessary. |
| if (auto *II = dyn_cast_or_null<IntrinsicInst>(N)) |
| if (II->getIntrinsicID() == Intrinsic::assume) |
| AC->registerAssumption(II); |
| } |
| |
| // Loop over all of the edges from PredBB to BB, changing them to branch |
| // to EdgeBB instead. |
| Instruction *PredBBTI = PredBB->getTerminator(); |
| for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) |
| if (PredBBTI->getSuccessor(i) == BB) { |
| BB->removePredecessor(PredBB); |
| PredBBTI->setSuccessor(i, EdgeBB); |
| } |
| |
| // Recurse, simplifying any other constants. |
| return FoldCondBranchOnPHI(BI, DL, AC) || true; |
| } |
| |
| return false; |
| } |
| |
| /// Given a BB that starts with the specified two-entry PHI node, |
| /// see if we can eliminate it. |
| static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, |
| const DataLayout &DL) { |
| // Ok, this is a two entry PHI node. Check to see if this is a simple "if |
| // statement", which has a very simple dominance structure. Basically, we |
| // are trying to find the condition that is being branched on, which |
| // subsequently causes this merge to happen. We really want control |
| // dependence information for this check, but simplifycfg can't keep it up |
| // to date, and this catches most of the cases we care about anyway. |
| BasicBlock *BB = PN->getParent(); |
| const Function *Fn = BB->getParent(); |
| if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing)) |
| return false; |
| |
| BasicBlock *IfTrue, *IfFalse; |
| Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); |
| if (!IfCond || |
| // Don't bother if the branch will be constant folded trivially. |
| isa<ConstantInt>(IfCond)) |
| return false; |
| |
| // Okay, we found that we can merge this two-entry phi node into a select. |
| // Doing so would require us to fold *all* two entry phi nodes in this block. |
| // At some point this becomes non-profitable (particularly if the target |
| // doesn't support cmov's). Only do this transformation if there are two or |
| // fewer PHI nodes in this block. |
| unsigned NumPhis = 0; |
| for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) |
| if (NumPhis > 2) |
| return false; |
| |
| // Loop over the PHI's seeing if we can promote them all to select |
| // instructions. While we are at it, keep track of the instructions |
| // that need to be moved to the dominating block. |
| SmallPtrSet<Instruction *, 4> AggressiveInsts; |
| unsigned MaxCostVal0 = PHINodeFoldingThreshold, |
| MaxCostVal1 = PHINodeFoldingThreshold; |
| MaxCostVal0 *= TargetTransformInfo::TCC_Basic; |
| MaxCostVal1 *= TargetTransformInfo::TCC_Basic; |
| |
| for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { |
| PHINode *PN = cast<PHINode>(II++); |
| if (Value *V = SimplifyInstruction(PN, {DL, PN})) { |
| PN->replaceAllUsesWith(V); |
| PN->eraseFromParent(); |
| continue; |
| } |
| |
| if (!DominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts, |
| MaxCostVal0, TTI) || |
| !DominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts, |
| MaxCostVal1, TTI)) |
| return false; |
| } |
| |
| // If we folded the first phi, PN dangles at this point. Refresh it. If |
| // we ran out of PHIs then we simplified them all. |
| PN = dyn_cast<PHINode>(BB->begin()); |
| if (!PN) |
| return true; |
| |
| // Don't fold i1 branches on PHIs which contain binary operators. These can |
| // often be turned into switches and other things. |
| if (PN->getType()->isIntegerTy(1) && |
| (isa<BinaryOperator>(PN->getIncomingValue(0)) || |
| isa<BinaryOperator>(PN->getIncomingValue(1)) || |
| isa<BinaryOperator>(IfCond))) |
| return false; |
| |
| // If all PHI nodes are promotable, check to make sure that all instructions |
| // in the predecessor blocks can be promoted as well. If not, we won't be able |
| // to get rid of the control flow, so it's not worth promoting to select |
| // instructions. |
| BasicBlock *DomBlock = nullptr; |
| BasicBlock *IfBlock1 = PN->getIncomingBlock(0); |
| BasicBlock *IfBlock2 = PN->getIncomingBlock(1); |
| if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) { |
| IfBlock1 = nullptr; |
| } else { |
| DomBlock = *pred_begin(IfBlock1); |
| for (BasicBlock::iterator I = IfBlock1->begin(); !I->isTerminator(); ++I) |
| if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { |
| // This is not an aggressive instruction that we can promote. |
| // Because of this, we won't be able to get rid of the control flow, so |
| // the xform is not worth it. |
| return false; |
| } |
| } |
| |
| if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) { |
| IfBlock2 = nullptr; |
| } else { |
| DomBlock = *pred_begin(IfBlock2); |
| for (BasicBlock::iterator I = IfBlock2->begin(); !I->isTerminator(); ++I) |
| if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { |
| // This is not an aggressive instruction that we can promote. |
| // Because of this, we won't be able to get rid of the control flow, so |
| // the xform is not worth it. |
| return false; |
| } |
| } |
| |
| LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond |
| << " T: " << IfTrue->getName() |
| << " F: " << IfFalse->getName() << "\n"); |
| |
| // If we can still promote the PHI nodes after this gauntlet of tests, |
| // do all of the PHI's now. |
| Instruction *InsertPt = DomBlock->getTerminator(); |
| IRBuilder<NoFolder> Builder(InsertPt); |
| |
| // Move all 'aggressive' instructions, which are defined in the |
| // conditional parts of the if's up to the dominating block. |
| if (IfBlock1) |
| hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock1); |
| if (IfBlock2) |
| hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock2); |
| |
| while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { |
| // Change the PHI node into a select instruction. |
| Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); |
| Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); |
| |
| Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt); |
| PN->replaceAllUsesWith(Sel); |
| Sel->takeName(PN); |
| PN->eraseFromParent(); |
| } |
| |
| // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement |
| // has been flattened. Change DomBlock to jump directly to our new block to |
| // avoid other simplifycfg's kicking in on the diamond. |
| Instruction *OldTI = DomBlock->getTerminator(); |
| Builder.SetInsertPoint(OldTI); |
| Builder.CreateBr(BB); |
| OldTI->eraseFromParent(); |
| return true; |
| } |
| |
| /// If we found a conditional branch that goes to two returning blocks, |
| /// try to merge them together into one return, |
| /// introducing a select if the return values disagree. |
| static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, |
| IRBuilder<> &Builder) { |
| assert(BI->isConditional() && "Must be a conditional branch"); |
| BasicBlock *TrueSucc = BI->getSuccessor(0); |
| BasicBlock *FalseSucc = BI->getSuccessor(1); |
| ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); |
| ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); |
| |
| // Check to ensure both blocks are empty (just a return) or optionally empty |
| // with PHI nodes. If there are other instructions, merging would cause extra |
| // computation on one path or the other. |
| if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) |
| return false; |
| if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) |
| return false; |
| |
| Builder.SetInsertPoint(BI); |
| // Okay, we found a branch that is going to two return nodes. If |
| // there is no return value for this function, just change the |
| // branch into a return. |
| if (FalseRet->getNumOperands() == 0) { |
| TrueSucc->removePredecessor(BI->getParent()); |
| FalseSucc->removePredecessor(BI->getParent()); |
| Builder.CreateRetVoid(); |
| EraseTerminatorAndDCECond(BI); |
| return true; |
| } |
| |
| // Otherwise, figure out what the true and false return values are |
| // so we can insert a new select instruction. |
| Value *TrueValue = TrueRet->getReturnValue(); |
| Value *FalseValue = FalseRet->getReturnValue(); |
| |
| // Unwrap any PHI nodes in the return blocks. |
| if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) |
| if (TVPN->getParent() == TrueSucc) |
| TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); |
| if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) |
| if (FVPN->getParent() == FalseSucc) |
| FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); |
| |
| // In order for this transformation to be safe, we must be able to |
| // unconditionally execute both operands to the return. This is |
| // normally the case, but we could have a potentially-trapping |
| // constant expression that prevents this transformation from being |
| // safe. |
| if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) |
| if (TCV->canTrap()) |
| return false; |
| if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) |
| if (FCV->canTrap()) |
| return false; |
| |
| // Okay, we collected all the mapped values and checked them for sanity, and |
| // defined to really do this transformation. First, update the CFG. |
| TrueSucc->removePredecessor(BI->getParent()); |
| FalseSucc->removePredecessor(BI->getParent()); |
| |
| // Insert select instructions where needed. |
| Value *BrCond = BI->getCondition(); |
| if (TrueValue) { |
| // Insert a select if the results differ. |
| if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { |
| } else if (isa<UndefValue>(TrueValue)) { |
| TrueValue = FalseValue; |
| } else { |
| TrueValue = |
| Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI); |
| } |
| } |
| |
| Value *RI = |
| !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); |
| |
| (void)RI; |
| |
| LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" |
| << "\n " << *BI << "NewRet = " << *RI << "TRUEBLOCK: " |
| << *TrueSucc << "FALSEBLOCK: " << *FalseSucc); |
| |
| EraseTerminatorAndDCECond(BI); |
| |
| return true; |
| } |
| |
| /// Return true if the given instruction is available |
| /// in its predecessor block. If yes, the instruction will be removed. |
| static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB) { |
| if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) |
| return false; |
| for (Instruction &I : *PB) { |
| Instruction *PBI = &I; |
| // Check whether Inst and PBI generate the same value. |
| if (Inst->isIdenticalTo(PBI)) { |
| Inst->replaceAllUsesWith(PBI); |
| Inst->eraseFromParent(); |
| return true; |
| } |
| } |
| return false; |
| } |
| |
| /// Return true if either PBI or BI has branch weight available, and store |
| /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does |
| /// not have branch weight, use 1:1 as its weight. |
| static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, |
| uint64_t &PredTrueWeight, |
| uint64_t &PredFalseWeight, |
| uint64_t &SuccTrueWeight, |
| uint64_t &SuccFalseWeight) { |
| bool PredHasWeights = |
| PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight); |
| bool SuccHasWeights = |
| BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight); |
| if (PredHasWeights || SuccHasWeights) { |
| if (!PredHasWeights) |
| PredTrueWeight = PredFalseWeight = 1; |
| if (!SuccHasWeights) |
| SuccTrueWeight = SuccFalseWeight = 1; |
| return true; |
| } else { |
| return false; |
| } |
| } |
| |
| /// If this basic block is simple enough, and if a predecessor branches to us |
| /// and one of our successors, fold the block into the predecessor and use |
| /// logical operations to pick the right destination. |
| bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) { |
| BasicBlock *BB = BI->getParent(); |
| |
| const unsigned PredCount = pred_size(BB); |
| |
| Instruction *Cond = nullptr; |
| if (BI->isConditional()) |
| Cond = dyn_cast<Instruction>(BI->getCondition()); |
| else { |
| // For unconditional branch, check for a simple CFG pattern, where |
| // BB has a single predecessor and BB's successor is also its predecessor's |
| // successor. If such pattern exists, check for CSE between BB and its |
| // predecessor. |
| if (BasicBlock *PB = BB->getSinglePredecessor()) |
| if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) |
| if (PBI->isConditional() && |
| (BI->getSuccessor(0) == PBI->getSuccessor(0) || |
| BI->getSuccessor(0) == PBI->getSuccessor(1))) { |
| for (auto I = BB->instructionsWithoutDebug().begin(), |
| E = BB->instructionsWithoutDebug().end(); |
| I != E;) { |
| Instruction *Curr = &*I++; |
| if (isa<CmpInst>(Curr)) { |
| Cond = Curr; |
| break; |
| } |
| // Quit if we can't remove this instruction. |
| if (!tryCSEWithPredecessor(Curr, PB)) |
| return false; |
| } |
| } |
| |
| if (!Cond) |
| return false; |
| } |
| |
| if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || |
| Cond->getParent() != BB || !Cond->hasOneUse()) |
| return false; |
| |
| // Make sure the instruction after the condition is the cond branch. |
| BasicBlock::iterator CondIt = ++Cond->getIterator(); |
| |
| // Ignore dbg intrinsics. |
| while (isa<DbgInfoIntrinsic>(CondIt)) |
| ++CondIt; |
| |
| if (&*CondIt != BI) |
| return false; |
| |
| // Only allow this transformation if computing the condition doesn't involve |
| // too many instructions and these involved instructions can be executed |
| // unconditionally. We denote all involved instructions except the condition |
| // as "bonus instructions", and only allow this transformation when the |
| // number of the bonus instructions we'll need to create when cloning into |
| // each predecessor does not exceed a certain threshold. |
| unsigned NumBonusInsts = 0; |
| for (auto I = BB->begin(); Cond != &*I; ++I) { |
| // Ignore dbg intrinsics. |
| if (isa<DbgInfoIntrinsic>(I)) |
| continue; |
| if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I)) |
| return false; |
| // I has only one use and can be executed unconditionally. |
| Instruction *User = dyn_cast<Instruction>(I->user_back()); |
| if (User == nullptr || User->getParent() != BB) |
| return false; |
| // I is used in the same BB. Since BI uses Cond and doesn't have more slots |
| // to use any other instruction, User must be an instruction between next(I) |
| // and Cond. |
| |
| // Account for the cost of duplicating this instruction into each |
| // predecessor. |
| NumBonusInsts += PredCount; |
| // Early exits once we reach the limit. |
| if (NumBonusInsts > BonusInstThreshold) |
| return false; |
| } |
| |
| // Cond is known to be a compare or binary operator. Check to make sure that |
| // neither operand is a potentially-trapping constant expression. |
| if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) |
| if (CE->canTrap()) |
| return false; |
| if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) |
| if (CE->canTrap()) |
| return false; |
| |
| // Finally, don't infinitely unroll conditional loops. |
| BasicBlock *TrueDest = BI->getSuccessor(0); |
| BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr; |
| if (TrueDest == BB || FalseDest == BB) |
| return false; |
| |
| for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| BasicBlock *PredBlock = *PI; |
| BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); |
| |
| // Check that we have two conditional branches. If there is a PHI node in |
| // the common successor, verify that the same value flows in from both |
| // blocks. |
| SmallVector<PHINode *, 4> PHIs; |
| if (!PBI || PBI->isUnconditional() || |
| (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) || |
| (!BI->isConditional() && |
| !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) |
| continue; |
| |
| // Determine if the two branches share a common destination. |
| Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; |
| bool InvertPredCond = false; |
| |
| if (BI->isConditional()) { |
| if (PBI->getSuccessor(0) == TrueDest) { |
| Opc = Instruction::Or; |
| } else if (PBI->getSuccessor(1) == FalseDest) { |
| Opc = Instruction::And; |
| } else if (PBI->getSuccessor(0) == FalseDest) { |
| Opc = Instruction::And; |
| InvertPredCond = true; |
| } else if (PBI->getSuccessor(1) == TrueDest) { |
| Opc = Instruction::Or; |
| InvertPredCond = true; |
| } else { |
| continue; |
| } |
| } else { |
| if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) |
| continue; |
| } |
| |
| LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); |
| IRBuilder<> Builder(PBI); |
| |
| // If we need to invert the condition in the pred block to match, do so now. |
| if (InvertPredCond) { |
| Value *NewCond = PBI->getCondition(); |
| |
| if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { |
| CmpInst *CI = cast<CmpInst>(NewCond); |
| CI->setPredicate(CI->getInversePredicate()); |
| } else { |
| NewCond = |
| Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not"); |
| } |
| |
| PBI->setCondition(NewCond); |
| PBI->swapSuccessors(); |
| } |
| |
| // If we have bonus instructions, clone them into the predecessor block. |
| // Note that there may be multiple predecessor blocks, so we cannot move |
| // bonus instructions to a predecessor block. |
| ValueToValueMapTy VMap; // maps original values to cloned values |
| // We already make sure Cond is the last instruction before BI. Therefore, |
| // all instructions before Cond other than DbgInfoIntrinsic are bonus |
| // instructions. |
| for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) { |
| if (isa<DbgInfoIntrinsic>(BonusInst)) |
| continue; |
| Instruction *NewBonusInst = BonusInst->clone(); |
| RemapInstruction(NewBonusInst, VMap, |
| RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
| VMap[&*BonusInst] = NewBonusInst; |
| |
| // If we moved a load, we cannot any longer claim any knowledge about |
| // its potential value. The previous information might have been valid |
| // only given the branch precondition. |
| // For an analogous reason, we must also drop all the metadata whose |
| // semantics we don't understand. |
| NewBonusInst->dropUnknownNonDebugMetadata(); |
| |
| PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst); |
| NewBonusInst->takeName(&*BonusInst); |
| BonusInst->setName(BonusInst->getName() + ".old"); |
| } |
| |
| // Clone Cond into the predecessor basic block, and or/and the |
| // two conditions together. |
| Instruction *CondInPred = Cond->clone(); |
| RemapInstruction(CondInPred, VMap, |
| RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
| PredBlock->getInstList().insert(PBI->getIterator(), CondInPred); |
| CondInPred->takeName(Cond); |
| Cond->setName(CondInPred->getName() + ".old"); |
| |
| if (BI->isConditional()) { |
| Instruction *NewCond = |