blob: 93701b2a77916ad572487dcfb62b1de21ffb81a1 [file] [log] [blame]
//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See 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/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Sequence.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/CaptureTracking.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/Analysis/GuardUtils.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.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/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/MemoryModelRelaxationAnnotations.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/ProfDataUtils.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Support/BranchProbability.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/Local.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <map>
#include <optional>
#include <set>
#include <tuple>
#include <utility>
#include <vector>
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "simplifycfg"
cl::opt<bool> llvm::RequireAndPreserveDomTree(
"simplifycfg-require-and-preserve-domtree", cl::Hidden,
cl::desc("Temorary development switch used to gradually uplift SimplifyCFG "
"into preserving DomTree,"));
// 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),
"Control the amount of phi node folding to perform (default = 2)"));
static cl::opt<unsigned> TwoEntryPHINodeFoldingThreshold(
"two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
cl::desc("Control the maximal total instruction cost that we are willing "
"to speculatively execute to fold a 2-entry PHI node into a "
"select (default = 4)"));
static cl::opt<bool>
HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
cl::desc("Hoist common instructions up to the parent block"));
static cl::opt<unsigned>
HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
cl::desc("Allow reordering across at most this many "
"instructions when hoisting"));
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 "
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"));
static cl::opt<int>
MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
cl::desc("Max size of a block which is still considered "
"small enough to thread through"));
// Two is chosen to allow one negation and a logical combine.
static cl::opt<unsigned>
BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
cl::desc("Maximum cost of combining conditions when "
"folding branches"));
static cl::opt<unsigned> BranchFoldToCommonDestVectorMultiplier(
"simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
cl::desc("Multiplier to apply to threshold when determining whether or not "
"to fold branch to common destination when vector operations are "
static cl::opt<bool> EnableMergeCompatibleInvokes(
"simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
static cl::opt<unsigned> MaxSwitchCasesPerResult(
"max-switch-cases-per-result", cl::Hidden, cl::init(16),
cl::desc("Limit cases to analyze when converting a switch to select"));
STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
"Number of switch instructions turned into linear mapping");
"Number of switch instructions turned into lookup tables");
"Number of switch instructions turned into lookup tables (holes checked)");
STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
"Number of value comparisons folded into predecessor basic blocks");
"Number of branches folded into predecessor basic block");
"Number of common instruction 'blocks' hoisted up to the begin block");
"Number of common instructions hoisted up to the begin block");
"Number of common instruction 'blocks' sunk down to the end block");
"Number of common instructions sunk down to the end block");
STATISTIC(NumSpeculations, "Number of speculative executed instructions");
"Number of invokes with empty resume blocks simplified into calls");
STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
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;
DomTreeUpdater *DTU;
const DataLayout &DL;
ArrayRef<WeakVH> 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 PerformValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
Instruction *PTI,
IRBuilder<> &Builder);
bool FoldValueComparisonIntoPredecessors(Instruction *TI,
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 simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder);
bool simplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
bool simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
IRBuilder<> &Builder);
bool hoistCommonCodeFromSuccessors(BasicBlock *BB, bool EqTermsOnly);
bool hoistSuccIdenticalTerminatorToSwitchOrIf(
Instruction *TI, Instruction *I1,
SmallVectorImpl<Instruction *> &OtherSuccTIs);
bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB);
bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
BasicBlock *TrueBB, BasicBlock *FalseBB,
uint32_t TrueWeight, uint32_t FalseWeight);
bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
const DataLayout &DL);
bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
const SimplifyCFGOptions &Opts)
: TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
assert((!DTU || !DTU->hasPostDomTree()) &&
"SimplifyCFG is not yet capable of maintaining validity of a "
"PostDomTree, so don't ask for it.");
bool simplifyOnce(BasicBlock *BB);
bool run(BasicBlock *BB);
// Helper to set Resimplify and return change indication.
bool requestResimplify() {
Resimplify = true;
return true;
} // end anonymous namespace
/// Return true if all the PHI nodes in the basic block \p BB
/// receive compatible (identical) incoming values when coming from
/// all of the predecessor blocks that are specified in \p IncomingBlocks.
/// Note that if the values aren't exactly identical, but \p EquivalenceSet
/// is provided, and *both* of the values are present in the set,
/// then they are considered equal.
static bool IncomingValuesAreCompatible(
BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
assert(IncomingBlocks.size() == 2 &&
"Only for a pair of incoming blocks at the time!");
// FIXME: it is okay if one of the incoming values is an `undef` value,
// iff the other incoming value is guaranteed to be a non-poison value.
// FIXME: it is okay if one of the incoming values is a `poison` value.
return all_of(BB->phis(), [IncomingBlocks, EquivalenceSet](PHINode &PN) {
Value *IV0 = PN.getIncomingValueForBlock(IncomingBlocks[0]);
Value *IV1 = PN.getIncomingValueForBlock(IncomingBlocks[1]);
if (IV0 == IV1)
return true;
if (EquivalenceSet && EquivalenceSet->contains(IV0) &&
return true;
return false;
/// 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))
if (IncomingValuesAreCompatible(Succ, {SI1BB, SI2BB}))
Fail = true;
if (FailBlocks)
return !Fail;
/// 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,
MemorySSAUpdater *MSSAU = nullptr) {
for (PHINode &PN : Succ->phis())
PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
if (MSSAU)
if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
MPhi->addIncoming(MPhi->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 InstructionCost computeSpeculationCost(const User *I,
const TargetTransformInfo &TTI) {
assert((!isa<Instruction>(I) ||
isSafeToSpeculativelyExecute(cast<Instruction>(I))) &&
"Instruction is not safe to speculatively execute!");
return TTI.getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency);
/// 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 Budget 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, Cost is increased by the cost of
/// V plus its non-dominating operands. If that cost is greater than
/// Budget, false is returned and Cost is undefined.
static bool dominatesMergePoint(Value *V, BasicBlock *BB,
SmallPtrSetImpl<Instruction *> &AggressiveInsts,
InstructionCost &Cost,
InstructionCost Budget,
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 dominate all instructions and can be executed
// unconditionally.
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;
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 > Budget &&
(!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
return false;
// Okay, we can only really hoist these out if their operands do
// not take us over the cost threshold.
for (Use &Op : I->operands())
if (!dominatesMergePoint(Op, BB, AggressiveInsts, Cost, Budget, TTI,
Depth + 1))
return false;
// Okay, it's safe to do this! Remember this instruction.
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;
return cast<ConstantInt>(
ConstantFoldIntegerCast(CI, PtrTy, /*isSigned=*/false, DL));
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) {
ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
ConstantComparesGatherer &
operator=(const ConstantComparesGatherer &) = delete;
/// 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:
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;
C->getValue() | Mask));
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;
C->getValue() & ~Mask));
return true;
// If we already have a value for the switch, it has to match!
if (!setValueOnce(ICI->getOperand(0)))
return false;
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::makeExactICmpRegion(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));
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) {
bool isEQ = match(V, m_LogicalOr(m_Value(), m_Value()));
// Keep a stack (SmallVector for efficiency) for depth-first traversal
SmallVector<Value *, 8> DFT;
SmallPtrSet<Value *, 8> Visited;
// Initialize
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.
Value *Op0, *Op1;
if (isEQ ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
: match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
if (Visited.insert(Op1).second)
if (Visited.insert(Op0).second)
// Try to match the current instruction
if (matchInstruction(I, isEQ))
// Match succeed, continue the loop
// 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;
// Failed to parse a proper sequence, abort now
CompValue = nullptr;
} // end anonymous namespace
static void EraseTerminatorAndDCECond(Instruction *TI,
MemorySSAUpdater *MSSAU = nullptr) {
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());
if (Cond)
RecursivelyDeleteTriviallyDeadInstructions(Cond, nullptr, MSSAU);
/// 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)) {
for (auto Case : SI->cases())
return SI->getDefaultDest();
BranchInst *BI = cast<BranchInst>(TI);
ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
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) {
llvm::erase(Cases, BB);
/// 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 (const ValueEqualityComparisonCase &VECC : *V2)
if (TheVal == VECC.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)
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);
// Remove PHI node entries for the dead edge.
LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
<< "Through successor TI: " << *TI << "Leaving: " << *NI
<< "\n");
if (DTU)
{{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
return true;
SwitchInstProfUpdateWrapper 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)
LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
<< "Through successor TI: " << *TI);
SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
auto *Successor = i->getCaseSuccessor();
if (DTU)
if (DeadCases.count(i->getCaseValue())) {
if (DTU)
if (DTU) {
std::vector<DominatorTree::UpdateType> Updates;
for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
if (I.second == 0)
Updates.push_back({DominatorTree::Delete, PredDef, I.first});
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;
// If not handled by any explicit cases, it is handled by the default case.
if (!TheRealDest)
TheRealDest = ThisDef;
SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
// Remove PHI node entries for dead edges.
BasicBlock *CheckEdge = TheRealDest;
for (BasicBlock *Succ : successors(TIBB))
if (Succ != CheckEdge) {
if (Succ != TheRealDest)
} else
CheckEdge = nullptr;
// Insert the new branch.
Instruction *NI = Builder.CreateBr(TheRealDest);
LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
<< "Through successor TI: " << *TI << "Leaving: " << *NI
<< "\n");
if (DTU) {
SmallVector<DominatorTree::UpdateType, 2> Updates;
for (auto *RemovedSucc : RemovedSuccs)
Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
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;
/// 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 && "Invalid branch-weight metadata");
extractFromBranchWeightMD64(MD, Weights);
// 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 = *llvm::max_element(Weights);
if (Max > UINT_MAX) {
unsigned Offset = 32 - llvm::countl_zero(Max);
for (uint64_t &I : Weights)
I >>= Offset;
static void CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(
BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
Instruction *PTI = PredBlock->getTerminator();
// 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.
for (Instruction &BonusInst : *BB) {
if (BonusInst.isTerminator())
Instruction *NewBonusInst = BonusInst.clone();
if (!isa<DbgInfoIntrinsic>(BonusInst) &&
PTI->getDebugLoc() != NewBonusInst->getDebugLoc()) {
// Unless the instruction has the same !dbg location as the original
// branch, drop it. When we fold the bonus instructions we want to make
// sure we reset their debug locations in order to avoid stepping on
// dead code caused by folding dead branches.
RemapInstruction(NewBonusInst, VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
// If we speculated an instruction, we need to drop any metadata that may
// result in undefined behavior, as the metadata might have been valid
// only given the branch precondition.
// Similarly strip attributes on call parameters that may cause UB in
// location the call is moved to.
NewBonusInst->insertInto(PredBlock, PTI->getIterator());
auto Range = NewBonusInst->cloneDebugInfoFrom(&BonusInst);
RemapDbgRecordRange(NewBonusInst->getModule(), Range, VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
if (isa<DbgInfoIntrinsic>(BonusInst))
BonusInst.setName(NewBonusInst->getName() + ".old");
VMap[&BonusInst] = NewBonusInst;
// Update (liveout) uses of bonus instructions,
// now that the bonus instruction has been cloned into predecessor.
// Note that we expect to be in a block-closed SSA form for this to work!
for (Use &U : make_early_inc_range(BonusInst.uses())) {
auto *UI = cast<Instruction>(U.getUser());
auto *PN = dyn_cast<PHINode>(UI);
if (!PN) {
assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
"If the user is not a PHI node, then it should be in the same "
"block as, and come after, the original bonus instruction.");
continue; // Keep using the original bonus instruction.
// Is this the block-closed SSA form PHI node?
if (PN->getIncomingBlock(U) == BB)
continue; // Great, keep using the original bonus instruction.
// The only other alternative is an "use" when coming from
// the predecessor block - here we should refer to the cloned bonus instr.
assert(PN->getIncomingBlock(U) == PredBlock &&
"Not in block-closed SSA form?");
bool SimplifyCFGOpt::PerformValueComparisonIntoPredecessorFolding(
Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
BasicBlock *BB = TI->getParent();
BasicBlock *Pred = PTI->getParent();
SmallVector<DominatorTree::UpdateType, 32> Updates;
// 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.
SmallMapVector<BasicBlock *, int, 8> NewSuccessors;
// Update the branch weight metadata along the way
SmallVector<uint64_t, 8> Weights;
bool PredHasWeights = hasBranchWeightMD(*PTI);
bool SuccHasWeights = hasBranchWeightMD(*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)
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());
// Reconstruct the new switch statement we will be building.
if (PredDefault != BBDefault) {
if (DTU && PredDefault != BB)
Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
PredDefault = 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) {
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) {
if (PredHasWeights || SuccHasWeights) {
WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
std::swap(Weights[i + 1], Weights.back());
std::swap(PredCases[i], PredCases.back());
// 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)
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)
PredCases.push_back(ValueEqualityComparisonCase(I, 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.
SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
if (DTU) {
SuccsOfPred = {succ_begin(Pred), succ_end(Pred)};
Updates.reserve(Updates.size() + NewSuccessors.size());
for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
NewSuccessors) {
for (auto I : seq(NewSuccessor.second)) {
AddPredecessorToBlock(NewSuccessor.first, Pred, BB);
if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
// 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());
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
SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
setBranchWeights(NewSI, MDWeights);
// 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);
if (DTU)
{DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
NewSI->setSuccessor(i, InfLoopBlock);
if (DTU) {
if (InfLoopBlock)
Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
Updates.push_back({DominatorTree::Delete, Pred, BB});
return true;
/// 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;
SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
while (!Preds.empty()) {
BasicBlock *Pred = Preds.pop_back_val();
Instruction *PTI = Pred->getTerminator();
// Don't try to fold into itself.
if (Pred == BB)
// See if the predecessor is a comparison with the same value.
Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
if (PCV != CV)
SmallSetVector<BasicBlock *, 4> FailBlocks;
if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
for (auto *Succ : FailBlocks) {
if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
return false;
PerformValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
Changed = true;
return Changed;
// If we would need to insert a select that uses the value of this invoke
// (comments in hoistSuccIdenticalTerminatorToSwitchOrIf 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;
// Get interesting characteristics of instructions that
// `hoistCommonCodeFromSuccessors` didn't hoist. They restrict what kind of
// instructions can be reordered across.
enum SkipFlags {
SkipReadMem = 1,
SkipSideEffect = 2,
SkipImplicitControlFlow = 4
static unsigned skippedInstrFlags(Instruction *I) {
unsigned Flags = 0;
if (I->mayReadFromMemory())
Flags |= SkipReadMem;
// We can't arbitrarily move around allocas, e.g. moving allocas (especially
// inalloca) across stacksave/stackrestore boundaries.
if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
Flags |= SkipSideEffect;
if (!isGuaranteedToTransferExecutionToSuccessor(I))
Flags |= SkipImplicitControlFlow;
return Flags;
// Returns true if it is safe to reorder an instruction across preceding
// instructions in a basic block.
static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
// Don't reorder a store over a load.
if ((Flags & SkipReadMem) && I->mayWriteToMemory())
return false;
// If we have seen an instruction with side effects, it's unsafe to reorder an
// instruction which reads memory or itself has side effects.
if ((Flags & SkipSideEffect) &&
(I->mayReadFromMemory() || I->mayHaveSideEffects() || isa<AllocaInst>(I)))
return false;
// Reordering across an instruction which does not necessarily transfer
// control to the next instruction is speculation.
if ((Flags & SkipImplicitControlFlow) && !isSafeToSpeculativelyExecute(I))
return false;
// Hoisting of llvm.deoptimize is only legal together with the next return
// instruction, which this pass is not always able to do.
if (auto *CB = dyn_cast<CallBase>(I))
if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
return false;
// It's also unsafe/illegal to hoist an instruction above its instruction
// operands
BasicBlock *BB = I->getParent();
for (Value *Op : I->operands()) {
if (auto *J = dyn_cast<Instruction>(Op))
if (J->getParent() == BB)
return false;
return true;
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
/// Helper function for hoistCommonCodeFromSuccessors. Return true if identical
/// instructions \p I1 and \p I2 can and should be hoisted.
static bool shouldHoistCommonInstructions(Instruction *I1, Instruction *I2,
const TargetTransformInfo &TTI) {
// 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 false;
if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
return false;
// If any of the two call sites has nomerge or convergent attribute, stop
// hoisting.
if (const auto *CB1 = dyn_cast<CallBase>(I1))
if (CB1->cannotMerge() || CB1->isConvergent())
return false;
if (const auto *CB2 = dyn_cast<CallBase>(I2))
if (CB2->cannotMerge() || CB2->isConvergent())
return false;
return true;
/// Hoists DbgVariableRecords from \p I1 and \p OtherInstrs that are identical
/// in lock-step to \p TI. This matches how dbg.* intrinsics are hoisting in
/// hoistCommonCodeFromSuccessors. e.g. The input:
/// I1 DVRs: { x, z },
/// OtherInsts: { I2 DVRs: { x, y, z } }
/// would result in hoisting only DbgVariableRecord x.
static void hoistLockstepIdenticalDbgVariableRecords(
Instruction *TI, Instruction *I1,
SmallVectorImpl<Instruction *> &OtherInsts) {
if (!I1->hasDbgRecords())
using CurrentAndEndIt =
std::pair<DbgRecord::self_iterator, DbgRecord::self_iterator>;
// Vector of {Current, End} iterators.
SmallVector<CurrentAndEndIt> Itrs;
Itrs.reserve(OtherInsts.size() + 1);
// Helper lambdas for lock-step checks:
// Return true if this Current == End.
auto atEnd = [](const CurrentAndEndIt &Pair) {
return Pair.first == Pair.second;
// Return true if all Current are identical.
auto allIdentical = [](const SmallVector<CurrentAndEndIt> &Itrs) {
return all_of(make_first_range(ArrayRef(Itrs).drop_front()),
[&](DbgRecord::self_iterator I) {
return Itrs[0].first->isIdenticalToWhenDefined(*I);
// Collect the iterators.
{I1->getDbgRecordRange().begin(), I1->getDbgRecordRange().end()});
for (Instruction *Other : OtherInsts) {
if (!Other->hasDbgRecords())
{Other->getDbgRecordRange().begin(), Other->getDbgRecordRange().end()});
// Iterate in lock-step until any of the DbgRecord lists are exausted. If
// the lock-step DbgRecord are identical, hoist all of them to TI.
// This replicates the dbg.* intrinsic behaviour in
// hoistCommonCodeFromSuccessors.
while (none_of(Itrs, atEnd)) {
bool HoistDVRs = allIdentical(Itrs);
for (CurrentAndEndIt &Pair : Itrs) {
// Increment Current iterator now as we may be about to move the
// DbgRecord.
DbgRecord &DR = *Pair.first++;
if (HoistDVRs) {
TI->getParent()->insertDbgRecordBefore(&DR, TI->getIterator());
/// Hoist any common code in the successor blocks up into the block. This
/// function guarantees that BB dominates all successors. If EqTermsOnly is
/// given, only perform hoisting in case both blocks only contain a terminator.
/// In that case, only the original BI will be replaced and selects for PHIs are
/// added.
bool SimplifyCFGOpt::hoistCommonCodeFromSuccessors(BasicBlock *BB,
bool EqTermsOnly) {
// 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(N1*N2*...) situations here where Ni are the sizes of these successors. As
// such, we currently just scan for obviously identical instructions in an
// identical order, possibly separated by the same number of non-identical
// instructions.
unsigned int SuccSize = succ_size(BB);
if (SuccSize < 2)
return false;
// If either of the blocks has it's address taken, then we can't do this fold,
// because the code we'd hoist would no longer run when we jump into the block
// by it's address.
for (auto *Succ : successors(BB))
if (Succ->hasAddressTaken() || !Succ->getSinglePredecessor())
return false;
auto *TI = BB->getTerminator();
// The second of pair is a SkipFlags bitmask.
using SuccIterPair = std::pair<BasicBlock::iterator, unsigned>;
SmallVector<SuccIterPair, 8> SuccIterPairs;
for (auto *Succ : successors(BB)) {
BasicBlock::iterator SuccItr = Succ->begin();
if (isa<PHINode>(*SuccItr))
return false;
SuccIterPairs.push_back(SuccIterPair(SuccItr, 0));
// Check if only hoisting terminators is allowed. This does not add new
// instructions to the hoist location.
if (EqTermsOnly) {
// Skip any debug intrinsics, as they are free to hoist.
for (auto &SuccIter : make_first_range(SuccIterPairs)) {
auto *INonDbg = &*skipDebugIntrinsics(SuccIter);
if (!INonDbg->isTerminator())
return false;
// Now we know that we only need to hoist debug intrinsics and the
// terminator. Let the loop below handle those 2 cases.
// Count how many instructions were not hoisted so far. There's a limit on how
// many instructions we skip, serving as a compilation time control as well as
// preventing excessive increase of life ranges.
unsigned NumSkipped = 0;
// If we find an unreachable instruction at the beginning of a basic block, we
// can still hoist instructions from the rest of the basic blocks.
if (SuccIterPairs.size() > 2) {
[](const auto &Pair) { return isa<UnreachableInst>(Pair.first); });
if (SuccIterPairs.size() < 2)
return false;
bool Changed = false;
for (;;) {
auto *SuccIterPairBegin = SuccIterPairs.begin();
auto &BB1ItrPair = *SuccIterPairBegin++;
auto OtherSuccIterPairRange =
iterator_range(SuccIterPairBegin, SuccIterPairs.end());
auto OtherSuccIterRange = make_first_range(OtherSuccIterPairRange);
Instruction *I1 = &*BB1ItrPair.first;
// Skip debug info if it is not identical.
bool AllDbgInstsAreIdentical = all_of(OtherSuccIterRange, [I1](auto &Iter) {
Instruction *I2 = &*Iter;
return I1->isIdenticalToWhenDefined(I2);
if (!AllDbgInstsAreIdentical) {
while (isa<DbgInfoIntrinsic>(I1))
I1 = &*++BB1ItrPair.first;
for (auto &SuccIter : OtherSuccIterRange) {
Instruction *I2 = &*SuccIter;
while (isa<DbgInfoIntrinsic>(I2))
I2 = &*++SuccIter;
bool AllInstsAreIdentical = true;
bool HasTerminator = I1->isTerminator();
for (auto &SuccIter : OtherSuccIterRange) {
Instruction *I2 = &*SuccIter;
HasTerminator |= I2->isTerminator();
if (AllInstsAreIdentical && (!I1->isIdenticalToWhenDefined(I2) ||
MMRAMetadata(*I1) != MMRAMetadata(*I2)))
AllInstsAreIdentical = false;
SmallVector<Instruction *, 8> OtherInsts;
for (auto &SuccIter : OtherSuccIterRange)
// If we are hoisting the terminator instruction, don't move one (making a
// broken BB), instead clone it, and remove BI.
if (HasTerminator) {
// Even if BB, which contains only one unreachable instruction, is ignored
// at the beginning of the loop, we can hoist the terminator instruction.
// If any instructions remain in the block, we cannot hoist terminators.
if (NumSkipped || !AllInstsAreIdentical) {
hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
return Changed;
return hoistSuccIdenticalTerminatorToSwitchOrIf(TI, I1, OtherInsts) ||
if (AllInstsAreIdentical) {
unsigned SkipFlagsBB1 = BB1ItrPair.second;
AllInstsAreIdentical =
isSafeToHoistInstr(I1, SkipFlagsBB1) &&
all_of(OtherSuccIterPairRange, [=](const auto &Pair) {
Instruction *I2 = &*Pair.first;
unsigned SkipFlagsBB2 = Pair.second;
// Even if the instructions are identical, it may not
// be safe to hoist them if we have skipped over
// instructions with side effects or their operands
// weren't hoisted.
return isSafeToHoistInstr(I2, SkipFlagsBB2) &&
shouldHoistCommonInstructions(I1, I2, TTI);
if (AllInstsAreIdentical) {
if (isa<DbgInfoIntrinsic>(I1)) {
// 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.
hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
// We've just hoisted DbgVariableRecords; move I1 after them (before TI)
// and leave any that were not hoisted behind (by calling moveBefore
// rather than moveBeforePreserving).
for (auto &SuccIter : OtherSuccIterRange) {
auto *I2 = &*SuccIter++;
} 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.
hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
// We've just hoisted DbgVariableRecords; move I1 after them (before TI)
// and leave any that were not hoisted behind (by calling moveBefore
// rather than moveBeforePreserving).
for (auto &SuccIter : OtherSuccIterRange) {
Instruction *I2 = &*SuccIter++;
assert(I2 != I1);
if (!I2->use_empty())
combineMetadataForCSE(I1, I2, 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());
if (!Changed)
NumHoistCommonCode += SuccIterPairs.size();
Changed = true;
NumHoistCommonInstrs += SuccIterPairs.size();
} else {
if (NumSkipped >= HoistCommonSkipLimit) {
hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
return Changed;
// We are about to skip over a pair of non-identical instructions. Record
// if any have characteristics that would prevent reordering instructions
// across them.
for (auto &SuccIterPair : SuccIterPairs) {
Instruction *I = &*SuccIterPair.first++;
SuccIterPair.second |= skippedInstrFlags(I);
bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
Instruction *TI, Instruction *I1,
SmallVectorImpl<Instruction *> &OtherSuccTIs) {
auto *BI = dyn_cast<BranchInst>(TI);
bool Changed = false;
BasicBlock *TIParent = TI->getParent();
BasicBlock *BB1 = I1->getParent();
// Use only for an if statement.
auto *I2 = *OtherSuccTIs.begin();
auto *BB2 = I2->getParent();
if (BI) {
assert(OtherSuccTIs.size() == 1);
assert(BI->getSuccessor(0) == I1->getParent());
assert(BI->getSuccessor(1) == I2->getParent());
// In the case of an if statement, we try to hoist an invoke.
// FIXME: Can we define a safety predicate for CallBr?
// FIXME: Test case llvm/test/Transforms/SimplifyCFG/2009-06-15-InvokeCrash.ll
// removed in 4c923b3b3fd0ac1edebf0603265ca3ba51724937 commit?
if (isa<InvokeInst>(I1) && (!BI || !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
return false;
// TODO: callbr hoisting currently disabled pending further study.
if (isa<CallBrInst>(I1))
return false;
for (BasicBlock *Succ : successors(BB1)) {
for (PHINode &PN : Succ->phis()) {
Value *BB1V = PN.getIncomingValueForBlock(BB1);
for (Instruction *OtherSuccTI : OtherSuccTIs) {
Value *BB2V = PN.getIncomingValueForBlock(OtherSuccTI->getParent());
if (BB1V == BB2V)
// In the case of an if statement, check for
// passingValueIsAlwaysUndefined here because we would rather eliminate
// undefined control flow then converting it to a select.
if (!BI || passingValueIsAlwaysUndefined(BB1V, &PN) ||
passingValueIsAlwaysUndefined(BB2V, &PN))
return false;
// Hoist DbgVariableRecords attached to the terminator to match dbg.*
// intrinsic hoisting behaviour in hoistCommonCodeFromSuccessors.
hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherSuccTIs);
// Clone the terminator and hoist it into the pred, without any debug info.
Instruction *NT = I1->clone();
NT->insertInto(TIParent, TI->getIterator());
if (!NT->getType()->isVoidTy()) {
for (Instruction *OtherSuccTI : OtherSuccTIs)
Changed = true;
NumHoistCommonInstrs += OtherSuccTIs.size() + 1;
// Ensure terminator gets a debug location, even an unknown one, in case
// it involves inlinable calls.
SmallVector<DILocation *, 4> Locs;
for (auto *OtherSuccTI : OtherSuccTIs)
// PHIs created below will adopt NT's merged DebugLoc.
IRBuilder<NoFolder> Builder(NT);
// In the case of an if statement, 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.
if (BI) {
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)
// 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) {
// Propagate fast-math-flags from phi node to its replacement select.
IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
if (isa<FPMathOperator>(PN))
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);
SmallVector<DominatorTree::UpdateType, 4> Updates;
// Update any PHI nodes in our new successors.
for (BasicBlock *Succ : successors(BB1)) {
AddPredecessorToBlock(Succ, TIParent, BB1);
if (DTU)
Updates.push_back({DominatorTree::Insert, TIParent, Succ});
if (DTU)
for (BasicBlock *Succ : successors(TI))
Updates.push_back({DominatorTree::Delete, TIParent, Succ});
if (DTU)
return Changed;
// Check lifetime markers.
static bool isLifeTimeMarker(const Instruction *I) {
if (auto II = dyn_cast<IntrinsicInst>(I)) {
switch (II->getIntrinsicID()) {
case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
return true;
return false;
// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
// into variables.
static bool replacingOperandWithVariableIsCheap(const Instruction *I,
int OpIdx) {
return !isa<IntrinsicInst>(I);
// 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. Each instruction must have
// exactly zero or one use, and we check later that use is by a single, common
// PHI instruction in the successor.
bool HasUse = !Insts.front()->user_empty();
for (auto *I : Insts) {
// These instructions may change or break semantics if moved.
if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
return false;
// Do not try to sink an instruction in an infinite loop - it can cause
// this algorithm to infinite loop.
if (I->getParent()->getSingleSuccessor() == I->getParent())
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 the instruction has nomerge or convergent attribute, return false.
if (const auto *C = dyn_cast<CallBase>(I))
if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
return false;
// Each instruction must have zero or one use.
if (HasUse && !I->hasOneUse())
return false;
if (!HasUse && !I->user_empty())
return false;
const Instruction *I0 = Insts.front();
const auto I0MMRA = MMRAMetadata(*I0);
for (auto *I : Insts) {
if (!I->isSameOperationAs(I0))
return false;
// swifterror pointers can only be used by a load or store; sinking a load
// or store would require introducing a select for the pointer operand,
// which isn't allowed for swifterror pointers.
if (isa<StoreInst>(I) && I->getOperand(1)->isSwiftError())
return false;
if (isa<LoadInst>(I) && I->getOperand(0)->isSwiftError())
return false;
// Treat MMRAs conservatively. This pass can be quite aggressive and
// could drop a lot of MMRAs otherwise.
if (MMRAMetadata(*I) != I0MMRA)
return false;
// All instructions in Insts are known to be the same opcode. If they have a
// use, check that the only user 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 (HasUse) {
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, stores or lifetime markers 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
// FIXME: This is a workaround for a deficiency in SROA - see
if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
return false;
if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts());
return false;
if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) {
return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
return false;
// For calls to be sinkable, they must all be indirect, or have same callee.
// I.e. if we have two direct calls to different callees, we don't want to
// turn that into an indirect call. Likewise, if we have an indirect call,
// and a direct call, we don't actually want to have a single indirect call.
if (isa<CallBase>(I0)) {
auto IsIndirectCall = [](const Instruction *I) {
return cast<CallBase>(I)->isIndirectCall();
bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
if (HaveIndirectCalls) {
if (!AllCallsAreIndirect)
return false;
} else {
// All callees must be identical.
Value *Callee = nullptr;
for (const Instruction *I : Insts) {
Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
if (!Callee)
Callee = CurrCallee;
else if (Callee != CurrCallee)
return false;
for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
Value *Op = I0->getOperand(OI);
if (Op->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 ((isa<Constant>(Op) && !replacingOperandWithVariableIsCheap(I0, OI)) ||
!canReplaceOperandWithVariable(I0, OI))
// We can't create a PHI from this GEP.
return false;
for (auto *I : Insts)
return true;
// Assuming canSinkInstructions(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);
// canSinkInstructions 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))
// The only checking we need to do now is that all users of all instructions
// are the same PHI node. canSinkInstructions 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 (!I0->user_empty()) {
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; canSinkInstructions 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 canSinkInstructions. 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) {
// 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");
for (auto *I : Insts)
PN->addIncoming(I->getOperand(O), I->getParent());
// 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->moveBefore(*BBEnd, 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);
if (!I0->user_empty()) {
// 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.
auto *PN = cast<PHINode>(*I0->user_begin());
// Finally nuke all instructions apart from the common instruction.
for (auto *I : Insts) {
if (I == I0)
// The remaining uses are debug users, replace those with the common inst.
// In most (all?) cases this just introduces a use-before-def.
assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
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;
LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
void reset() {
Fail = false;
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;
bool isValid() const {
return !Fail;
void operator--() {
if (Fail)
for (auto *&Inst : Insts) {
for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
Inst = Inst->getPrevNode();
// Already at beginning of block.
if (!Inst) {
Fail = true;
void operator++() {
if (Fail)
for (auto *&Inst : Insts) {
for (Inst = Inst->getNextNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
Inst = Inst->getNextNode();
// Already at end of block.
if (!Inst) {
Fail = true;
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.
static bool SinkCommonCodeFromPredecessors(BasicBlock *BB,
DomTreeUpdater *DTU) {
// We support two situations:
// (1) all incoming arcs are unconditional
// (2) there are non-unconditional incoming arcs
// (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;
bool HaveNonUnconditionalPredecessors = false;
for (auto *PredBB : predecessors(BB)) {
auto *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
if (PredBr && PredBr->isUnconditional())
HaveNonUnconditionalPredecessors = true;
if (UnconditionalPreds.size() < 2)
return 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.
int 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());
// If no instructions can be sunk, early-return.
if (ScanIdx == 0)
return false;
bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
if (!followedByDeoptOrUnreachable) {
// Okay, we *could* sink last ScanIdx instructions. But how many can we
// actually sink before encountering instruction that is unprofitable to
// sink?
auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
unsigned NumPHIdValues = 0;
for (auto *I : *LRI)
for (auto *V : PHIOperands[I]) {
if (!InstructionsToSink.contains(V))
// FIXME: this check is overly optimistic. We may end up not sinking
// said instruction, due to the very same profitability check.
// See @creating_too_many_phis in sink-common-code.ll.
LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
return NumPHIInsts <= 1;
// We've determined that we are going to sink last ScanIdx instructions,
// and recorded them in InstructionsToSink. Now, some instructions may be
// unprofitable to sink. But that determination depends on the instructions
// that we are going to sink.
// First, forward scan: find the first instruction unprofitable to sink,
// recording all the ones that are profitable to sink.
// FIXME: would it be better, after we detect that not all are profitable.
// to either record the profitable ones, or erase the unprofitable ones?
// Maybe we need to choose (at runtime) the one that will touch least
// instrs?
int Idx = 0;
SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
while (Idx < ScanIdx) {
if (!ProfitableToSinkInstruction(LRI)) {
// Too many PHIs would be created.
dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
InstructionsProfitableToSink.insert((*LRI).begin(), (*LRI).end());
// If no instructions can be sunk, early-return.
if (Idx == 0)
return false;
// Did we determine that (only) some instructions are unprofitable to sink?
if (Idx < ScanIdx) {
// Okay, some instructions are unprofitable.
ScanIdx = Idx;
InstructionsToSink = InstructionsProfitableToSink;
// But, that may make other instructions unprofitable, too.
// So, do a backward scan, do any earlier instructions become
// unprofitable?
!ProfitableToSinkInstruction(LRI) &&
"We already know that the last instruction is unprofitable to sink");
while (Idx >= 0) {
// If we detect that an instruction becomes unprofitable to sink,
// all earlier instructions won't be sunk either,
// so preemptively keep InstructionsProfitableToSink in sync.
// FIXME: is this the most performant approach?
for (auto *I : *LRI)
if (!ProfitableToSinkInstruction(LRI)) {
// Everything starting with this instruction won't be sunk.
ScanIdx = Idx;
InstructionsToSink = InstructionsProfitableToSink;
// If no instructions can be sunk, early-return.
if (ScanIdx == 0)
return false;
bool Changed = false;
if (HaveNonUnconditionalPredecessors) {
if (!followedByDeoptOrUnreachable) {
// It is always legal to sink common instructions from unconditional
// predecessors. However, if not all predecessors are unconditional,
// this transformation might be pessimizing. So as a rule of thumb,
// don't do it unless we'd sink at least one non-speculatable instruction.
// See
int Idx = 0;
bool Profitable = false;
while (Idx < ScanIdx) {
if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
Profitable = true;
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", DTU))
// 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.
int SinkIdx = 0;
for (; 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.
if (!sinkLastInstruction(UnconditionalPreds)) {
<< "SINK: stopping here, failed to actually sink instruction!\n");
Changed = true;
if (SinkIdx != 0)
return Changed;
namespace {
struct CompatibleSets {
using SetTy = SmallVector<InvokeInst *, 2>;
SmallVector<SetTy, 1> Sets;
static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
SetTy &getCompatibleSet(InvokeInst *II);
void insert(InvokeInst *II);
CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
// Perform a linear scan over all the existing sets, see if the new `invoke`
// is compatible with any particular set. Since we know that all the `invokes`
// within a set are compatible, only check the first `invoke` in each set.
// WARNING: at worst, this has quadratic complexity.
for (CompatibleSets::SetTy &Set : Sets) {
if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
return Set;
// Otherwise, we either had no sets yet, or this invoke forms a new set.
return Sets.emplace_back();
void CompatibleSets::insert(InvokeInst *II) {
bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
// Can we theoretically merge these `invoke`s?
auto IsIllegalToMerge = [](InvokeInst *II) {
return II->cannotMerge() || II->isInlineAsm();
if (any_of(Invokes, IsIllegalToMerge))
return false;
// Either both `invoke`s must be direct,
// or both `invoke`s must be indirect.
auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
if (HaveIndirectCalls) {
if (!AllCallsAreIndirect)
return false;
} else {
// All callees must be identical.
Value *Callee = nullptr;
for (InvokeInst *II : Invokes) {
Value *CurrCallee = II->getCalledOperand();
assert(CurrCallee && "There is always a called operand.");
if (!Callee)
Callee = CurrCallee;
else if (Callee != CurrCallee)
return false;
// Either both `invoke`s must not have a normal destination,
// or both `invoke`s must have a normal destination,
auto HasNormalDest = [](InvokeInst *II) {
return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIOrDbg());
if (any_of(Invokes, HasNormalDest)) {
// Do not merge `invoke` that does not have a normal destination with one
// that does have a normal destination, even though doing so would be legal.
if (!all_of(Invokes, HasNormalDest))
return false;
// All normal destinations must be identical.
BasicBlock *NormalBB = nullptr;
for (InvokeInst *II : Invokes) {
BasicBlock *CurrNormalBB = II->getNormalDest();
assert(CurrNormalBB && "There is always a 'continue to' basic block.");
if (!NormalBB)
NormalBB = CurrNormalBB;
else if (NormalBB != CurrNormalBB)
return false;
// In the normal destination, the incoming values for these two `invoke`s
// must be compatible.
SmallPtrSet<Value *, 16> EquivalenceSet(Invokes.begin(), Invokes.end());
if (!IncomingValuesAreCompatible(
NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
return false;
#ifndef NDEBUG
// All unwind destinations must be identical.
// We know that because we have started from said unwind destination.
BasicBlock *UnwindBB = nullptr;
for (InvokeInst *II : Invokes) {
BasicBlock *CurrUnwindBB = II->getUnwindDest();
assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
if (!UnwindBB)
UnwindBB = CurrUnwindBB;
assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
// In the unwind destination, the incoming values for these two `invoke`s
// must be compatible.
if (!IncomingValuesAreCompatible(
{Invokes[0]->getParent(), Invokes[1]->getParent()}))
return false;
// Ignoring arguments, these `invoke`s must be identical,
// including operand bundles.
const InvokeInst *II0 = Invokes.front();
for (auto *II : Invokes.drop_front())
if (!II->isSameOperationAs(II0))
return false;
// Can we theoretically form the data operands for the merged `invoke`?
auto IsIllegalToMergeArguments = [](auto Ops) {
Use &U0 = std::get<0>(Ops);
Use &U1 = std::get<1>(Ops);
if (U0 == U1)
return false;
return U0->getType()->isTokenTy() ||
assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
return false;
return true;
} // namespace
// Merge all invokes in the provided set, all of which are compatible
// as per the `CompatibleSets::shouldBelongToSameSet()`.
static void MergeCompatibleInvokesImpl(ArrayRef<InvokeInst *> Invokes,
DomTreeUpdater *DTU) {
assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
SmallVector<DominatorTree::UpdateType, 8> Updates;
if (DTU)
Updates.reserve(2 + 3 * Invokes.size());
bool HasNormalDest =
// Clone one of the invokes into a new basic block.
// Since they are all compatible, it doesn't matter which invoke is cloned.
InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
InvokeInst *II0 = Invokes.front();
BasicBlock *II0BB = II0->getParent();
BasicBlock *InsertBeforeBlock =
Function *Func = II0BB->getParent();
LLVMContext &Ctx = II0->getContext();
BasicBlock *MergedInvokeBB = BasicBlock::Create(
Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
auto *MergedInvoke = cast<InvokeInst>(II0->clone());
// NOTE: all invokes have the same attributes, so no handling needed.
MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end());
if (!HasNormalDest) {
// This set does not have a normal destination,
// so just form a new block with unreachable terminator.
BasicBlock *MergedNormalDest = BasicBlock::Create(
Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
new UnreachableInst(Ctx, MergedNormalDest);
// The unwind destination, however, remainds identical for all invokes here.
return MergedInvoke;
if (DTU) {
// Predecessor blocks that contained these invokes will now branch to
// the new block that contains the merged invoke, ...
for (InvokeInst *II : Invokes)
{DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
// ... which has the new `unreachable` block as normal destination,
// or unwinds to the (same for all `invoke`s in this set) `landingpad`,
for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
// Since predecessor blocks now unconditionally branch to a new block,
// they no longer branch to their original successors.
for (InvokeInst *II : Invokes)
for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
{DominatorTree::Delete, II->getParent(), SuccOfPredBB});
bool IsIndirectCall = Invokes[0]->isIndirectCall();
// Form the merged operands for the merged invoke.
for (Use &U : MergedInvoke->operands()) {
// Only PHI together the indirect callees and data operands.
if (MergedInvoke->isCallee(&U)) {
if (!IsIndirectCall)
} else if (!MergedInvoke->isDataOperand(&U))
// Don't create trivial PHI's with all-identical incoming values.
bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
return II->getOperand(U.getOperandNo()) != U.get();
if (!NeedPHI)
// Form a PHI out of all the data ops under this index.
PHINode *PN = PHINode::Create(
U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke->getIterator());
for (InvokeInst *II : Invokes)
PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
// We've ensured that each PHI node has compatible (identical) incoming values
// when coming from each of the `invoke`s in the current merge set,
// so update the PHI nodes accordingly.
for (BasicBlock *Succ : successors(MergedInvoke))
AddPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
// And finally, replace the original `invoke`s with an unconditional branch
// to the block with the merged `invoke`. Also, give that merged `invoke`
// the merged debugloc of all the original `invoke`s.
DILocation *MergedDebugLoc = nullptr;
for (InvokeInst *II : Invokes) {
// Compute the debug location common to all the original `invoke`s.
if (!MergedDebugLoc)
MergedDebugLoc = II->getDebugLoc();
MergedDebugLoc =
DILocation::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
// And replace the old `invoke` with an unconditionally branch
// to the block with the merged `invoke`.
for (BasicBlock *OrigSuccBB : successors(II->getParent()))
BranchInst::Create(MergedInvoke->getParent(), II->getParent());
if (DTU)
/// If this block is a `landingpad` exception handling block, categorize all
/// the predecessor `invoke`s into sets, with all `invoke`s in each set
/// being "mergeable" together, and then merge invokes in each set together.
/// This is a weird mix of hoisting and sinking. Visually, it goes from:
/// [...] [...]
/// | |
/// [invoke0] [invoke1]
/// / \ / \
/// [cont0] [landingpad] [cont1]
/// to:
/// [...] [...]
/// \ /
/// [invoke]
/// / \
/// [cont] [landingpad]
/// But of course we can only do that if the i