Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Utils/Local.cpp
35271 views
//===- Local.cpp - Functions to perform local transformations -------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This family of functions perform various local transformations to the9// program.10//11//===----------------------------------------------------------------------===//1213#include "llvm/Transforms/Utils/Local.h"14#include "llvm/ADT/APInt.h"15#include "llvm/ADT/DenseMap.h"16#include "llvm/ADT/DenseMapInfo.h"17#include "llvm/ADT/DenseSet.h"18#include "llvm/ADT/Hashing.h"19#include "llvm/ADT/STLExtras.h"20#include "llvm/ADT/SetVector.h"21#include "llvm/ADT/SmallPtrSet.h"22#include "llvm/ADT/SmallVector.h"23#include "llvm/ADT/Statistic.h"24#include "llvm/Analysis/AssumeBundleQueries.h"25#include "llvm/Analysis/ConstantFolding.h"26#include "llvm/Analysis/DomTreeUpdater.h"27#include "llvm/Analysis/InstructionSimplify.h"28#include "llvm/Analysis/MemoryBuiltins.h"29#include "llvm/Analysis/MemorySSAUpdater.h"30#include "llvm/Analysis/TargetLibraryInfo.h"31#include "llvm/Analysis/ValueTracking.h"32#include "llvm/Analysis/VectorUtils.h"33#include "llvm/BinaryFormat/Dwarf.h"34#include "llvm/IR/Argument.h"35#include "llvm/IR/Attributes.h"36#include "llvm/IR/BasicBlock.h"37#include "llvm/IR/CFG.h"38#include "llvm/IR/Constant.h"39#include "llvm/IR/ConstantRange.h"40#include "llvm/IR/Constants.h"41#include "llvm/IR/DIBuilder.h"42#include "llvm/IR/DataLayout.h"43#include "llvm/IR/DebugInfo.h"44#include "llvm/IR/DebugInfoMetadata.h"45#include "llvm/IR/DebugLoc.h"46#include "llvm/IR/DerivedTypes.h"47#include "llvm/IR/Dominators.h"48#include "llvm/IR/EHPersonalities.h"49#include "llvm/IR/Function.h"50#include "llvm/IR/GetElementPtrTypeIterator.h"51#include "llvm/IR/GlobalObject.h"52#include "llvm/IR/IRBuilder.h"53#include "llvm/IR/InstrTypes.h"54#include "llvm/IR/Instruction.h"55#include "llvm/IR/Instructions.h"56#include "llvm/IR/IntrinsicInst.h"57#include "llvm/IR/Intrinsics.h"58#include "llvm/IR/IntrinsicsWebAssembly.h"59#include "llvm/IR/LLVMContext.h"60#include "llvm/IR/MDBuilder.h"61#include "llvm/IR/MemoryModelRelaxationAnnotations.h"62#include "llvm/IR/Metadata.h"63#include "llvm/IR/Module.h"64#include "llvm/IR/PatternMatch.h"65#include "llvm/IR/ProfDataUtils.h"66#include "llvm/IR/Type.h"67#include "llvm/IR/Use.h"68#include "llvm/IR/User.h"69#include "llvm/IR/Value.h"70#include "llvm/IR/ValueHandle.h"71#include "llvm/Support/Casting.h"72#include "llvm/Support/CommandLine.h"73#include "llvm/Support/Debug.h"74#include "llvm/Support/ErrorHandling.h"75#include "llvm/Support/KnownBits.h"76#include "llvm/Support/raw_ostream.h"77#include "llvm/Transforms/Utils/BasicBlockUtils.h"78#include "llvm/Transforms/Utils/ValueMapper.h"79#include <algorithm>80#include <cassert>81#include <cstdint>82#include <iterator>83#include <map>84#include <optional>85#include <utility>8687using namespace llvm;88using namespace llvm::PatternMatch;8990extern cl::opt<bool> UseNewDbgInfoFormat;9192#define DEBUG_TYPE "local"9394STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");95STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");9697static cl::opt<bool> PHICSEDebugHash(98"phicse-debug-hash",99#ifdef EXPENSIVE_CHECKS100cl::init(true),101#else102cl::init(false),103#endif104cl::Hidden,105cl::desc("Perform extra assertion checking to verify that PHINodes's hash "106"function is well-behaved w.r.t. its isEqual predicate"));107108static cl::opt<unsigned> PHICSENumPHISmallSize(109"phicse-num-phi-smallsize", cl::init(32), cl::Hidden,110cl::desc(111"When the basic block contains not more than this number of PHI nodes, "112"perform a (faster!) exhaustive search instead of set-driven one."));113114// Max recursion depth for collectBitParts used when detecting bswap and115// bitreverse idioms.116static const unsigned BitPartRecursionMaxDepth = 48;117118//===----------------------------------------------------------------------===//119// Local constant propagation.120//121122/// ConstantFoldTerminator - If a terminator instruction is predicated on a123/// constant value, convert it into an unconditional branch to the constant124/// destination. This is a nontrivial operation because the successors of this125/// basic block must have their PHI nodes updated.126/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch127/// conditions and indirectbr addresses this might make dead if128/// DeleteDeadConditions is true.129bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,130const TargetLibraryInfo *TLI,131DomTreeUpdater *DTU) {132Instruction *T = BB->getTerminator();133IRBuilder<> Builder(T);134135// Branch - See if we are conditional jumping on constant136if (auto *BI = dyn_cast<BranchInst>(T)) {137if (BI->isUnconditional()) return false; // Can't optimize uncond branch138139BasicBlock *Dest1 = BI->getSuccessor(0);140BasicBlock *Dest2 = BI->getSuccessor(1);141142if (Dest2 == Dest1) { // Conditional branch to same location?143// This branch matches something like this:144// br bool %cond, label %Dest, label %Dest145// and changes it into: br label %Dest146147// Let the basic block know that we are letting go of one copy of it.148assert(BI->getParent() && "Terminator not inserted in block!");149Dest1->removePredecessor(BI->getParent());150151// Replace the conditional branch with an unconditional one.152BranchInst *NewBI = Builder.CreateBr(Dest1);153154// Transfer the metadata to the new branch instruction.155NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,156LLVMContext::MD_annotation});157158Value *Cond = BI->getCondition();159BI->eraseFromParent();160if (DeleteDeadConditions)161RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);162return true;163}164165if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {166// Are we branching on constant?167// YES. Change to unconditional branch...168BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;169BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;170171// Let the basic block know that we are letting go of it. Based on this,172// it will adjust it's PHI nodes.173OldDest->removePredecessor(BB);174175// Replace the conditional branch with an unconditional one.176BranchInst *NewBI = Builder.CreateBr(Destination);177178// Transfer the metadata to the new branch instruction.179NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,180LLVMContext::MD_annotation});181182BI->eraseFromParent();183if (DTU)184DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});185return true;186}187188return false;189}190191if (auto *SI = dyn_cast<SwitchInst>(T)) {192// If we are switching on a constant, we can convert the switch to an193// unconditional branch.194auto *CI = dyn_cast<ConstantInt>(SI->getCondition());195BasicBlock *DefaultDest = SI->getDefaultDest();196BasicBlock *TheOnlyDest = DefaultDest;197198// If the default is unreachable, ignore it when searching for TheOnlyDest.199if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&200SI->getNumCases() > 0) {201TheOnlyDest = SI->case_begin()->getCaseSuccessor();202}203204bool Changed = false;205206// Figure out which case it goes to.207for (auto It = SI->case_begin(), End = SI->case_end(); It != End;) {208// Found case matching a constant operand?209if (It->getCaseValue() == CI) {210TheOnlyDest = It->getCaseSuccessor();211break;212}213214// Check to see if this branch is going to the same place as the default215// dest. If so, eliminate it as an explicit compare.216if (It->getCaseSuccessor() == DefaultDest) {217MDNode *MD = getValidBranchWeightMDNode(*SI);218unsigned NCases = SI->getNumCases();219// Fold the case metadata into the default if there will be any branches220// left, unless the metadata doesn't match the switch.221if (NCases > 1 && MD) {222// Collect branch weights into a vector.223SmallVector<uint32_t, 8> Weights;224extractBranchWeights(MD, Weights);225226// Merge weight of this case to the default weight.227unsigned Idx = It->getCaseIndex();228// TODO: Add overflow check.229Weights[0] += Weights[Idx + 1];230// Remove weight for this case.231std::swap(Weights[Idx + 1], Weights.back());232Weights.pop_back();233setBranchWeights(*SI, Weights, hasBranchWeightOrigin(MD));234}235// Remove this entry.236BasicBlock *ParentBB = SI->getParent();237DefaultDest->removePredecessor(ParentBB);238It = SI->removeCase(It);239End = SI->case_end();240241// Removing this case may have made the condition constant. In that242// case, update CI and restart iteration through the cases.243if (auto *NewCI = dyn_cast<ConstantInt>(SI->getCondition())) {244CI = NewCI;245It = SI->case_begin();246}247248Changed = true;249continue;250}251252// Otherwise, check to see if the switch only branches to one destination.253// We do this by reseting "TheOnlyDest" to null when we find two non-equal254// destinations.255if (It->getCaseSuccessor() != TheOnlyDest)256TheOnlyDest = nullptr;257258// Increment this iterator as we haven't removed the case.259++It;260}261262if (CI && !TheOnlyDest) {263// Branching on a constant, but not any of the cases, go to the default264// successor.265TheOnlyDest = SI->getDefaultDest();266}267268// If we found a single destination that we can fold the switch into, do so269// now.270if (TheOnlyDest) {271// Insert the new branch.272Builder.CreateBr(TheOnlyDest);273BasicBlock *BB = SI->getParent();274275SmallSet<BasicBlock *, 8> RemovedSuccessors;276277// Remove entries from PHI nodes which we no longer branch to...278BasicBlock *SuccToKeep = TheOnlyDest;279for (BasicBlock *Succ : successors(SI)) {280if (DTU && Succ != TheOnlyDest)281RemovedSuccessors.insert(Succ);282// Found case matching a constant operand?283if (Succ == SuccToKeep) {284SuccToKeep = nullptr; // Don't modify the first branch to TheOnlyDest285} else {286Succ->removePredecessor(BB);287}288}289290// Delete the old switch.291Value *Cond = SI->getCondition();292SI->eraseFromParent();293if (DeleteDeadConditions)294RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);295if (DTU) {296std::vector<DominatorTree::UpdateType> Updates;297Updates.reserve(RemovedSuccessors.size());298for (auto *RemovedSuccessor : RemovedSuccessors)299Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});300DTU->applyUpdates(Updates);301}302return true;303}304305if (SI->getNumCases() == 1) {306// Otherwise, we can fold this switch into a conditional branch307// instruction if it has only one non-default destination.308auto FirstCase = *SI->case_begin();309Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),310FirstCase.getCaseValue(), "cond");311312// Insert the new branch.313BranchInst *NewBr = Builder.CreateCondBr(Cond,314FirstCase.getCaseSuccessor(),315SI->getDefaultDest());316SmallVector<uint32_t> Weights;317if (extractBranchWeights(*SI, Weights) && Weights.size() == 2) {318uint32_t DefWeight = Weights[0];319uint32_t CaseWeight = Weights[1];320// The TrueWeight should be the weight for the single case of SI.321NewBr->setMetadata(LLVMContext::MD_prof,322MDBuilder(BB->getContext())323.createBranchWeights(CaseWeight, DefWeight));324}325326// Update make.implicit metadata to the newly-created conditional branch.327MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);328if (MakeImplicitMD)329NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);330331// Delete the old switch.332SI->eraseFromParent();333return true;334}335return Changed;336}337338if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {339// indirectbr blockaddress(@F, @BB) -> br label @BB340if (auto *BA =341dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {342BasicBlock *TheOnlyDest = BA->getBasicBlock();343SmallSet<BasicBlock *, 8> RemovedSuccessors;344345// Insert the new branch.346Builder.CreateBr(TheOnlyDest);347348BasicBlock *SuccToKeep = TheOnlyDest;349for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {350BasicBlock *DestBB = IBI->getDestination(i);351if (DTU && DestBB != TheOnlyDest)352RemovedSuccessors.insert(DestBB);353if (IBI->getDestination(i) == SuccToKeep) {354SuccToKeep = nullptr;355} else {356DestBB->removePredecessor(BB);357}358}359Value *Address = IBI->getAddress();360IBI->eraseFromParent();361if (DeleteDeadConditions)362// Delete pointer cast instructions.363RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);364365// Also zap the blockaddress constant if there are no users remaining,366// otherwise the destination is still marked as having its address taken.367if (BA->use_empty())368BA->destroyConstant();369370// If we didn't find our destination in the IBI successor list, then we371// have undefined behavior. Replace the unconditional branch with an372// 'unreachable' instruction.373if (SuccToKeep) {374BB->getTerminator()->eraseFromParent();375new UnreachableInst(BB->getContext(), BB);376}377378if (DTU) {379std::vector<DominatorTree::UpdateType> Updates;380Updates.reserve(RemovedSuccessors.size());381for (auto *RemovedSuccessor : RemovedSuccessors)382Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});383DTU->applyUpdates(Updates);384}385return true;386}387}388389return false;390}391392//===----------------------------------------------------------------------===//393// Local dead code elimination.394//395396/// isInstructionTriviallyDead - Return true if the result produced by the397/// instruction is not used, and the instruction has no side effects.398///399bool llvm::isInstructionTriviallyDead(Instruction *I,400const TargetLibraryInfo *TLI) {401if (!I->use_empty())402return false;403return wouldInstructionBeTriviallyDead(I, TLI);404}405406bool llvm::wouldInstructionBeTriviallyDeadOnUnusedPaths(407Instruction *I, const TargetLibraryInfo *TLI) {408// Instructions that are "markers" and have implied meaning on code around409// them (without explicit uses), are not dead on unused paths.410if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))411if (II->getIntrinsicID() == Intrinsic::stacksave ||412II->getIntrinsicID() == Intrinsic::launder_invariant_group ||413II->isLifetimeStartOrEnd())414return false;415return wouldInstructionBeTriviallyDead(I, TLI);416}417418bool llvm::wouldInstructionBeTriviallyDead(const Instruction *I,419const TargetLibraryInfo *TLI) {420if (I->isTerminator())421return false;422423// We don't want the landingpad-like instructions removed by anything this424// general.425if (I->isEHPad())426return false;427428// We don't want debug info removed by anything this general.429if (isa<DbgVariableIntrinsic>(I))430return false;431432if (const DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {433if (DLI->getLabel())434return false;435return true;436}437438if (auto *CB = dyn_cast<CallBase>(I))439if (isRemovableAlloc(CB, TLI))440return true;441442if (!I->willReturn()) {443auto *II = dyn_cast<IntrinsicInst>(I);444if (!II)445return false;446447switch (II->getIntrinsicID()) {448case Intrinsic::experimental_guard: {449// Guards on true are operationally no-ops. In the future we can450// consider more sophisticated tradeoffs for guards considering potential451// for check widening, but for now we keep things simple.452auto *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0));453return Cond && Cond->isOne();454}455// TODO: These intrinsics are not safe to remove, because this may remove456// a well-defined trap.457case Intrinsic::wasm_trunc_signed:458case Intrinsic::wasm_trunc_unsigned:459case Intrinsic::ptrauth_auth:460case Intrinsic::ptrauth_resign:461return true;462default:463return false;464}465}466467if (!I->mayHaveSideEffects())468return true;469470// Special case intrinsics that "may have side effects" but can be deleted471// when dead.472if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {473// Safe to delete llvm.stacksave and launder.invariant.group if dead.474if (II->getIntrinsicID() == Intrinsic::stacksave ||475II->getIntrinsicID() == Intrinsic::launder_invariant_group)476return true;477478// Intrinsics declare sideeffects to prevent them from moving, but they are479// nops without users.480if (II->getIntrinsicID() == Intrinsic::allow_runtime_check ||481II->getIntrinsicID() == Intrinsic::allow_ubsan_check)482return true;483484if (II->isLifetimeStartOrEnd()) {485auto *Arg = II->getArgOperand(1);486// Lifetime intrinsics are dead when their right-hand is undef.487if (isa<UndefValue>(Arg))488return true;489// If the right-hand is an alloc, global, or argument and the only uses490// are lifetime intrinsics then the intrinsics are dead.491if (isa<AllocaInst>(Arg) || isa<GlobalValue>(Arg) || isa<Argument>(Arg))492return llvm::all_of(Arg->uses(), [](Use &Use) {493if (IntrinsicInst *IntrinsicUse =494dyn_cast<IntrinsicInst>(Use.getUser()))495return IntrinsicUse->isLifetimeStartOrEnd();496return false;497});498return false;499}500501// Assumptions are dead if their condition is trivially true.502if (II->getIntrinsicID() == Intrinsic::assume &&503isAssumeWithEmptyBundle(cast<AssumeInst>(*II))) {504if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))505return !Cond->isZero();506507return false;508}509510if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I)) {511std::optional<fp::ExceptionBehavior> ExBehavior =512FPI->getExceptionBehavior();513return *ExBehavior != fp::ebStrict;514}515}516517if (auto *Call = dyn_cast<CallBase>(I)) {518if (Value *FreedOp = getFreedOperand(Call, TLI))519if (Constant *C = dyn_cast<Constant>(FreedOp))520return C->isNullValue() || isa<UndefValue>(C);521if (isMathLibCallNoop(Call, TLI))522return true;523}524525// Non-volatile atomic loads from constants can be removed.526if (auto *LI = dyn_cast<LoadInst>(I))527if (auto *GV = dyn_cast<GlobalVariable>(528LI->getPointerOperand()->stripPointerCasts()))529if (!LI->isVolatile() && GV->isConstant())530return true;531532return false;533}534535/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a536/// trivially dead instruction, delete it. If that makes any of its operands537/// trivially dead, delete them too, recursively. Return true if any538/// instructions were deleted.539bool llvm::RecursivelyDeleteTriviallyDeadInstructions(540Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU,541std::function<void(Value *)> AboutToDeleteCallback) {542Instruction *I = dyn_cast<Instruction>(V);543if (!I || !isInstructionTriviallyDead(I, TLI))544return false;545546SmallVector<WeakTrackingVH, 16> DeadInsts;547DeadInsts.push_back(I);548RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,549AboutToDeleteCallback);550551return true;552}553554bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(555SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,556MemorySSAUpdater *MSSAU,557std::function<void(Value *)> AboutToDeleteCallback) {558unsigned S = 0, E = DeadInsts.size(), Alive = 0;559for (; S != E; ++S) {560auto *I = dyn_cast_or_null<Instruction>(DeadInsts[S]);561if (!I || !isInstructionTriviallyDead(I)) {562DeadInsts[S] = nullptr;563++Alive;564}565}566if (Alive == E)567return false;568RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,569AboutToDeleteCallback);570return true;571}572573void llvm::RecursivelyDeleteTriviallyDeadInstructions(574SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,575MemorySSAUpdater *MSSAU,576std::function<void(Value *)> AboutToDeleteCallback) {577// Process the dead instruction list until empty.578while (!DeadInsts.empty()) {579Value *V = DeadInsts.pop_back_val();580Instruction *I = cast_or_null<Instruction>(V);581if (!I)582continue;583assert(isInstructionTriviallyDead(I, TLI) &&584"Live instruction found in dead worklist!");585assert(I->use_empty() && "Instructions with uses are not dead.");586587// Don't lose the debug info while deleting the instructions.588salvageDebugInfo(*I);589590if (AboutToDeleteCallback)591AboutToDeleteCallback(I);592593// Null out all of the instruction's operands to see if any operand becomes594// dead as we go.595for (Use &OpU : I->operands()) {596Value *OpV = OpU.get();597OpU.set(nullptr);598599if (!OpV->use_empty())600continue;601602// If the operand is an instruction that became dead as we nulled out the603// operand, and if it is 'trivially' dead, delete it in a future loop604// iteration.605if (Instruction *OpI = dyn_cast<Instruction>(OpV))606if (isInstructionTriviallyDead(OpI, TLI))607DeadInsts.push_back(OpI);608}609if (MSSAU)610MSSAU->removeMemoryAccess(I);611612I->eraseFromParent();613}614}615616bool llvm::replaceDbgUsesWithUndef(Instruction *I) {617SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;618SmallVector<DbgVariableRecord *, 1> DPUsers;619findDbgUsers(DbgUsers, I, &DPUsers);620for (auto *DII : DbgUsers)621DII->setKillLocation();622for (auto *DVR : DPUsers)623DVR->setKillLocation();624return !DbgUsers.empty() || !DPUsers.empty();625}626627/// areAllUsesEqual - Check whether the uses of a value are all the same.628/// This is similar to Instruction::hasOneUse() except this will also return629/// true when there are no uses or multiple uses that all refer to the same630/// value.631static bool areAllUsesEqual(Instruction *I) {632Value::user_iterator UI = I->user_begin();633Value::user_iterator UE = I->user_end();634if (UI == UE)635return true;636637User *TheUse = *UI;638for (++UI; UI != UE; ++UI) {639if (*UI != TheUse)640return false;641}642return true;643}644645/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively646/// dead PHI node, due to being a def-use chain of single-use nodes that647/// either forms a cycle or is terminated by a trivially dead instruction,648/// delete it. If that makes any of its operands trivially dead, delete them649/// too, recursively. Return true if a change was made.650bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,651const TargetLibraryInfo *TLI,652llvm::MemorySSAUpdater *MSSAU) {653SmallPtrSet<Instruction*, 4> Visited;654for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();655I = cast<Instruction>(*I->user_begin())) {656if (I->use_empty())657return RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);658659// If we find an instruction more than once, we're on a cycle that660// won't prove fruitful.661if (!Visited.insert(I).second) {662// Break the cycle and delete the instruction and its operands.663I->replaceAllUsesWith(PoisonValue::get(I->getType()));664(void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);665return true;666}667}668return false;669}670671static bool672simplifyAndDCEInstruction(Instruction *I,673SmallSetVector<Instruction *, 16> &WorkList,674const DataLayout &DL,675const TargetLibraryInfo *TLI) {676if (isInstructionTriviallyDead(I, TLI)) {677salvageDebugInfo(*I);678679// Null out all of the instruction's operands to see if any operand becomes680// dead as we go.681for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {682Value *OpV = I->getOperand(i);683I->setOperand(i, nullptr);684685if (!OpV->use_empty() || I == OpV)686continue;687688// If the operand is an instruction that became dead as we nulled out the689// operand, and if it is 'trivially' dead, delete it in a future loop690// iteration.691if (Instruction *OpI = dyn_cast<Instruction>(OpV))692if (isInstructionTriviallyDead(OpI, TLI))693WorkList.insert(OpI);694}695696I->eraseFromParent();697698return true;699}700701if (Value *SimpleV = simplifyInstruction(I, DL)) {702// Add the users to the worklist. CAREFUL: an instruction can use itself,703// in the case of a phi node.704for (User *U : I->users()) {705if (U != I) {706WorkList.insert(cast<Instruction>(U));707}708}709710// Replace the instruction with its simplified value.711bool Changed = false;712if (!I->use_empty()) {713I->replaceAllUsesWith(SimpleV);714Changed = true;715}716if (isInstructionTriviallyDead(I, TLI)) {717I->eraseFromParent();718Changed = true;719}720return Changed;721}722return false;723}724725/// SimplifyInstructionsInBlock - Scan the specified basic block and try to726/// simplify any instructions in it and recursively delete dead instructions.727///728/// This returns true if it changed the code, note that it can delete729/// instructions in other blocks as well in this block.730bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,731const TargetLibraryInfo *TLI) {732bool MadeChange = false;733const DataLayout &DL = BB->getDataLayout();734735#ifndef NDEBUG736// In debug builds, ensure that the terminator of the block is never replaced737// or deleted by these simplifications. The idea of simplification is that it738// cannot introduce new instructions, and there is no way to replace the739// terminator of a block without introducing a new instruction.740AssertingVH<Instruction> TerminatorVH(&BB->back());741#endif742743SmallSetVector<Instruction *, 16> WorkList;744// Iterate over the original function, only adding insts to the worklist745// if they actually need to be revisited. This avoids having to pre-init746// the worklist with the entire function's worth of instructions.747for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());748BI != E;) {749assert(!BI->isTerminator());750Instruction *I = &*BI;751++BI;752753// We're visiting this instruction now, so make sure it's not in the754// worklist from an earlier visit.755if (!WorkList.count(I))756MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);757}758759while (!WorkList.empty()) {760Instruction *I = WorkList.pop_back_val();761MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);762}763return MadeChange;764}765766//===----------------------------------------------------------------------===//767// Control Flow Graph Restructuring.768//769770void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,771DomTreeUpdater *DTU) {772773// If BB has single-entry PHI nodes, fold them.774while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {775Value *NewVal = PN->getIncomingValue(0);776// Replace self referencing PHI with poison, it must be dead.777if (NewVal == PN) NewVal = PoisonValue::get(PN->getType());778PN->replaceAllUsesWith(NewVal);779PN->eraseFromParent();780}781782BasicBlock *PredBB = DestBB->getSinglePredecessor();783assert(PredBB && "Block doesn't have a single predecessor!");784785bool ReplaceEntryBB = PredBB->isEntryBlock();786787// DTU updates: Collect all the edges that enter788// PredBB. These dominator edges will be redirected to DestBB.789SmallVector<DominatorTree::UpdateType, 32> Updates;790791if (DTU) {792// To avoid processing the same predecessor more than once.793SmallPtrSet<BasicBlock *, 2> SeenPreds;794Updates.reserve(Updates.size() + 2 * pred_size(PredBB) + 1);795for (BasicBlock *PredOfPredBB : predecessors(PredBB))796// This predecessor of PredBB may already have DestBB as a successor.797if (PredOfPredBB != PredBB)798if (SeenPreds.insert(PredOfPredBB).second)799Updates.push_back({DominatorTree::Insert, PredOfPredBB, DestBB});800SeenPreds.clear();801for (BasicBlock *PredOfPredBB : predecessors(PredBB))802if (SeenPreds.insert(PredOfPredBB).second)803Updates.push_back({DominatorTree::Delete, PredOfPredBB, PredBB});804Updates.push_back({DominatorTree::Delete, PredBB, DestBB});805}806807// Zap anything that took the address of DestBB. Not doing this will give the808// address an invalid value.809if (DestBB->hasAddressTaken()) {810BlockAddress *BA = BlockAddress::get(DestBB);811Constant *Replacement =812ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);813BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,814BA->getType()));815BA->destroyConstant();816}817818// Anything that branched to PredBB now branches to DestBB.819PredBB->replaceAllUsesWith(DestBB);820821// Splice all the instructions from PredBB to DestBB.822PredBB->getTerminator()->eraseFromParent();823DestBB->splice(DestBB->begin(), PredBB);824new UnreachableInst(PredBB->getContext(), PredBB);825826// If the PredBB is the entry block of the function, move DestBB up to827// become the entry block after we erase PredBB.828if (ReplaceEntryBB)829DestBB->moveAfter(PredBB);830831if (DTU) {832assert(PredBB->size() == 1 &&833isa<UnreachableInst>(PredBB->getTerminator()) &&834"The successor list of PredBB isn't empty before "835"applying corresponding DTU updates.");836DTU->applyUpdatesPermissive(Updates);837DTU->deleteBB(PredBB);838// Recalculation of DomTree is needed when updating a forward DomTree and839// the Entry BB is replaced.840if (ReplaceEntryBB && DTU->hasDomTree()) {841// The entry block was removed and there is no external interface for842// the dominator tree to be notified of this change. In this corner-case843// we recalculate the entire tree.844DTU->recalculate(*(DestBB->getParent()));845}846}847848else {849PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.850}851}852853/// Return true if we can choose one of these values to use in place of the854/// other. Note that we will always choose the non-undef value to keep.855static bool CanMergeValues(Value *First, Value *Second) {856return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);857}858859/// Return true if we can fold BB, an almost-empty BB ending in an unconditional860/// branch to Succ, into Succ.861///862/// Assumption: Succ is the single successor for BB.863static bool864CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ,865const SmallPtrSetImpl<BasicBlock *> &BBPreds) {866assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");867868LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "869<< Succ->getName() << "\n");870// Shortcut, if there is only a single predecessor it must be BB and merging871// is always safe872if (Succ->getSinglePredecessor())873return true;874875// Look at all the phi nodes in Succ, to see if they present a conflict when876// merging these blocks877for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {878PHINode *PN = cast<PHINode>(I);879880// If the incoming value from BB is again a PHINode in881// BB which has the same incoming value for *PI as PN does, we can882// merge the phi nodes and then the blocks can still be merged883PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));884if (BBPN && BBPN->getParent() == BB) {885for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {886BasicBlock *IBB = PN->getIncomingBlock(PI);887if (BBPreds.count(IBB) &&888!CanMergeValues(BBPN->getIncomingValueForBlock(IBB),889PN->getIncomingValue(PI))) {890LLVM_DEBUG(dbgs()891<< "Can't fold, phi node " << PN->getName() << " in "892<< Succ->getName() << " is conflicting with "893<< BBPN->getName() << " with regard to common predecessor "894<< IBB->getName() << "\n");895return false;896}897}898} else {899Value* Val = PN->getIncomingValueForBlock(BB);900for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {901// See if the incoming value for the common predecessor is equal to the902// one for BB, in which case this phi node will not prevent the merging903// of the block.904BasicBlock *IBB = PN->getIncomingBlock(PI);905if (BBPreds.count(IBB) &&906!CanMergeValues(Val, PN->getIncomingValue(PI))) {907LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()908<< " in " << Succ->getName()909<< " is conflicting with regard to common "910<< "predecessor " << IBB->getName() << "\n");911return false;912}913}914}915}916917return true;918}919920using PredBlockVector = SmallVector<BasicBlock *, 16>;921using IncomingValueMap = DenseMap<BasicBlock *, Value *>;922923/// Determines the value to use as the phi node input for a block.924///925/// Select between \p OldVal any value that we know flows from \p BB926/// to a particular phi on the basis of which one (if either) is not927/// undef. Update IncomingValues based on the selected value.928///929/// \param OldVal The value we are considering selecting.930/// \param BB The block that the value flows in from.931/// \param IncomingValues A map from block-to-value for other phi inputs932/// that we have examined.933///934/// \returns the selected value.935static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,936IncomingValueMap &IncomingValues) {937if (!isa<UndefValue>(OldVal)) {938assert((!IncomingValues.count(BB) ||939IncomingValues.find(BB)->second == OldVal) &&940"Expected OldVal to match incoming value from BB!");941942IncomingValues.insert(std::make_pair(BB, OldVal));943return OldVal;944}945946IncomingValueMap::const_iterator It = IncomingValues.find(BB);947if (It != IncomingValues.end()) return It->second;948949return OldVal;950}951952/// Create a map from block to value for the operands of a953/// given phi.954///955/// Create a map from block to value for each non-undef value flowing956/// into \p PN.957///958/// \param PN The phi we are collecting the map for.959/// \param IncomingValues [out] The map from block to value for this phi.960static void gatherIncomingValuesToPhi(PHINode *PN,961IncomingValueMap &IncomingValues) {962for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {963BasicBlock *BB = PN->getIncomingBlock(i);964Value *V = PN->getIncomingValue(i);965966if (!isa<UndefValue>(V))967IncomingValues.insert(std::make_pair(BB, V));968}969}970971/// Replace the incoming undef values to a phi with the values972/// from a block-to-value map.973///974/// \param PN The phi we are replacing the undefs in.975/// \param IncomingValues A map from block to value.976static void replaceUndefValuesInPhi(PHINode *PN,977const IncomingValueMap &IncomingValues) {978SmallVector<unsigned> TrueUndefOps;979for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {980Value *V = PN->getIncomingValue(i);981982if (!isa<UndefValue>(V)) continue;983984BasicBlock *BB = PN->getIncomingBlock(i);985IncomingValueMap::const_iterator It = IncomingValues.find(BB);986987// Keep track of undef/poison incoming values. Those must match, so we fix988// them up below if needed.989// Note: this is conservatively correct, but we could try harder and group990// the undef values per incoming basic block.991if (It == IncomingValues.end()) {992TrueUndefOps.push_back(i);993continue;994}995996// There is a defined value for this incoming block, so map this undef997// incoming value to the defined value.998PN->setIncomingValue(i, It->second);999}10001001// If there are both undef and poison values incoming, then convert those1002// values to undef. It is invalid to have different values for the same1003// incoming block.1004unsigned PoisonCount = count_if(TrueUndefOps, [&](unsigned i) {1005return isa<PoisonValue>(PN->getIncomingValue(i));1006});1007if (PoisonCount != 0 && PoisonCount != TrueUndefOps.size()) {1008for (unsigned i : TrueUndefOps)1009PN->setIncomingValue(i, UndefValue::get(PN->getType()));1010}1011}10121013// Only when they shares a single common predecessor, return true.1014// Only handles cases when BB can't be merged while its predecessors can be1015// redirected.1016static bool1017CanRedirectPredsOfEmptyBBToSucc(BasicBlock *BB, BasicBlock *Succ,1018const SmallPtrSetImpl<BasicBlock *> &BBPreds,1019const SmallPtrSetImpl<BasicBlock *> &SuccPreds,1020BasicBlock *&CommonPred) {10211022// There must be phis in BB, otherwise BB will be merged into Succ directly1023if (BB->phis().empty() || Succ->phis().empty())1024return false;10251026// BB must have predecessors not shared that can be redirected to Succ1027if (!BB->hasNPredecessorsOrMore(2))1028return false;10291030if (any_of(BBPreds, [](const BasicBlock *Pred) {1031return isa<IndirectBrInst>(Pred->getTerminator());1032}))1033return false;10341035// Get the single common predecessor of both BB and Succ. Return false1036// when there are more than one common predecessors.1037for (BasicBlock *SuccPred : SuccPreds) {1038if (BBPreds.count(SuccPred)) {1039if (CommonPred)1040return false;1041CommonPred = SuccPred;1042}1043}10441045return true;1046}10471048/// Replace a value flowing from a block to a phi with1049/// potentially multiple instances of that value flowing from the1050/// block's predecessors to the phi.1051///1052/// \param BB The block with the value flowing into the phi.1053/// \param BBPreds The predecessors of BB.1054/// \param PN The phi that we are updating.1055/// \param CommonPred The common predecessor of BB and PN's BasicBlock1056static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,1057const PredBlockVector &BBPreds,1058PHINode *PN,1059BasicBlock *CommonPred) {1060Value *OldVal = PN->removeIncomingValue(BB, false);1061assert(OldVal && "No entry in PHI for Pred BB!");10621063IncomingValueMap IncomingValues;10641065// We are merging two blocks - BB, and the block containing PN - and1066// as a result we need to redirect edges from the predecessors of BB1067// to go to the block containing PN, and update PN1068// accordingly. Since we allow merging blocks in the case where the1069// predecessor and successor blocks both share some predecessors,1070// and where some of those common predecessors might have undef1071// values flowing into PN, we want to rewrite those values to be1072// consistent with the non-undef values.10731074gatherIncomingValuesToPhi(PN, IncomingValues);10751076// If this incoming value is one of the PHI nodes in BB, the new entries1077// in the PHI node are the entries from the old PHI.1078if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {1079PHINode *OldValPN = cast<PHINode>(OldVal);1080for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {1081// Note that, since we are merging phi nodes and BB and Succ might1082// have common predecessors, we could end up with a phi node with1083// identical incoming branches. This will be cleaned up later (and1084// will trigger asserts if we try to clean it up now, without also1085// simplifying the corresponding conditional branch).1086BasicBlock *PredBB = OldValPN->getIncomingBlock(i);10871088if (PredBB == CommonPred)1089continue;10901091Value *PredVal = OldValPN->getIncomingValue(i);1092Value *Selected =1093selectIncomingValueForBlock(PredVal, PredBB, IncomingValues);10941095// And add a new incoming value for this predecessor for the1096// newly retargeted branch.1097PN->addIncoming(Selected, PredBB);1098}1099if (CommonPred)1100PN->addIncoming(OldValPN->getIncomingValueForBlock(CommonPred), BB);11011102} else {1103for (BasicBlock *PredBB : BBPreds) {1104// Update existing incoming values in PN for this1105// predecessor of BB.1106if (PredBB == CommonPred)1107continue;11081109Value *Selected =1110selectIncomingValueForBlock(OldVal, PredBB, IncomingValues);11111112// And add a new incoming value for this predecessor for the1113// newly retargeted branch.1114PN->addIncoming(Selected, PredBB);1115}1116if (CommonPred)1117PN->addIncoming(OldVal, BB);1118}11191120replaceUndefValuesInPhi(PN, IncomingValues);1121}11221123bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,1124DomTreeUpdater *DTU) {1125assert(BB != &BB->getParent()->getEntryBlock() &&1126"TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");11271128// We can't simplify infinite loops.1129BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);1130if (BB == Succ)1131return false;11321133SmallPtrSet<BasicBlock *, 16> BBPreds(pred_begin(BB), pred_end(BB));1134SmallPtrSet<BasicBlock *, 16> SuccPreds(pred_begin(Succ), pred_end(Succ));11351136// The single common predecessor of BB and Succ when BB cannot be killed1137BasicBlock *CommonPred = nullptr;11381139bool BBKillable = CanPropagatePredecessorsForPHIs(BB, Succ, BBPreds);11401141// Even if we can not fold BB into Succ, we may be able to redirect the1142// predecessors of BB to Succ.1143bool BBPhisMergeable =1144BBKillable ||1145CanRedirectPredsOfEmptyBBToSucc(BB, Succ, BBPreds, SuccPreds, CommonPred);11461147if (!BBKillable && !BBPhisMergeable)1148return false;11491150// Check to see if merging these blocks/phis would cause conflicts for any of1151// the phi nodes in BB or Succ. If not, we can safely merge.11521153// Check for cases where Succ has multiple predecessors and a PHI node in BB1154// has uses which will not disappear when the PHI nodes are merged. It is1155// possible to handle such cases, but difficult: it requires checking whether1156// BB dominates Succ, which is non-trivial to calculate in the case where1157// Succ has multiple predecessors. Also, it requires checking whether1158// constructing the necessary self-referential PHI node doesn't introduce any1159// conflicts; this isn't too difficult, but the previous code for doing this1160// was incorrect.1161//1162// Note that if this check finds a live use, BB dominates Succ, so BB is1163// something like a loop pre-header (or rarely, a part of an irreducible CFG);1164// folding the branch isn't profitable in that case anyway.1165if (!Succ->getSinglePredecessor()) {1166BasicBlock::iterator BBI = BB->begin();1167while (isa<PHINode>(*BBI)) {1168for (Use &U : BBI->uses()) {1169if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {1170if (PN->getIncomingBlock(U) != BB)1171return false;1172} else {1173return false;1174}1175}1176++BBI;1177}1178}11791180if (BBPhisMergeable && CommonPred)1181LLVM_DEBUG(dbgs() << "Found Common Predecessor between: " << BB->getName()1182<< " and " << Succ->getName() << " : "1183<< CommonPred->getName() << "\n");11841185// 'BB' and 'BB->Pred' are loop latches, bail out to presrve inner loop1186// metadata.1187//1188// FIXME: This is a stop-gap solution to preserve inner-loop metadata given1189// current status (that loop metadata is implemented as metadata attached to1190// the branch instruction in the loop latch block). To quote from review1191// comments, "the current representation of loop metadata (using a loop latch1192// terminator attachment) is known to be fundamentally broken. Loop latches1193// are not uniquely associated with loops (both in that a latch can be part of1194// multiple loops and a loop may have multiple latches). Loop headers are. The1195// solution to this problem is also known: Add support for basic block1196// metadata, and attach loop metadata to the loop header."1197//1198// Why bail out:1199// In this case, we expect 'BB' is the latch for outer-loop and 'BB->Pred' is1200// the latch for inner-loop (see reason below), so bail out to prerserve1201// inner-loop metadata rather than eliminating 'BB' and attaching its metadata1202// to this inner-loop.1203// - The reason we believe 'BB' and 'BB->Pred' have different inner-most1204// loops: assuming 'BB' and 'BB->Pred' are from the same inner-most loop L,1205// then 'BB' is the header and latch of 'L' and thereby 'L' must consist of1206// one self-looping basic block, which is contradictory with the assumption.1207//1208// To illustrate how inner-loop metadata is dropped:1209//1210// CFG Before1211//1212// BB is while.cond.exit, attached with loop metdata md2.1213// BB->Pred is for.body, attached with loop metadata md1.1214//1215// entry1216// |1217// v1218// ---> while.cond -------------> while.end1219// | |1220// | v1221// | while.body1222// | |1223// | v1224// | for.body <---- (md1)1225// | | |______|1226// | v1227// | while.cond.exit (md2)1228// | |1229// |_______|1230//1231// CFG After1232//1233// while.cond1 is the merge of while.cond.exit and while.cond above.1234// for.body is attached with md2, and md1 is dropped.1235// If LoopSimplify runs later (as a part of loop pass), it could create1236// dedicated exits for inner-loop (essentially adding `while.cond.exit`1237// back), but won't it won't see 'md1' nor restore it for the inner-loop.1238//1239// entry1240// |1241// v1242// ---> while.cond1 -------------> while.end1243// | |1244// | v1245// | while.body1246// | |1247// | v1248// | for.body <---- (md2)1249// |_______| |______|1250if (Instruction *TI = BB->getTerminator())1251if (TI->hasMetadata(LLVMContext::MD_loop))1252for (BasicBlock *Pred : predecessors(BB))1253if (Instruction *PredTI = Pred->getTerminator())1254if (PredTI->hasMetadata(LLVMContext::MD_loop))1255return false;12561257if (BBKillable)1258LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);1259else if (BBPhisMergeable)1260LLVM_DEBUG(dbgs() << "Merge Phis in Trivial BB: \n" << *BB);12611262SmallVector<DominatorTree::UpdateType, 32> Updates;12631264if (DTU) {1265// To avoid processing the same predecessor more than once.1266SmallPtrSet<BasicBlock *, 8> SeenPreds;1267// All predecessors of BB (except the common predecessor) will be moved to1268// Succ.1269Updates.reserve(Updates.size() + 2 * pred_size(BB) + 1);12701271for (auto *PredOfBB : predecessors(BB)) {1272// Do not modify those common predecessors of BB and Succ1273if (!SuccPreds.contains(PredOfBB))1274if (SeenPreds.insert(PredOfBB).second)1275Updates.push_back({DominatorTree::Insert, PredOfBB, Succ});1276}12771278SeenPreds.clear();12791280for (auto *PredOfBB : predecessors(BB))1281// When BB cannot be killed, do not remove the edge between BB and1282// CommonPred.1283if (SeenPreds.insert(PredOfBB).second && PredOfBB != CommonPred)1284Updates.push_back({DominatorTree::Delete, PredOfBB, BB});12851286if (BBKillable)1287Updates.push_back({DominatorTree::Delete, BB, Succ});1288}12891290if (isa<PHINode>(Succ->begin())) {1291// If there is more than one pred of succ, and there are PHI nodes in1292// the successor, then we need to add incoming edges for the PHI nodes1293//1294const PredBlockVector BBPreds(predecessors(BB));12951296// Loop over all of the PHI nodes in the successor of BB.1297for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {1298PHINode *PN = cast<PHINode>(I);1299redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN, CommonPred);1300}1301}13021303if (Succ->getSinglePredecessor()) {1304// BB is the only predecessor of Succ, so Succ will end up with exactly1305// the same predecessors BB had.1306// Copy over any phi, debug or lifetime instruction.1307BB->getTerminator()->eraseFromParent();1308Succ->splice(Succ->getFirstNonPHIIt(), BB);1309} else {1310while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {1311// We explicitly check for such uses for merging phis.1312assert(PN->use_empty() && "There shouldn't be any uses here!");1313PN->eraseFromParent();1314}1315}13161317// If the unconditional branch we replaced contains llvm.loop metadata, we1318// add the metadata to the branch instructions in the predecessors.1319if (Instruction *TI = BB->getTerminator())1320if (MDNode *LoopMD = TI->getMetadata(LLVMContext::MD_loop))1321for (BasicBlock *Pred : predecessors(BB))1322Pred->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopMD);13231324if (BBKillable) {1325// Everything that jumped to BB now goes to Succ.1326BB->replaceAllUsesWith(Succ);13271328if (!Succ->hasName())1329Succ->takeName(BB);13301331// Clear the successor list of BB to match updates applying to DTU later.1332if (BB->getTerminator())1333BB->back().eraseFromParent();13341335new UnreachableInst(BB->getContext(), BB);1336assert(succ_empty(BB) && "The successor list of BB isn't empty before "1337"applying corresponding DTU updates.");1338} else if (BBPhisMergeable) {1339// Everything except CommonPred that jumped to BB now goes to Succ.1340BB->replaceUsesWithIf(Succ, [BBPreds, CommonPred](Use &U) -> bool {1341if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser()))1342return UseInst->getParent() != CommonPred &&1343BBPreds.contains(UseInst->getParent());1344return false;1345});1346}13471348if (DTU)1349DTU->applyUpdates(Updates);13501351if (BBKillable)1352DeleteDeadBlock(BB, DTU);13531354return true;1355}13561357static bool1358EliminateDuplicatePHINodesNaiveImpl(BasicBlock *BB,1359SmallPtrSetImpl<PHINode *> &ToRemove) {1360// This implementation doesn't currently consider undef operands1361// specially. Theoretically, two phis which are identical except for1362// one having an undef where the other doesn't could be collapsed.13631364bool Changed = false;13651366// Examine each PHI.1367// Note that increment of I must *NOT* be in the iteration_expression, since1368// we don't want to immediately advance when we restart from the beginning.1369for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I);) {1370++I;1371// Is there an identical PHI node in this basic block?1372// Note that we only look in the upper square's triangle,1373// we already checked that the lower triangle PHI's aren't identical.1374for (auto J = I; PHINode *DuplicatePN = dyn_cast<PHINode>(J); ++J) {1375if (ToRemove.contains(DuplicatePN))1376continue;1377if (!DuplicatePN->isIdenticalToWhenDefined(PN))1378continue;1379// A duplicate. Replace this PHI with the base PHI.1380++NumPHICSEs;1381DuplicatePN->replaceAllUsesWith(PN);1382ToRemove.insert(DuplicatePN);1383Changed = true;13841385// The RAUW can change PHIs that we already visited.1386I = BB->begin();1387break; // Start over from the beginning.1388}1389}1390return Changed;1391}13921393static bool1394EliminateDuplicatePHINodesSetBasedImpl(BasicBlock *BB,1395SmallPtrSetImpl<PHINode *> &ToRemove) {1396// This implementation doesn't currently consider undef operands1397// specially. Theoretically, two phis which are identical except for1398// one having an undef where the other doesn't could be collapsed.13991400struct PHIDenseMapInfo {1401static PHINode *getEmptyKey() {1402return DenseMapInfo<PHINode *>::getEmptyKey();1403}14041405static PHINode *getTombstoneKey() {1406return DenseMapInfo<PHINode *>::getTombstoneKey();1407}14081409static bool isSentinel(PHINode *PN) {1410return PN == getEmptyKey() || PN == getTombstoneKey();1411}14121413// WARNING: this logic must be kept in sync with1414// Instruction::isIdenticalToWhenDefined()!1415static unsigned getHashValueImpl(PHINode *PN) {1416// Compute a hash value on the operands. Instcombine will likely have1417// sorted them, which helps expose duplicates, but we have to check all1418// the operands to be safe in case instcombine hasn't run.1419return static_cast<unsigned>(hash_combine(1420hash_combine_range(PN->value_op_begin(), PN->value_op_end()),1421hash_combine_range(PN->block_begin(), PN->block_end())));1422}14231424static unsigned getHashValue(PHINode *PN) {1425#ifndef NDEBUG1426// If -phicse-debug-hash was specified, return a constant -- this1427// will force all hashing to collide, so we'll exhaustively search1428// the table for a match, and the assertion in isEqual will fire if1429// there's a bug causing equal keys to hash differently.1430if (PHICSEDebugHash)1431return 0;1432#endif1433return getHashValueImpl(PN);1434}14351436static bool isEqualImpl(PHINode *LHS, PHINode *RHS) {1437if (isSentinel(LHS) || isSentinel(RHS))1438return LHS == RHS;1439return LHS->isIdenticalTo(RHS);1440}14411442static bool isEqual(PHINode *LHS, PHINode *RHS) {1443// These comparisons are nontrivial, so assert that equality implies1444// hash equality (DenseMap demands this as an invariant).1445bool Result = isEqualImpl(LHS, RHS);1446assert(!Result || (isSentinel(LHS) && LHS == RHS) ||1447getHashValueImpl(LHS) == getHashValueImpl(RHS));1448return Result;1449}1450};14511452// Set of unique PHINodes.1453DenseSet<PHINode *, PHIDenseMapInfo> PHISet;1454PHISet.reserve(4 * PHICSENumPHISmallSize);14551456// Examine each PHI.1457bool Changed = false;1458for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {1459if (ToRemove.contains(PN))1460continue;1461auto Inserted = PHISet.insert(PN);1462if (!Inserted.second) {1463// A duplicate. Replace this PHI with its duplicate.1464++NumPHICSEs;1465PN->replaceAllUsesWith(*Inserted.first);1466ToRemove.insert(PN);1467Changed = true;14681469// The RAUW can change PHIs that we already visited. Start over from the1470// beginning.1471PHISet.clear();1472I = BB->begin();1473}1474}14751476return Changed;1477}14781479bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB,1480SmallPtrSetImpl<PHINode *> &ToRemove) {1481if (1482#ifndef NDEBUG1483!PHICSEDebugHash &&1484#endif1485hasNItemsOrLess(BB->phis(), PHICSENumPHISmallSize))1486return EliminateDuplicatePHINodesNaiveImpl(BB, ToRemove);1487return EliminateDuplicatePHINodesSetBasedImpl(BB, ToRemove);1488}14891490bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {1491SmallPtrSet<PHINode *, 8> ToRemove;1492bool Changed = EliminateDuplicatePHINodes(BB, ToRemove);1493for (PHINode *PN : ToRemove)1494PN->eraseFromParent();1495return Changed;1496}14971498Align llvm::tryEnforceAlignment(Value *V, Align PrefAlign,1499const DataLayout &DL) {1500V = V->stripPointerCasts();15011502if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {1503// TODO: Ideally, this function would not be called if PrefAlign is smaller1504// than the current alignment, as the known bits calculation should have1505// already taken it into account. However, this is not always the case,1506// as computeKnownBits() has a depth limit, while stripPointerCasts()1507// doesn't.1508Align CurrentAlign = AI->getAlign();1509if (PrefAlign <= CurrentAlign)1510return CurrentAlign;15111512// If the preferred alignment is greater than the natural stack alignment1513// then don't round up. This avoids dynamic stack realignment.1514if (DL.exceedsNaturalStackAlignment(PrefAlign))1515return CurrentAlign;1516AI->setAlignment(PrefAlign);1517return PrefAlign;1518}15191520if (auto *GO = dyn_cast<GlobalObject>(V)) {1521// TODO: as above, this shouldn't be necessary.1522Align CurrentAlign = GO->getPointerAlignment(DL);1523if (PrefAlign <= CurrentAlign)1524return CurrentAlign;15251526// If there is a large requested alignment and we can, bump up the alignment1527// of the global. If the memory we set aside for the global may not be the1528// memory used by the final program then it is impossible for us to reliably1529// enforce the preferred alignment.1530if (!GO->canIncreaseAlignment())1531return CurrentAlign;15321533if (GO->isThreadLocal()) {1534unsigned MaxTLSAlign = GO->getParent()->getMaxTLSAlignment() / CHAR_BIT;1535if (MaxTLSAlign && PrefAlign > Align(MaxTLSAlign))1536PrefAlign = Align(MaxTLSAlign);1537}15381539GO->setAlignment(PrefAlign);1540return PrefAlign;1541}15421543return Align(1);1544}15451546Align llvm::getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,1547const DataLayout &DL,1548const Instruction *CxtI,1549AssumptionCache *AC,1550const DominatorTree *DT) {1551assert(V->getType()->isPointerTy() &&1552"getOrEnforceKnownAlignment expects a pointer!");15531554KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);1555unsigned TrailZ = Known.countMinTrailingZeros();15561557// Avoid trouble with ridiculously large TrailZ values, such as1558// those computed from a null pointer.1559// LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent).1560TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent);15611562Align Alignment = Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));15631564if (PrefAlign && *PrefAlign > Alignment)1565Alignment = std::max(Alignment, tryEnforceAlignment(V, *PrefAlign, DL));15661567// We don't need to make any adjustment.1568return Alignment;1569}15701571///===---------------------------------------------------------------------===//1572/// Dbg Intrinsic utilities1573///15741575/// See if there is a dbg.value intrinsic for DIVar for the PHI node.1576static bool PhiHasDebugValue(DILocalVariable *DIVar,1577DIExpression *DIExpr,1578PHINode *APN) {1579// Since we can't guarantee that the original dbg.declare intrinsic1580// is removed by LowerDbgDeclare(), we need to make sure that we are1581// not inserting the same dbg.value intrinsic over and over.1582SmallVector<DbgValueInst *, 1> DbgValues;1583SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;1584findDbgValues(DbgValues, APN, &DbgVariableRecords);1585for (auto *DVI : DbgValues) {1586assert(is_contained(DVI->getValues(), APN));1587if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))1588return true;1589}1590for (auto *DVR : DbgVariableRecords) {1591assert(is_contained(DVR->location_ops(), APN));1592if ((DVR->getVariable() == DIVar) && (DVR->getExpression() == DIExpr))1593return true;1594}1595return false;1596}15971598/// Check if the alloc size of \p ValTy is large enough to cover the variable1599/// (or fragment of the variable) described by \p DII.1600///1601/// This is primarily intended as a helper for the different1602/// ConvertDebugDeclareToDebugValue functions. The dbg.declare that is converted1603/// describes an alloca'd variable, so we need to use the alloc size of the1604/// value when doing the comparison. E.g. an i1 value will be identified as1605/// covering an n-bit fragment, if the store size of i1 is at least n bits.1606static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {1607const DataLayout &DL = DII->getDataLayout();1608TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);1609if (std::optional<uint64_t> FragmentSize =1610DII->getExpression()->getActiveBits(DII->getVariable()))1611return TypeSize::isKnownGE(ValueSize, TypeSize::getFixed(*FragmentSize));16121613// We can't always calculate the size of the DI variable (e.g. if it is a1614// VLA). Try to use the size of the alloca that the dbg intrinsic describes1615// intead.1616if (DII->isAddressOfVariable()) {1617// DII should have exactly 1 location when it is an address.1618assert(DII->getNumVariableLocationOps() == 1 &&1619"address of variable must have exactly 1 location operand.");1620if (auto *AI =1621dyn_cast_or_null<AllocaInst>(DII->getVariableLocationOp(0))) {1622if (std::optional<TypeSize> FragmentSize =1623AI->getAllocationSizeInBits(DL)) {1624return TypeSize::isKnownGE(ValueSize, *FragmentSize);1625}1626}1627}1628// Could not determine size of variable. Conservatively return false.1629return false;1630}1631// RemoveDIs: duplicate implementation of the above, using DbgVariableRecords,1632// the replacement for dbg.values.1633static bool valueCoversEntireFragment(Type *ValTy, DbgVariableRecord *DVR) {1634const DataLayout &DL = DVR->getModule()->getDataLayout();1635TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);1636if (std::optional<uint64_t> FragmentSize =1637DVR->getExpression()->getActiveBits(DVR->getVariable()))1638return TypeSize::isKnownGE(ValueSize, TypeSize::getFixed(*FragmentSize));16391640// We can't always calculate the size of the DI variable (e.g. if it is a1641// VLA). Try to use the size of the alloca that the dbg intrinsic describes1642// intead.1643if (DVR->isAddressOfVariable()) {1644// DVR should have exactly 1 location when it is an address.1645assert(DVR->getNumVariableLocationOps() == 1 &&1646"address of variable must have exactly 1 location operand.");1647if (auto *AI =1648dyn_cast_or_null<AllocaInst>(DVR->getVariableLocationOp(0))) {1649if (std::optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {1650return TypeSize::isKnownGE(ValueSize, *FragmentSize);1651}1652}1653}1654// Could not determine size of variable. Conservatively return false.1655return false;1656}16571658static void insertDbgValueOrDbgVariableRecord(DIBuilder &Builder, Value *DV,1659DILocalVariable *DIVar,1660DIExpression *DIExpr,1661const DebugLoc &NewLoc,1662BasicBlock::iterator Instr) {1663if (!UseNewDbgInfoFormat) {1664auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,1665(Instruction *)nullptr);1666DbgVal.get<Instruction *>()->insertBefore(Instr);1667} else {1668// RemoveDIs: if we're using the new debug-info format, allocate a1669// DbgVariableRecord directly instead of a dbg.value intrinsic.1670ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);1671DbgVariableRecord *DV =1672new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());1673Instr->getParent()->insertDbgRecordBefore(DV, Instr);1674}1675}16761677static void insertDbgValueOrDbgVariableRecordAfter(1678DIBuilder &Builder, Value *DV, DILocalVariable *DIVar, DIExpression *DIExpr,1679const DebugLoc &NewLoc, BasicBlock::iterator Instr) {1680if (!UseNewDbgInfoFormat) {1681auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,1682(Instruction *)nullptr);1683DbgVal.get<Instruction *>()->insertAfter(&*Instr);1684} else {1685// RemoveDIs: if we're using the new debug-info format, allocate a1686// DbgVariableRecord directly instead of a dbg.value intrinsic.1687ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);1688DbgVariableRecord *DV =1689new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());1690Instr->getParent()->insertDbgRecordAfter(DV, &*Instr);1691}1692}16931694/// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value1695/// that has an associated llvm.dbg.declare intrinsic.1696void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,1697StoreInst *SI, DIBuilder &Builder) {1698assert(DII->isAddressOfVariable() || isa<DbgAssignIntrinsic>(DII));1699auto *DIVar = DII->getVariable();1700assert(DIVar && "Missing variable");1701auto *DIExpr = DII->getExpression();1702Value *DV = SI->getValueOperand();17031704DebugLoc NewLoc = getDebugValueLoc(DII);17051706// If the alloca describes the variable itself, i.e. the expression in the1707// dbg.declare doesn't start with a dereference, we can perform the1708// conversion if the value covers the entire fragment of DII.1709// If the alloca describes the *address* of DIVar, i.e. DIExpr is1710// *just* a DW_OP_deref, we use DV as is for the dbg.value.1711// We conservatively ignore other dereferences, because the following two are1712// not equivalent:1713// dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))1714// dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))1715// The former is adding 2 to the address of the variable, whereas the latter1716// is adding 2 to the value of the variable. As such, we insist on just a1717// deref expression.1718bool CanConvert =1719DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&1720valueCoversEntireFragment(DV->getType(), DII));1721if (CanConvert) {1722insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,1723SI->getIterator());1724return;1725}17261727// FIXME: If storing to a part of the variable described by the dbg.declare,1728// then we want to insert a dbg.value for the corresponding fragment.1729LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " << *DII1730<< '\n');1731// For now, when there is a store to parts of the variable (but we do not1732// know which part) we insert an dbg.value intrinsic to indicate that we1733// know nothing about the variable's content.1734DV = UndefValue::get(DV->getType());1735insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,1736SI->getIterator());1737}17381739/// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value1740/// that has an associated llvm.dbg.declare intrinsic.1741void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,1742LoadInst *LI, DIBuilder &Builder) {1743auto *DIVar = DII->getVariable();1744auto *DIExpr = DII->getExpression();1745assert(DIVar && "Missing variable");17461747if (!valueCoversEntireFragment(LI->getType(), DII)) {1748// FIXME: If only referring to a part of the variable described by the1749// dbg.declare, then we want to insert a dbg.value for the corresponding1750// fragment.1751LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "1752<< *DII << '\n');1753return;1754}17551756DebugLoc NewLoc = getDebugValueLoc(DII);17571758// We are now tracking the loaded value instead of the address. In the1759// future if multi-location support is added to the IR, it might be1760// preferable to keep tracking both the loaded value and the original1761// address in case the alloca can not be elided.1762insertDbgValueOrDbgVariableRecordAfter(Builder, LI, DIVar, DIExpr, NewLoc,1763LI->getIterator());1764}17651766void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,1767StoreInst *SI, DIBuilder &Builder) {1768assert(DVR->isAddressOfVariable() || DVR->isDbgAssign());1769auto *DIVar = DVR->getVariable();1770assert(DIVar && "Missing variable");1771auto *DIExpr = DVR->getExpression();1772Value *DV = SI->getValueOperand();17731774DebugLoc NewLoc = getDebugValueLoc(DVR);17751776// If the alloca describes the variable itself, i.e. the expression in the1777// dbg.declare doesn't start with a dereference, we can perform the1778// conversion if the value covers the entire fragment of DII.1779// If the alloca describes the *address* of DIVar, i.e. DIExpr is1780// *just* a DW_OP_deref, we use DV as is for the dbg.value.1781// We conservatively ignore other dereferences, because the following two are1782// not equivalent:1783// dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))1784// dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))1785// The former is adding 2 to the address of the variable, whereas the latter1786// is adding 2 to the value of the variable. As such, we insist on just a1787// deref expression.1788bool CanConvert =1789DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&1790valueCoversEntireFragment(DV->getType(), DVR));1791if (CanConvert) {1792insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,1793SI->getIterator());1794return;1795}17961797// FIXME: If storing to a part of the variable described by the dbg.declare,1798// then we want to insert a dbg.value for the corresponding fragment.1799LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " << *DVR1800<< '\n');1801assert(UseNewDbgInfoFormat);18021803// For now, when there is a store to parts of the variable (but we do not1804// know which part) we insert an dbg.value intrinsic to indicate that we1805// know nothing about the variable's content.1806DV = UndefValue::get(DV->getType());1807ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);1808DbgVariableRecord *NewDVR =1809new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());1810SI->getParent()->insertDbgRecordBefore(NewDVR, SI->getIterator());1811}18121813/// Inserts a llvm.dbg.value intrinsic after a phi that has an associated1814/// llvm.dbg.declare intrinsic.1815void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,1816PHINode *APN, DIBuilder &Builder) {1817auto *DIVar = DII->getVariable();1818auto *DIExpr = DII->getExpression();1819assert(DIVar && "Missing variable");18201821if (PhiHasDebugValue(DIVar, DIExpr, APN))1822return;18231824if (!valueCoversEntireFragment(APN->getType(), DII)) {1825// FIXME: If only referring to a part of the variable described by the1826// dbg.declare, then we want to insert a dbg.value for the corresponding1827// fragment.1828LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "1829<< *DII << '\n');1830return;1831}18321833BasicBlock *BB = APN->getParent();1834auto InsertionPt = BB->getFirstInsertionPt();18351836DebugLoc NewLoc = getDebugValueLoc(DII);18371838// The block may be a catchswitch block, which does not have a valid1839// insertion point.1840// FIXME: Insert dbg.value markers in the successors when appropriate.1841if (InsertionPt != BB->end()) {1842insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,1843InsertionPt);1844}1845}18461847void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, LoadInst *LI,1848DIBuilder &Builder) {1849auto *DIVar = DVR->getVariable();1850auto *DIExpr = DVR->getExpression();1851assert(DIVar && "Missing variable");18521853if (!valueCoversEntireFragment(LI->getType(), DVR)) {1854// FIXME: If only referring to a part of the variable described by the1855// dbg.declare, then we want to insert a DbgVariableRecord for the1856// corresponding fragment.1857LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "1858<< *DVR << '\n');1859return;1860}18611862DebugLoc NewLoc = getDebugValueLoc(DVR);18631864// We are now tracking the loaded value instead of the address. In the1865// future if multi-location support is added to the IR, it might be1866// preferable to keep tracking both the loaded value and the original1867// address in case the alloca can not be elided.1868assert(UseNewDbgInfoFormat);18691870// Create a DbgVariableRecord directly and insert.1871ValueAsMetadata *LIVAM = ValueAsMetadata::get(LI);1872DbgVariableRecord *DV =1873new DbgVariableRecord(LIVAM, DIVar, DIExpr, NewLoc.get());1874LI->getParent()->insertDbgRecordAfter(DV, LI);1875}18761877/// Determine whether this alloca is either a VLA or an array.1878static bool isArray(AllocaInst *AI) {1879return AI->isArrayAllocation() ||1880(AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());1881}18821883/// Determine whether this alloca is a structure.1884static bool isStructure(AllocaInst *AI) {1885return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();1886}1887void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, PHINode *APN,1888DIBuilder &Builder) {1889auto *DIVar = DVR->getVariable();1890auto *DIExpr = DVR->getExpression();1891assert(DIVar && "Missing variable");18921893if (PhiHasDebugValue(DIVar, DIExpr, APN))1894return;18951896if (!valueCoversEntireFragment(APN->getType(), DVR)) {1897// FIXME: If only referring to a part of the variable described by the1898// dbg.declare, then we want to insert a DbgVariableRecord for the1899// corresponding fragment.1900LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "1901<< *DVR << '\n');1902return;1903}19041905BasicBlock *BB = APN->getParent();1906auto InsertionPt = BB->getFirstInsertionPt();19071908DebugLoc NewLoc = getDebugValueLoc(DVR);19091910// The block may be a catchswitch block, which does not have a valid1911// insertion point.1912// FIXME: Insert DbgVariableRecord markers in the successors when appropriate.1913if (InsertionPt != BB->end()) {1914insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,1915InsertionPt);1916}1917}19181919/// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set1920/// of llvm.dbg.value intrinsics.1921bool llvm::LowerDbgDeclare(Function &F) {1922bool Changed = false;1923DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);1924SmallVector<DbgDeclareInst *, 4> Dbgs;1925SmallVector<DbgVariableRecord *> DVRs;1926for (auto &FI : F) {1927for (Instruction &BI : FI) {1928if (auto *DDI = dyn_cast<DbgDeclareInst>(&BI))1929Dbgs.push_back(DDI);1930for (DbgVariableRecord &DVR : filterDbgVars(BI.getDbgRecordRange())) {1931if (DVR.getType() == DbgVariableRecord::LocationType::Declare)1932DVRs.push_back(&DVR);1933}1934}1935}19361937if (Dbgs.empty() && DVRs.empty())1938return Changed;19391940auto LowerOne = [&](auto *DDI) {1941AllocaInst *AI =1942dyn_cast_or_null<AllocaInst>(DDI->getVariableLocationOp(0));1943// If this is an alloca for a scalar variable, insert a dbg.value1944// at each load and store to the alloca and erase the dbg.declare.1945// The dbg.values allow tracking a variable even if it is not1946// stored on the stack, while the dbg.declare can only describe1947// the stack slot (and at a lexical-scope granularity). Later1948// passes will attempt to elide the stack slot.1949if (!AI || isArray(AI) || isStructure(AI))1950return;19511952// A volatile load/store means that the alloca can't be elided anyway.1953if (llvm::any_of(AI->users(), [](User *U) -> bool {1954if (LoadInst *LI = dyn_cast<LoadInst>(U))1955return LI->isVolatile();1956if (StoreInst *SI = dyn_cast<StoreInst>(U))1957return SI->isVolatile();1958return false;1959}))1960return;19611962SmallVector<const Value *, 8> WorkList;1963WorkList.push_back(AI);1964while (!WorkList.empty()) {1965const Value *V = WorkList.pop_back_val();1966for (const auto &AIUse : V->uses()) {1967User *U = AIUse.getUser();1968if (StoreInst *SI = dyn_cast<StoreInst>(U)) {1969if (AIUse.getOperandNo() == 1)1970ConvertDebugDeclareToDebugValue(DDI, SI, DIB);1971} else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {1972ConvertDebugDeclareToDebugValue(DDI, LI, DIB);1973} else if (CallInst *CI = dyn_cast<CallInst>(U)) {1974// This is a call by-value or some other instruction that takes a1975// pointer to the variable. Insert a *value* intrinsic that describes1976// the variable by dereferencing the alloca.1977if (!CI->isLifetimeStartOrEnd()) {1978DebugLoc NewLoc = getDebugValueLoc(DDI);1979auto *DerefExpr =1980DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);1981insertDbgValueOrDbgVariableRecord(DIB, AI, DDI->getVariable(),1982DerefExpr, NewLoc,1983CI->getIterator());1984}1985} else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {1986if (BI->getType()->isPointerTy())1987WorkList.push_back(BI);1988}1989}1990}1991DDI->eraseFromParent();1992Changed = true;1993};19941995for_each(Dbgs, LowerOne);1996for_each(DVRs, LowerOne);19971998if (Changed)1999for (BasicBlock &BB : F)2000RemoveRedundantDbgInstrs(&BB);20012002return Changed;2003}20042005// RemoveDIs: re-implementation of insertDebugValuesForPHIs, but which pulls the2006// debug-info out of the block's DbgVariableRecords rather than dbg.value2007// intrinsics.2008static void2009insertDbgVariableRecordsForPHIs(BasicBlock *BB,2010SmallVectorImpl<PHINode *> &InsertedPHIs) {2011assert(BB && "No BasicBlock to clone DbgVariableRecord(s) from.");2012if (InsertedPHIs.size() == 0)2013return;20142015// Map existing PHI nodes to their DbgVariableRecords.2016DenseMap<Value *, DbgVariableRecord *> DbgValueMap;2017for (auto &I : *BB) {2018for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {2019for (Value *V : DVR.location_ops())2020if (auto *Loc = dyn_cast_or_null<PHINode>(V))2021DbgValueMap.insert({Loc, &DVR});2022}2023}2024if (DbgValueMap.size() == 0)2025return;20262027// Map a pair of the destination BB and old DbgVariableRecord to the new2028// DbgVariableRecord, so that if a DbgVariableRecord is being rewritten to use2029// more than one of the inserted PHIs in the same destination BB, we can2030// update the same DbgVariableRecord with all the new PHIs instead of creating2031// one copy for each.2032MapVector<std::pair<BasicBlock *, DbgVariableRecord *>, DbgVariableRecord *>2033NewDbgValueMap;2034// Then iterate through the new PHIs and look to see if they use one of the2035// previously mapped PHIs. If so, create a new DbgVariableRecord that will2036// propagate the info through the new PHI. If we use more than one new PHI in2037// a single destination BB with the same old dbg.value, merge the updates so2038// that we get a single new DbgVariableRecord with all the new PHIs.2039for (auto PHI : InsertedPHIs) {2040BasicBlock *Parent = PHI->getParent();2041// Avoid inserting a debug-info record into an EH block.2042if (Parent->getFirstNonPHI()->isEHPad())2043continue;2044for (auto VI : PHI->operand_values()) {2045auto V = DbgValueMap.find(VI);2046if (V != DbgValueMap.end()) {2047DbgVariableRecord *DbgII = cast<DbgVariableRecord>(V->second);2048auto NewDI = NewDbgValueMap.find({Parent, DbgII});2049if (NewDI == NewDbgValueMap.end()) {2050DbgVariableRecord *NewDbgII = DbgII->clone();2051NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;2052}2053DbgVariableRecord *NewDbgII = NewDI->second;2054// If PHI contains VI as an operand more than once, we may2055// replaced it in NewDbgII; confirm that it is present.2056if (is_contained(NewDbgII->location_ops(), VI))2057NewDbgII->replaceVariableLocationOp(VI, PHI);2058}2059}2060}2061// Insert the new DbgVariableRecords into their destination blocks.2062for (auto DI : NewDbgValueMap) {2063BasicBlock *Parent = DI.first.first;2064DbgVariableRecord *NewDbgII = DI.second;2065auto InsertionPt = Parent->getFirstInsertionPt();2066assert(InsertionPt != Parent->end() && "Ill-formed basic block");20672068Parent->insertDbgRecordBefore(NewDbgII, InsertionPt);2069}2070}20712072/// Propagate dbg.value intrinsics through the newly inserted PHIs.2073void llvm::insertDebugValuesForPHIs(BasicBlock *BB,2074SmallVectorImpl<PHINode *> &InsertedPHIs) {2075assert(BB && "No BasicBlock to clone dbg.value(s) from.");2076if (InsertedPHIs.size() == 0)2077return;20782079insertDbgVariableRecordsForPHIs(BB, InsertedPHIs);20802081// Map existing PHI nodes to their dbg.values.2082ValueToValueMapTy DbgValueMap;2083for (auto &I : *BB) {2084if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {2085for (Value *V : DbgII->location_ops())2086if (auto *Loc = dyn_cast_or_null<PHINode>(V))2087DbgValueMap.insert({Loc, DbgII});2088}2089}2090if (DbgValueMap.size() == 0)2091return;20922093// Map a pair of the destination BB and old dbg.value to the new dbg.value,2094// so that if a dbg.value is being rewritten to use more than one of the2095// inserted PHIs in the same destination BB, we can update the same dbg.value2096// with all the new PHIs instead of creating one copy for each.2097MapVector<std::pair<BasicBlock *, DbgVariableIntrinsic *>,2098DbgVariableIntrinsic *>2099NewDbgValueMap;2100// Then iterate through the new PHIs and look to see if they use one of the2101// previously mapped PHIs. If so, create a new dbg.value intrinsic that will2102// propagate the info through the new PHI. If we use more than one new PHI in2103// a single destination BB with the same old dbg.value, merge the updates so2104// that we get a single new dbg.value with all the new PHIs.2105for (auto *PHI : InsertedPHIs) {2106BasicBlock *Parent = PHI->getParent();2107// Avoid inserting an intrinsic into an EH block.2108if (Parent->getFirstNonPHI()->isEHPad())2109continue;2110for (auto *VI : PHI->operand_values()) {2111auto V = DbgValueMap.find(VI);2112if (V != DbgValueMap.end()) {2113auto *DbgII = cast<DbgVariableIntrinsic>(V->second);2114auto NewDI = NewDbgValueMap.find({Parent, DbgII});2115if (NewDI == NewDbgValueMap.end()) {2116auto *NewDbgII = cast<DbgVariableIntrinsic>(DbgII->clone());2117NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;2118}2119DbgVariableIntrinsic *NewDbgII = NewDI->second;2120// If PHI contains VI as an operand more than once, we may2121// replaced it in NewDbgII; confirm that it is present.2122if (is_contained(NewDbgII->location_ops(), VI))2123NewDbgII->replaceVariableLocationOp(VI, PHI);2124}2125}2126}2127// Insert thew new dbg.values into their destination blocks.2128for (auto DI : NewDbgValueMap) {2129BasicBlock *Parent = DI.first.first;2130auto *NewDbgII = DI.second;2131auto InsertionPt = Parent->getFirstInsertionPt();2132assert(InsertionPt != Parent->end() && "Ill-formed basic block");2133NewDbgII->insertBefore(&*InsertionPt);2134}2135}21362137bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,2138DIBuilder &Builder, uint8_t DIExprFlags,2139int Offset) {2140TinyPtrVector<DbgDeclareInst *> DbgDeclares = findDbgDeclares(Address);2141TinyPtrVector<DbgVariableRecord *> DVRDeclares = findDVRDeclares(Address);21422143auto ReplaceOne = [&](auto *DII) {2144assert(DII->getVariable() && "Missing variable");2145auto *DIExpr = DII->getExpression();2146DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);2147DII->setExpression(DIExpr);2148DII->replaceVariableLocationOp(Address, NewAddress);2149};21502151for_each(DbgDeclares, ReplaceOne);2152for_each(DVRDeclares, ReplaceOne);21532154return !DbgDeclares.empty() || !DVRDeclares.empty();2155}21562157static void updateOneDbgValueForAlloca(const DebugLoc &Loc,2158DILocalVariable *DIVar,2159DIExpression *DIExpr, Value *NewAddress,2160DbgValueInst *DVI,2161DbgVariableRecord *DVR,2162DIBuilder &Builder, int Offset) {2163assert(DIVar && "Missing variable");21642165// This is an alloca-based dbg.value/DbgVariableRecord. The first thing it2166// should do with the alloca pointer is dereference it. Otherwise we don't2167// know how to handle it and give up.2168if (!DIExpr || DIExpr->getNumElements() < 1 ||2169DIExpr->getElement(0) != dwarf::DW_OP_deref)2170return;21712172// Insert the offset before the first deref.2173if (Offset)2174DIExpr = DIExpression::prepend(DIExpr, 0, Offset);21752176if (DVI) {2177DVI->setExpression(DIExpr);2178DVI->replaceVariableLocationOp(0u, NewAddress);2179} else {2180assert(DVR);2181DVR->setExpression(DIExpr);2182DVR->replaceVariableLocationOp(0u, NewAddress);2183}2184}21852186void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,2187DIBuilder &Builder, int Offset) {2188SmallVector<DbgValueInst *, 1> DbgUsers;2189SmallVector<DbgVariableRecord *, 1> DPUsers;2190findDbgValues(DbgUsers, AI, &DPUsers);21912192// Attempt to replace dbg.values that use this alloca.2193for (auto *DVI : DbgUsers)2194updateOneDbgValueForAlloca(DVI->getDebugLoc(), DVI->getVariable(),2195DVI->getExpression(), NewAllocaAddress, DVI,2196nullptr, Builder, Offset);21972198// Replace any DbgVariableRecords that use this alloca.2199for (DbgVariableRecord *DVR : DPUsers)2200updateOneDbgValueForAlloca(DVR->getDebugLoc(), DVR->getVariable(),2201DVR->getExpression(), NewAllocaAddress, nullptr,2202DVR, Builder, Offset);2203}22042205/// Where possible to salvage debug information for \p I do so.2206/// If not possible mark undef.2207void llvm::salvageDebugInfo(Instruction &I) {2208SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;2209SmallVector<DbgVariableRecord *, 1> DPUsers;2210findDbgUsers(DbgUsers, &I, &DPUsers);2211salvageDebugInfoForDbgValues(I, DbgUsers, DPUsers);2212}22132214template <typename T> static void salvageDbgAssignAddress(T *Assign) {2215Instruction *I = dyn_cast<Instruction>(Assign->getAddress());2216// Only instructions can be salvaged at the moment.2217if (!I)2218return;22192220assert(!Assign->getAddressExpression()->getFragmentInfo().has_value() &&2221"address-expression shouldn't have fragment info");22222223// The address component of a dbg.assign cannot be variadic.2224uint64_t CurrentLocOps = 0;2225SmallVector<Value *, 4> AdditionalValues;2226SmallVector<uint64_t, 16> Ops;2227Value *NewV = salvageDebugInfoImpl(*I, CurrentLocOps, Ops, AdditionalValues);22282229// Check if the salvage failed.2230if (!NewV)2231return;22322233DIExpression *SalvagedExpr = DIExpression::appendOpsToArg(2234Assign->getAddressExpression(), Ops, 0, /*StackValue=*/false);2235assert(!SalvagedExpr->getFragmentInfo().has_value() &&2236"address-expression shouldn't have fragment info");22372238SalvagedExpr = SalvagedExpr->foldConstantMath();22392240// Salvage succeeds if no additional values are required.2241if (AdditionalValues.empty()) {2242Assign->setAddress(NewV);2243Assign->setAddressExpression(SalvagedExpr);2244} else {2245Assign->setKillAddress();2246}2247}22482249void llvm::salvageDebugInfoForDbgValues(2250Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers,2251ArrayRef<DbgVariableRecord *> DPUsers) {2252// These are arbitrary chosen limits on the maximum number of values and the2253// maximum size of a debug expression we can salvage up to, used for2254// performance reasons.2255const unsigned MaxDebugArgs = 16;2256const unsigned MaxExpressionSize = 128;2257bool Salvaged = false;22582259for (auto *DII : DbgUsers) {2260if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DII)) {2261if (DAI->getAddress() == &I) {2262salvageDbgAssignAddress(DAI);2263Salvaged = true;2264}2265if (DAI->getValue() != &I)2266continue;2267}22682269// Do not add DW_OP_stack_value for DbgDeclare, because they are implicitly2270// pointing out the value as a DWARF memory location description.2271bool StackValue = isa<DbgValueInst>(DII);2272auto DIILocation = DII->location_ops();2273assert(2274is_contained(DIILocation, &I) &&2275"DbgVariableIntrinsic must use salvaged instruction as its location");2276SmallVector<Value *, 4> AdditionalValues;2277// `I` may appear more than once in DII's location ops, and each use of `I`2278// must be updated in the DIExpression and potentially have additional2279// values added; thus we call salvageDebugInfoImpl for each `I` instance in2280// DIILocation.2281Value *Op0 = nullptr;2282DIExpression *SalvagedExpr = DII->getExpression();2283auto LocItr = find(DIILocation, &I);2284while (SalvagedExpr && LocItr != DIILocation.end()) {2285SmallVector<uint64_t, 16> Ops;2286unsigned LocNo = std::distance(DIILocation.begin(), LocItr);2287uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();2288Op0 = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);2289if (!Op0)2290break;2291SalvagedExpr =2292DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);2293LocItr = std::find(++LocItr, DIILocation.end(), &I);2294}2295// salvageDebugInfoImpl should fail on examining the first element of2296// DbgUsers, or none of them.2297if (!Op0)2298break;22992300SalvagedExpr = SalvagedExpr->foldConstantMath();2301DII->replaceVariableLocationOp(&I, Op0);2302bool IsValidSalvageExpr = SalvagedExpr->getNumElements() <= MaxExpressionSize;2303if (AdditionalValues.empty() && IsValidSalvageExpr) {2304DII->setExpression(SalvagedExpr);2305} else if (isa<DbgValueInst>(DII) && IsValidSalvageExpr &&2306DII->getNumVariableLocationOps() + AdditionalValues.size() <=2307MaxDebugArgs) {2308DII->addVariableLocationOps(AdditionalValues, SalvagedExpr);2309} else {2310// Do not salvage using DIArgList for dbg.declare, as it is not currently2311// supported in those instructions. Also do not salvage if the resulting2312// DIArgList would contain an unreasonably large number of values.2313DII->setKillLocation();2314}2315LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');2316Salvaged = true;2317}2318// Duplicate of above block for DbgVariableRecords.2319for (auto *DVR : DPUsers) {2320if (DVR->isDbgAssign()) {2321if (DVR->getAddress() == &I) {2322salvageDbgAssignAddress(DVR);2323Salvaged = true;2324}2325if (DVR->getValue() != &I)2326continue;2327}23282329// Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they2330// are implicitly pointing out the value as a DWARF memory location2331// description.2332bool StackValue =2333DVR->getType() != DbgVariableRecord::LocationType::Declare;2334auto DVRLocation = DVR->location_ops();2335assert(2336is_contained(DVRLocation, &I) &&2337"DbgVariableIntrinsic must use salvaged instruction as its location");2338SmallVector<Value *, 4> AdditionalValues;2339// 'I' may appear more than once in DVR's location ops, and each use of 'I'2340// must be updated in the DIExpression and potentially have additional2341// values added; thus we call salvageDebugInfoImpl for each 'I' instance in2342// DVRLocation.2343Value *Op0 = nullptr;2344DIExpression *SalvagedExpr = DVR->getExpression();2345auto LocItr = find(DVRLocation, &I);2346while (SalvagedExpr && LocItr != DVRLocation.end()) {2347SmallVector<uint64_t, 16> Ops;2348unsigned LocNo = std::distance(DVRLocation.begin(), LocItr);2349uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();2350Op0 = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);2351if (!Op0)2352break;2353SalvagedExpr =2354DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);2355LocItr = std::find(++LocItr, DVRLocation.end(), &I);2356}2357// salvageDebugInfoImpl should fail on examining the first element of2358// DbgUsers, or none of them.2359if (!Op0)2360break;23612362SalvagedExpr = SalvagedExpr->foldConstantMath();2363DVR->replaceVariableLocationOp(&I, Op0);2364bool IsValidSalvageExpr =2365SalvagedExpr->getNumElements() <= MaxExpressionSize;2366if (AdditionalValues.empty() && IsValidSalvageExpr) {2367DVR->setExpression(SalvagedExpr);2368} else if (DVR->getType() != DbgVariableRecord::LocationType::Declare &&2369IsValidSalvageExpr &&2370DVR->getNumVariableLocationOps() + AdditionalValues.size() <=2371MaxDebugArgs) {2372DVR->addVariableLocationOps(AdditionalValues, SalvagedExpr);2373} else {2374// Do not salvage using DIArgList for dbg.addr/dbg.declare, as it is2375// currently only valid for stack value expressions.2376// Also do not salvage if the resulting DIArgList would contain an2377// unreasonably large number of values.2378DVR->setKillLocation();2379}2380LLVM_DEBUG(dbgs() << "SALVAGE: " << DVR << '\n');2381Salvaged = true;2382}23832384if (Salvaged)2385return;23862387for (auto *DII : DbgUsers)2388DII->setKillLocation();23892390for (auto *DVR : DPUsers)2391DVR->setKillLocation();2392}23932394Value *getSalvageOpsForGEP(GetElementPtrInst *GEP, const DataLayout &DL,2395uint64_t CurrentLocOps,2396SmallVectorImpl<uint64_t> &Opcodes,2397SmallVectorImpl<Value *> &AdditionalValues) {2398unsigned BitWidth = DL.getIndexSizeInBits(GEP->getPointerAddressSpace());2399// Rewrite a GEP into a DIExpression.2400MapVector<Value *, APInt> VariableOffsets;2401APInt ConstantOffset(BitWidth, 0);2402if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))2403return nullptr;2404if (!VariableOffsets.empty() && !CurrentLocOps) {2405Opcodes.insert(Opcodes.begin(), {dwarf::DW_OP_LLVM_arg, 0});2406CurrentLocOps = 1;2407}2408for (const auto &Offset : VariableOffsets) {2409AdditionalValues.push_back(Offset.first);2410assert(Offset.second.isStrictlyPositive() &&2411"Expected strictly positive multiplier for offset.");2412Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps++, dwarf::DW_OP_constu,2413Offset.second.getZExtValue(), dwarf::DW_OP_mul,2414dwarf::DW_OP_plus});2415}2416DIExpression::appendOffset(Opcodes, ConstantOffset.getSExtValue());2417return GEP->getOperand(0);2418}24192420uint64_t getDwarfOpForBinOp(Instruction::BinaryOps Opcode) {2421switch (Opcode) {2422case Instruction::Add:2423return dwarf::DW_OP_plus;2424case Instruction::Sub:2425return dwarf::DW_OP_minus;2426case Instruction::Mul:2427return dwarf::DW_OP_mul;2428case Instruction::SDiv:2429return dwarf::DW_OP_div;2430case Instruction::SRem:2431return dwarf::DW_OP_mod;2432case Instruction::Or:2433return dwarf::DW_OP_or;2434case Instruction::And:2435return dwarf::DW_OP_and;2436case Instruction::Xor:2437return dwarf::DW_OP_xor;2438case Instruction::Shl:2439return dwarf::DW_OP_shl;2440case Instruction::LShr:2441return dwarf::DW_OP_shr;2442case Instruction::AShr:2443return dwarf::DW_OP_shra;2444default:2445// TODO: Salvage from each kind of binop we know about.2446return 0;2447}2448}24492450static void handleSSAValueOperands(uint64_t CurrentLocOps,2451SmallVectorImpl<uint64_t> &Opcodes,2452SmallVectorImpl<Value *> &AdditionalValues,2453Instruction *I) {2454if (!CurrentLocOps) {2455Opcodes.append({dwarf::DW_OP_LLVM_arg, 0});2456CurrentLocOps = 1;2457}2458Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps});2459AdditionalValues.push_back(I->getOperand(1));2460}24612462Value *getSalvageOpsForBinOp(BinaryOperator *BI, uint64_t CurrentLocOps,2463SmallVectorImpl<uint64_t> &Opcodes,2464SmallVectorImpl<Value *> &AdditionalValues) {2465// Handle binary operations with constant integer operands as a special case.2466auto *ConstInt = dyn_cast<ConstantInt>(BI->getOperand(1));2467// Values wider than 64 bits cannot be represented within a DIExpression.2468if (ConstInt && ConstInt->getBitWidth() > 64)2469return nullptr;24702471Instruction::BinaryOps BinOpcode = BI->getOpcode();2472// Push any Constant Int operand onto the expression stack.2473if (ConstInt) {2474uint64_t Val = ConstInt->getSExtValue();2475// Add or Sub Instructions with a constant operand can potentially be2476// simplified.2477if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {2478uint64_t Offset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);2479DIExpression::appendOffset(Opcodes, Offset);2480return BI->getOperand(0);2481}2482Opcodes.append({dwarf::DW_OP_constu, Val});2483} else {2484handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, BI);2485}24862487// Add salvaged binary operator to expression stack, if it has a valid2488// representation in a DIExpression.2489uint64_t DwarfBinOp = getDwarfOpForBinOp(BinOpcode);2490if (!DwarfBinOp)2491return nullptr;2492Opcodes.push_back(DwarfBinOp);2493return BI->getOperand(0);2494}24952496uint64_t getDwarfOpForIcmpPred(CmpInst::Predicate Pred) {2497// The signedness of the operation is implicit in the typed stack, signed and2498// unsigned instructions map to the same DWARF opcode.2499switch (Pred) {2500case CmpInst::ICMP_EQ:2501return dwarf::DW_OP_eq;2502case CmpInst::ICMP_NE:2503return dwarf::DW_OP_ne;2504case CmpInst::ICMP_UGT:2505case CmpInst::ICMP_SGT:2506return dwarf::DW_OP_gt;2507case CmpInst::ICMP_UGE:2508case CmpInst::ICMP_SGE:2509return dwarf::DW_OP_ge;2510case CmpInst::ICMP_ULT:2511case CmpInst::ICMP_SLT:2512return dwarf::DW_OP_lt;2513case CmpInst::ICMP_ULE:2514case CmpInst::ICMP_SLE:2515return dwarf::DW_OP_le;2516default:2517return 0;2518}2519}25202521Value *getSalvageOpsForIcmpOp(ICmpInst *Icmp, uint64_t CurrentLocOps,2522SmallVectorImpl<uint64_t> &Opcodes,2523SmallVectorImpl<Value *> &AdditionalValues) {2524// Handle icmp operations with constant integer operands as a special case.2525auto *ConstInt = dyn_cast<ConstantInt>(Icmp->getOperand(1));2526// Values wider than 64 bits cannot be represented within a DIExpression.2527if (ConstInt && ConstInt->getBitWidth() > 64)2528return nullptr;2529// Push any Constant Int operand onto the expression stack.2530if (ConstInt) {2531if (Icmp->isSigned())2532Opcodes.push_back(dwarf::DW_OP_consts);2533else2534Opcodes.push_back(dwarf::DW_OP_constu);2535uint64_t Val = ConstInt->getSExtValue();2536Opcodes.push_back(Val);2537} else {2538handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, Icmp);2539}25402541// Add salvaged binary operator to expression stack, if it has a valid2542// representation in a DIExpression.2543uint64_t DwarfIcmpOp = getDwarfOpForIcmpPred(Icmp->getPredicate());2544if (!DwarfIcmpOp)2545return nullptr;2546Opcodes.push_back(DwarfIcmpOp);2547return Icmp->getOperand(0);2548}25492550Value *llvm::salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps,2551SmallVectorImpl<uint64_t> &Ops,2552SmallVectorImpl<Value *> &AdditionalValues) {2553auto &M = *I.getModule();2554auto &DL = M.getDataLayout();25552556if (auto *CI = dyn_cast<CastInst>(&I)) {2557Value *FromValue = CI->getOperand(0);2558// No-op casts are irrelevant for debug info.2559if (CI->isNoopCast(DL)) {2560return FromValue;2561}25622563Type *Type = CI->getType();2564if (Type->isPointerTy())2565Type = DL.getIntPtrType(Type);2566// Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.2567if (Type->isVectorTy() ||2568!(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I) ||2569isa<IntToPtrInst>(&I) || isa<PtrToIntInst>(&I)))2570return nullptr;25712572llvm::Type *FromType = FromValue->getType();2573if (FromType->isPointerTy())2574FromType = DL.getIntPtrType(FromType);25752576unsigned FromTypeBitSize = FromType->getScalarSizeInBits();2577unsigned ToTypeBitSize = Type->getScalarSizeInBits();25782579auto ExtOps = DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,2580isa<SExtInst>(&I));2581Ops.append(ExtOps.begin(), ExtOps.end());2582return FromValue;2583}25842585if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))2586return getSalvageOpsForGEP(GEP, DL, CurrentLocOps, Ops, AdditionalValues);2587if (auto *BI = dyn_cast<BinaryOperator>(&I))2588return getSalvageOpsForBinOp(BI, CurrentLocOps, Ops, AdditionalValues);2589if (auto *IC = dyn_cast<ICmpInst>(&I))2590return getSalvageOpsForIcmpOp(IC, CurrentLocOps, Ops, AdditionalValues);25912592// *Not* to do: we should not attempt to salvage load instructions,2593// because the validity and lifetime of a dbg.value containing2594// DW_OP_deref becomes difficult to analyze. See PR40628 for examples.2595return nullptr;2596}25972598/// A replacement for a dbg.value expression.2599using DbgValReplacement = std::optional<DIExpression *>;26002601/// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,2602/// possibly moving/undefing users to prevent use-before-def. Returns true if2603/// changes are made.2604static bool rewriteDebugUsers(2605Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,2606function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr,2607function_ref<DbgValReplacement(DbgVariableRecord &DVR)> RewriteDVRExpr) {2608// Find debug users of From.2609SmallVector<DbgVariableIntrinsic *, 1> Users;2610SmallVector<DbgVariableRecord *, 1> DPUsers;2611findDbgUsers(Users, &From, &DPUsers);2612if (Users.empty() && DPUsers.empty())2613return false;26142615// Prevent use-before-def of To.2616bool Changed = false;26172618SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;2619SmallPtrSet<DbgVariableRecord *, 1> UndefOrSalvageDVR;2620if (isa<Instruction>(&To)) {2621bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;26222623for (auto *DII : Users) {2624// It's common to see a debug user between From and DomPoint. Move it2625// after DomPoint to preserve the variable update without any reordering.2626if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {2627LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n');2628DII->moveAfter(&DomPoint);2629Changed = true;26302631// Users which otherwise aren't dominated by the replacement value must2632// be salvaged or deleted.2633} else if (!DT.dominates(&DomPoint, DII)) {2634UndefOrSalvage.insert(DII);2635}2636}26372638// DbgVariableRecord implementation of the above.2639for (auto *DVR : DPUsers) {2640Instruction *MarkedInstr = DVR->getMarker()->MarkedInstr;2641Instruction *NextNonDebug = MarkedInstr;2642// The next instruction might still be a dbg.declare, skip over it.2643if (isa<DbgVariableIntrinsic>(NextNonDebug))2644NextNonDebug = NextNonDebug->getNextNonDebugInstruction();26452646if (DomPointAfterFrom && NextNonDebug == &DomPoint) {2647LLVM_DEBUG(dbgs() << "MOVE: " << *DVR << '\n');2648DVR->removeFromParent();2649// Ensure there's a marker.2650DomPoint.getParent()->insertDbgRecordAfter(DVR, &DomPoint);2651Changed = true;2652} else if (!DT.dominates(&DomPoint, MarkedInstr)) {2653UndefOrSalvageDVR.insert(DVR);2654}2655}2656}26572658// Update debug users without use-before-def risk.2659for (auto *DII : Users) {2660if (UndefOrSalvage.count(DII))2661continue;26622663DbgValReplacement DVRepl = RewriteExpr(*DII);2664if (!DVRepl)2665continue;26662667DII->replaceVariableLocationOp(&From, &To);2668DII->setExpression(*DVRepl);2669LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n');2670Changed = true;2671}2672for (auto *DVR : DPUsers) {2673if (UndefOrSalvageDVR.count(DVR))2674continue;26752676DbgValReplacement DVRepl = RewriteDVRExpr(*DVR);2677if (!DVRepl)2678continue;26792680DVR->replaceVariableLocationOp(&From, &To);2681DVR->setExpression(*DVRepl);2682LLVM_DEBUG(dbgs() << "REWRITE: " << DVR << '\n');2683Changed = true;2684}26852686if (!UndefOrSalvage.empty() || !UndefOrSalvageDVR.empty()) {2687// Try to salvage the remaining debug users.2688salvageDebugInfo(From);2689Changed = true;2690}26912692return Changed;2693}26942695/// Check if a bitcast between a value of type \p FromTy to type \p ToTy would2696/// losslessly preserve the bits and semantics of the value. This predicate is2697/// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.2698///2699/// Note that Type::canLosslesslyBitCastTo is not suitable here because it2700/// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,2701/// and also does not allow lossless pointer <-> integer conversions.2702static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,2703Type *ToTy) {2704// Trivially compatible types.2705if (FromTy == ToTy)2706return true;27072708// Handle compatible pointer <-> integer conversions.2709if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {2710bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);2711bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&2712!DL.isNonIntegralPointerType(ToTy);2713return SameSize && LosslessConversion;2714}27152716// TODO: This is not exhaustive.2717return false;2718}27192720bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,2721Instruction &DomPoint, DominatorTree &DT) {2722// Exit early if From has no debug users.2723if (!From.isUsedByMetadata())2724return false;27252726assert(&From != &To && "Can't replace something with itself");27272728Type *FromTy = From.getType();2729Type *ToTy = To.getType();27302731auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {2732return DII.getExpression();2733};2734auto IdentityDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {2735return DVR.getExpression();2736};27372738// Handle no-op conversions.2739Module &M = *From.getModule();2740const DataLayout &DL = M.getDataLayout();2741if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))2742return rewriteDebugUsers(From, To, DomPoint, DT, Identity, IdentityDVR);27432744// Handle integer-to-integer widening and narrowing.2745// FIXME: Use DW_OP_convert when it's available everywhere.2746if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {2747uint64_t FromBits = FromTy->getPrimitiveSizeInBits();2748uint64_t ToBits = ToTy->getPrimitiveSizeInBits();2749assert(FromBits != ToBits && "Unexpected no-op conversion");27502751// When the width of the result grows, assume that a debugger will only2752// access the low `FromBits` bits when inspecting the source variable.2753if (FromBits < ToBits)2754return rewriteDebugUsers(From, To, DomPoint, DT, Identity, IdentityDVR);27552756// The width of the result has shrunk. Use sign/zero extension to describe2757// the source variable's high bits.2758auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {2759DILocalVariable *Var = DII.getVariable();27602761// Without knowing signedness, sign/zero extension isn't possible.2762auto Signedness = Var->getSignedness();2763if (!Signedness)2764return std::nullopt;27652766bool Signed = *Signedness == DIBasicType::Signedness::Signed;2767return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,2768Signed);2769};2770// RemoveDIs: duplicate implementation working on DbgVariableRecords rather2771// than on dbg.value intrinsics.2772auto SignOrZeroExtDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {2773DILocalVariable *Var = DVR.getVariable();27742775// Without knowing signedness, sign/zero extension isn't possible.2776auto Signedness = Var->getSignedness();2777if (!Signedness)2778return std::nullopt;27792780bool Signed = *Signedness == DIBasicType::Signedness::Signed;2781return DIExpression::appendExt(DVR.getExpression(), ToBits, FromBits,2782Signed);2783};2784return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt,2785SignOrZeroExtDVR);2786}27872788// TODO: Floating-point conversions, vectors.2789return false;2790}27912792bool llvm::handleUnreachableTerminator(2793Instruction *I, SmallVectorImpl<Value *> &PoisonedValues) {2794bool Changed = false;2795// RemoveDIs: erase debug-info on this instruction manually.2796I->dropDbgRecords();2797for (Use &U : I->operands()) {2798Value *Op = U.get();2799if (isa<Instruction>(Op) && !Op->getType()->isTokenTy()) {2800U.set(PoisonValue::get(Op->getType()));2801PoisonedValues.push_back(Op);2802Changed = true;2803}2804}28052806return Changed;2807}28082809std::pair<unsigned, unsigned>2810llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {2811unsigned NumDeadInst = 0;2812unsigned NumDeadDbgInst = 0;2813// Delete the instructions backwards, as it has a reduced likelihood of2814// having to update as many def-use and use-def chains.2815Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.2816SmallVector<Value *> Uses;2817handleUnreachableTerminator(EndInst, Uses);28182819while (EndInst != &BB->front()) {2820// Delete the next to last instruction.2821Instruction *Inst = &*--EndInst->getIterator();2822if (!Inst->use_empty() && !Inst->getType()->isTokenTy())2823Inst->replaceAllUsesWith(PoisonValue::get(Inst->getType()));2824if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {2825// EHPads can't have DbgVariableRecords attached to them, but it might be2826// possible for things with token type.2827Inst->dropDbgRecords();2828EndInst = Inst;2829continue;2830}2831if (isa<DbgInfoIntrinsic>(Inst))2832++NumDeadDbgInst;2833else2834++NumDeadInst;2835// RemoveDIs: erasing debug-info must be done manually.2836Inst->dropDbgRecords();2837Inst->eraseFromParent();2838}2839return {NumDeadInst, NumDeadDbgInst};2840}28412842unsigned llvm::changeToUnreachable(Instruction *I, bool PreserveLCSSA,2843DomTreeUpdater *DTU,2844MemorySSAUpdater *MSSAU) {2845BasicBlock *BB = I->getParent();28462847if (MSSAU)2848MSSAU->changeToUnreachable(I);28492850SmallSet<BasicBlock *, 8> UniqueSuccessors;28512852// Loop over all of the successors, removing BB's entry from any PHI2853// nodes.2854for (BasicBlock *Successor : successors(BB)) {2855Successor->removePredecessor(BB, PreserveLCSSA);2856if (DTU)2857UniqueSuccessors.insert(Successor);2858}2859auto *UI = new UnreachableInst(I->getContext(), I->getIterator());2860UI->setDebugLoc(I->getDebugLoc());28612862// All instructions after this are dead.2863unsigned NumInstrsRemoved = 0;2864BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();2865while (BBI != BBE) {2866if (!BBI->use_empty())2867BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));2868BBI++->eraseFromParent();2869++NumInstrsRemoved;2870}2871if (DTU) {2872SmallVector<DominatorTree::UpdateType, 8> Updates;2873Updates.reserve(UniqueSuccessors.size());2874for (BasicBlock *UniqueSuccessor : UniqueSuccessors)2875Updates.push_back({DominatorTree::Delete, BB, UniqueSuccessor});2876DTU->applyUpdates(Updates);2877}2878BB->flushTerminatorDbgRecords();2879return NumInstrsRemoved;2880}28812882CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {2883SmallVector<Value *, 8> Args(II->args());2884SmallVector<OperandBundleDef, 1> OpBundles;2885II->getOperandBundlesAsDefs(OpBundles);2886CallInst *NewCall = CallInst::Create(II->getFunctionType(),2887II->getCalledOperand(), Args, OpBundles);2888NewCall->setCallingConv(II->getCallingConv());2889NewCall->setAttributes(II->getAttributes());2890NewCall->setDebugLoc(II->getDebugLoc());2891NewCall->copyMetadata(*II);28922893// If the invoke had profile metadata, try converting them for CallInst.2894uint64_t TotalWeight;2895if (NewCall->extractProfTotalWeight(TotalWeight)) {2896// Set the total weight if it fits into i32, otherwise reset.2897MDBuilder MDB(NewCall->getContext());2898auto NewWeights = uint32_t(TotalWeight) != TotalWeight2899? nullptr2900: MDB.createBranchWeights({uint32_t(TotalWeight)});2901NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);2902}29032904return NewCall;2905}29062907// changeToCall - Convert the specified invoke into a normal call.2908CallInst *llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {2909CallInst *NewCall = createCallMatchingInvoke(II);2910NewCall->takeName(II);2911NewCall->insertBefore(II);2912II->replaceAllUsesWith(NewCall);29132914// Follow the call by a branch to the normal destination.2915BasicBlock *NormalDestBB = II->getNormalDest();2916BranchInst::Create(NormalDestBB, II->getIterator());29172918// Update PHI nodes in the unwind destination2919BasicBlock *BB = II->getParent();2920BasicBlock *UnwindDestBB = II->getUnwindDest();2921UnwindDestBB->removePredecessor(BB);2922II->eraseFromParent();2923if (DTU)2924DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});2925return NewCall;2926}29272928BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,2929BasicBlock *UnwindEdge,2930DomTreeUpdater *DTU) {2931BasicBlock *BB = CI->getParent();29322933// Convert this function call into an invoke instruction. First, split the2934// basic block.2935BasicBlock *Split = SplitBlock(BB, CI, DTU, /*LI=*/nullptr, /*MSSAU*/ nullptr,2936CI->getName() + ".noexc");29372938// Delete the unconditional branch inserted by SplitBlock2939BB->back().eraseFromParent();29402941// Create the new invoke instruction.2942SmallVector<Value *, 8> InvokeArgs(CI->args());2943SmallVector<OperandBundleDef, 1> OpBundles;29442945CI->getOperandBundlesAsDefs(OpBundles);29462947// Note: we're round tripping operand bundles through memory here, and that2948// can potentially be avoided with a cleverer API design that we do not have2949// as of this time.29502951InvokeInst *II =2952InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,2953UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);2954II->setDebugLoc(CI->getDebugLoc());2955II->setCallingConv(CI->getCallingConv());2956II->setAttributes(CI->getAttributes());2957II->setMetadata(LLVMContext::MD_prof, CI->getMetadata(LLVMContext::MD_prof));29582959if (DTU)2960DTU->applyUpdates({{DominatorTree::Insert, BB, UnwindEdge}});29612962// Make sure that anything using the call now uses the invoke! This also2963// updates the CallGraph if present, because it uses a WeakTrackingVH.2964CI->replaceAllUsesWith(II);29652966// Delete the original call2967Split->front().eraseFromParent();2968return Split;2969}29702971static bool markAliveBlocks(Function &F,2972SmallPtrSetImpl<BasicBlock *> &Reachable,2973DomTreeUpdater *DTU = nullptr) {2974SmallVector<BasicBlock*, 128> Worklist;2975BasicBlock *BB = &F.front();2976Worklist.push_back(BB);2977Reachable.insert(BB);2978bool Changed = false;2979do {2980BB = Worklist.pop_back_val();29812982// Do a quick scan of the basic block, turning any obviously unreachable2983// instructions into LLVM unreachable insts. The instruction combining pass2984// canonicalizes unreachable insts into stores to null or undef.2985for (Instruction &I : *BB) {2986if (auto *CI = dyn_cast<CallInst>(&I)) {2987Value *Callee = CI->getCalledOperand();2988// Handle intrinsic calls.2989if (Function *F = dyn_cast<Function>(Callee)) {2990auto IntrinsicID = F->getIntrinsicID();2991// Assumptions that are known to be false are equivalent to2992// unreachable. Also, if the condition is undefined, then we make the2993// choice most beneficial to the optimizer, and choose that to also be2994// unreachable.2995if (IntrinsicID == Intrinsic::assume) {2996if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {2997// Don't insert a call to llvm.trap right before the unreachable.2998changeToUnreachable(CI, false, DTU);2999Changed = true;3000break;3001}3002} else if (IntrinsicID == Intrinsic::experimental_guard) {3003// A call to the guard intrinsic bails out of the current3004// compilation unit if the predicate passed to it is false. If the3005// predicate is a constant false, then we know the guard will bail3006// out of the current compile unconditionally, so all code following3007// it is dead.3008//3009// Note: unlike in llvm.assume, it is not "obviously profitable" for3010// guards to treat `undef` as `false` since a guard on `undef` can3011// still be useful for widening.3012if (match(CI->getArgOperand(0), m_Zero()))3013if (!isa<UnreachableInst>(CI->getNextNode())) {3014changeToUnreachable(CI->getNextNode(), false, DTU);3015Changed = true;3016break;3017}3018}3019} else if ((isa<ConstantPointerNull>(Callee) &&3020!NullPointerIsDefined(CI->getFunction(),3021cast<PointerType>(Callee->getType())3022->getAddressSpace())) ||3023isa<UndefValue>(Callee)) {3024changeToUnreachable(CI, false, DTU);3025Changed = true;3026break;3027}3028if (CI->doesNotReturn() && !CI->isMustTailCall()) {3029// If we found a call to a no-return function, insert an unreachable3030// instruction after it. Make sure there isn't *already* one there3031// though.3032if (!isa<UnreachableInst>(CI->getNextNonDebugInstruction())) {3033// Don't insert a call to llvm.trap right before the unreachable.3034changeToUnreachable(CI->getNextNonDebugInstruction(), false, DTU);3035Changed = true;3036}3037break;3038}3039} else if (auto *SI = dyn_cast<StoreInst>(&I)) {3040// Store to undef and store to null are undefined and used to signal3041// that they should be changed to unreachable by passes that can't3042// modify the CFG.30433044// Don't touch volatile stores.3045if (SI->isVolatile()) continue;30463047Value *Ptr = SI->getOperand(1);30483049if (isa<UndefValue>(Ptr) ||3050(isa<ConstantPointerNull>(Ptr) &&3051!NullPointerIsDefined(SI->getFunction(),3052SI->getPointerAddressSpace()))) {3053changeToUnreachable(SI, false, DTU);3054Changed = true;3055break;3056}3057}3058}30593060Instruction *Terminator = BB->getTerminator();3061if (auto *II = dyn_cast<InvokeInst>(Terminator)) {3062// Turn invokes that call 'nounwind' functions into ordinary calls.3063Value *Callee = II->getCalledOperand();3064if ((isa<ConstantPointerNull>(Callee) &&3065!NullPointerIsDefined(BB->getParent())) ||3066isa<UndefValue>(Callee)) {3067changeToUnreachable(II, false, DTU);3068Changed = true;3069} else {3070if (II->doesNotReturn() &&3071!isa<UnreachableInst>(II->getNormalDest()->front())) {3072// If we found an invoke of a no-return function,3073// create a new empty basic block with an `unreachable` terminator,3074// and set it as the normal destination for the invoke,3075// unless that is already the case.3076// Note that the original normal destination could have other uses.3077BasicBlock *OrigNormalDest = II->getNormalDest();3078OrigNormalDest->removePredecessor(II->getParent());3079LLVMContext &Ctx = II->getContext();3080BasicBlock *UnreachableNormalDest = BasicBlock::Create(3081Ctx, OrigNormalDest->getName() + ".unreachable",3082II->getFunction(), OrigNormalDest);3083new UnreachableInst(Ctx, UnreachableNormalDest);3084II->setNormalDest(UnreachableNormalDest);3085if (DTU)3086DTU->applyUpdates(3087{{DominatorTree::Delete, BB, OrigNormalDest},3088{DominatorTree::Insert, BB, UnreachableNormalDest}});3089Changed = true;3090}3091if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {3092if (II->use_empty() && !II->mayHaveSideEffects()) {3093// jump to the normal destination branch.3094BasicBlock *NormalDestBB = II->getNormalDest();3095BasicBlock *UnwindDestBB = II->getUnwindDest();3096BranchInst::Create(NormalDestBB, II->getIterator());3097UnwindDestBB->removePredecessor(II->getParent());3098II->eraseFromParent();3099if (DTU)3100DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});3101} else3102changeToCall(II, DTU);3103Changed = true;3104}3105}3106} else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {3107// Remove catchpads which cannot be reached.3108struct CatchPadDenseMapInfo {3109static CatchPadInst *getEmptyKey() {3110return DenseMapInfo<CatchPadInst *>::getEmptyKey();3111}31123113static CatchPadInst *getTombstoneKey() {3114return DenseMapInfo<CatchPadInst *>::getTombstoneKey();3115}31163117static unsigned getHashValue(CatchPadInst *CatchPad) {3118return static_cast<unsigned>(hash_combine_range(3119CatchPad->value_op_begin(), CatchPad->value_op_end()));3120}31213122static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {3123if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||3124RHS == getEmptyKey() || RHS == getTombstoneKey())3125return LHS == RHS;3126return LHS->isIdenticalTo(RHS);3127}3128};31293130SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;3131// Set of unique CatchPads.3132SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,3133CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>3134HandlerSet;3135detail::DenseSetEmpty Empty;3136for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),3137E = CatchSwitch->handler_end();3138I != E; ++I) {3139BasicBlock *HandlerBB = *I;3140if (DTU)3141++NumPerSuccessorCases[HandlerBB];3142auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());3143if (!HandlerSet.insert({CatchPad, Empty}).second) {3144if (DTU)3145--NumPerSuccessorCases[HandlerBB];3146CatchSwitch->removeHandler(I);3147--I;3148--E;3149Changed = true;3150}3151}3152if (DTU) {3153std::vector<DominatorTree::UpdateType> Updates;3154for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)3155if (I.second == 0)3156Updates.push_back({DominatorTree::Delete, BB, I.first});3157DTU->applyUpdates(Updates);3158}3159}31603161Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);3162for (BasicBlock *Successor : successors(BB))3163if (Reachable.insert(Successor).second)3164Worklist.push_back(Successor);3165} while (!Worklist.empty());3166return Changed;3167}31683169Instruction *llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {3170Instruction *TI = BB->getTerminator();31713172if (auto *II = dyn_cast<InvokeInst>(TI))3173return changeToCall(II, DTU);31743175Instruction *NewTI;3176BasicBlock *UnwindDest;31773178if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {3179NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI->getIterator());3180UnwindDest = CRI->getUnwindDest();3181} else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {3182auto *NewCatchSwitch = CatchSwitchInst::Create(3183CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),3184CatchSwitch->getName(), CatchSwitch->getIterator());3185for (BasicBlock *PadBB : CatchSwitch->handlers())3186NewCatchSwitch->addHandler(PadBB);31873188NewTI = NewCatchSwitch;3189UnwindDest = CatchSwitch->getUnwindDest();3190} else {3191llvm_unreachable("Could not find unwind successor");3192}31933194NewTI->takeName(TI);3195NewTI->setDebugLoc(TI->getDebugLoc());3196UnwindDest->removePredecessor(BB);3197TI->replaceAllUsesWith(NewTI);3198TI->eraseFromParent();3199if (DTU)3200DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDest}});3201return NewTI;3202}32033204/// removeUnreachableBlocks - Remove blocks that are not reachable, even3205/// if they are in a dead cycle. Return true if a change was made, false3206/// otherwise.3207bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,3208MemorySSAUpdater *MSSAU) {3209SmallPtrSet<BasicBlock *, 16> Reachable;3210bool Changed = markAliveBlocks(F, Reachable, DTU);32113212// If there are unreachable blocks in the CFG...3213if (Reachable.size() == F.size())3214return Changed;32153216assert(Reachable.size() < F.size());32173218// Are there any blocks left to actually delete?3219SmallSetVector<BasicBlock *, 8> BlocksToRemove;3220for (BasicBlock &BB : F) {3221// Skip reachable basic blocks3222if (Reachable.count(&BB))3223continue;3224// Skip already-deleted blocks3225if (DTU && DTU->isBBPendingDeletion(&BB))3226continue;3227BlocksToRemove.insert(&BB);3228}32293230if (BlocksToRemove.empty())3231return Changed;32323233Changed = true;3234NumRemoved += BlocksToRemove.size();32353236if (MSSAU)3237MSSAU->removeBlocks(BlocksToRemove);32383239DeleteDeadBlocks(BlocksToRemove.takeVector(), DTU);32403241return Changed;3242}32433244void llvm::combineMetadata(Instruction *K, const Instruction *J,3245ArrayRef<unsigned> KnownIDs, bool DoesKMove) {3246SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;3247K->dropUnknownNonDebugMetadata(KnownIDs);3248K->getAllMetadataOtherThanDebugLoc(Metadata);3249for (const auto &MD : Metadata) {3250unsigned Kind = MD.first;3251MDNode *JMD = J->getMetadata(Kind);3252MDNode *KMD = MD.second;32533254switch (Kind) {3255default:3256K->setMetadata(Kind, nullptr); // Remove unknown metadata3257break;3258case LLVMContext::MD_dbg:3259llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");3260case LLVMContext::MD_DIAssignID:3261K->mergeDIAssignID(J);3262break;3263case LLVMContext::MD_tbaa:3264K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));3265break;3266case LLVMContext::MD_alias_scope:3267K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));3268break;3269case LLVMContext::MD_noalias:3270case LLVMContext::MD_mem_parallel_loop_access:3271K->setMetadata(Kind, MDNode::intersect(JMD, KMD));3272break;3273case LLVMContext::MD_access_group:3274K->setMetadata(LLVMContext::MD_access_group,3275intersectAccessGroups(K, J));3276break;3277case LLVMContext::MD_range:3278if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))3279K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));3280break;3281case LLVMContext::MD_fpmath:3282K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));3283break;3284case LLVMContext::MD_invariant_load:3285// If K moves, only set the !invariant.load if it is present in both3286// instructions.3287if (DoesKMove)3288K->setMetadata(Kind, JMD);3289break;3290case LLVMContext::MD_nonnull:3291if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))3292K->setMetadata(Kind, JMD);3293break;3294case LLVMContext::MD_invariant_group:3295// Preserve !invariant.group in K.3296break;3297case LLVMContext::MD_mmra:3298// Combine MMRAs3299break;3300case LLVMContext::MD_align:3301if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))3302K->setMetadata(3303Kind, MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));3304break;3305case LLVMContext::MD_dereferenceable:3306case LLVMContext::MD_dereferenceable_or_null:3307if (DoesKMove)3308K->setMetadata(Kind,3309MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));3310break;3311case LLVMContext::MD_preserve_access_index:3312// Preserve !preserve.access.index in K.3313break;3314case LLVMContext::MD_noundef:3315// If K does move, keep noundef if it is present in both instructions.3316if (DoesKMove)3317K->setMetadata(Kind, JMD);3318break;3319case LLVMContext::MD_nontemporal:3320// Preserve !nontemporal if it is present on both instructions.3321K->setMetadata(Kind, JMD);3322break;3323case LLVMContext::MD_prof:3324if (DoesKMove)3325K->setMetadata(Kind, MDNode::getMergedProfMetadata(KMD, JMD, K, J));3326break;3327}3328}3329// Set !invariant.group from J if J has it. If both instructions have it3330// then we will just pick it from J - even when they are different.3331// Also make sure that K is load or store - f.e. combining bitcast with load3332// could produce bitcast with invariant.group metadata, which is invalid.3333// FIXME: we should try to preserve both invariant.group md if they are3334// different, but right now instruction can only have one invariant.group.3335if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))3336if (isa<LoadInst>(K) || isa<StoreInst>(K))3337K->setMetadata(LLVMContext::MD_invariant_group, JMD);33383339// Merge MMRAs.3340// This is handled separately because we also want to handle cases where K3341// doesn't have tags but J does.3342auto JMMRA = J->getMetadata(LLVMContext::MD_mmra);3343auto KMMRA = K->getMetadata(LLVMContext::MD_mmra);3344if (JMMRA || KMMRA) {3345K->setMetadata(LLVMContext::MD_mmra,3346MMRAMetadata::combine(K->getContext(), JMMRA, KMMRA));3347}3348}33493350void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,3351bool KDominatesJ) {3352unsigned KnownIDs[] = {LLVMContext::MD_tbaa,3353LLVMContext::MD_alias_scope,3354LLVMContext::MD_noalias,3355LLVMContext::MD_range,3356LLVMContext::MD_fpmath,3357LLVMContext::MD_invariant_load,3358LLVMContext::MD_nonnull,3359LLVMContext::MD_invariant_group,3360LLVMContext::MD_align,3361LLVMContext::MD_dereferenceable,3362LLVMContext::MD_dereferenceable_or_null,3363LLVMContext::MD_access_group,3364LLVMContext::MD_preserve_access_index,3365LLVMContext::MD_prof,3366LLVMContext::MD_nontemporal,3367LLVMContext::MD_noundef,3368LLVMContext::MD_mmra};3369combineMetadata(K, J, KnownIDs, KDominatesJ);3370}33713372void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {3373SmallVector<std::pair<unsigned, MDNode *>, 8> MD;3374Source.getAllMetadata(MD);3375MDBuilder MDB(Dest.getContext());3376Type *NewType = Dest.getType();3377const DataLayout &DL = Source.getDataLayout();3378for (const auto &MDPair : MD) {3379unsigned ID = MDPair.first;3380MDNode *N = MDPair.second;3381// Note, essentially every kind of metadata should be preserved here! This3382// routine is supposed to clone a load instruction changing *only its type*.3383// The only metadata it makes sense to drop is metadata which is invalidated3384// when the pointer type changes. This should essentially never be the case3385// in LLVM, but we explicitly switch over only known metadata to be3386// conservatively correct. If you are adding metadata to LLVM which pertains3387// to loads, you almost certainly want to add it here.3388switch (ID) {3389case LLVMContext::MD_dbg:3390case LLVMContext::MD_tbaa:3391case LLVMContext::MD_prof:3392case LLVMContext::MD_fpmath:3393case LLVMContext::MD_tbaa_struct:3394case LLVMContext::MD_invariant_load:3395case LLVMContext::MD_alias_scope:3396case LLVMContext::MD_noalias:3397case LLVMContext::MD_nontemporal:3398case LLVMContext::MD_mem_parallel_loop_access:3399case LLVMContext::MD_access_group:3400case LLVMContext::MD_noundef:3401// All of these directly apply.3402Dest.setMetadata(ID, N);3403break;34043405case LLVMContext::MD_nonnull:3406copyNonnullMetadata(Source, N, Dest);3407break;34083409case LLVMContext::MD_align:3410case LLVMContext::MD_dereferenceable:3411case LLVMContext::MD_dereferenceable_or_null:3412// These only directly apply if the new type is also a pointer.3413if (NewType->isPointerTy())3414Dest.setMetadata(ID, N);3415break;34163417case LLVMContext::MD_range:3418copyRangeMetadata(DL, Source, N, Dest);3419break;3420}3421}3422}34233424void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {3425auto *ReplInst = dyn_cast<Instruction>(Repl);3426if (!ReplInst)3427return;34283429// Patch the replacement so that it is not more restrictive than the value3430// being replaced.3431WithOverflowInst *UnusedWO;3432// When replacing the result of a llvm.*.with.overflow intrinsic with a3433// overflowing binary operator, nuw/nsw flags may no longer hold.3434if (isa<OverflowingBinaryOperator>(ReplInst) &&3435match(I, m_ExtractValue<0>(m_WithOverflowInst(UnusedWO))))3436ReplInst->dropPoisonGeneratingFlags();3437// Note that if 'I' is a load being replaced by some operation,3438// for example, by an arithmetic operation, then andIRFlags()3439// would just erase all math flags from the original arithmetic3440// operation, which is clearly not wanted and not needed.3441else if (!isa<LoadInst>(I))3442ReplInst->andIRFlags(I);34433444// FIXME: If both the original and replacement value are part of the3445// same control-flow region (meaning that the execution of one3446// guarantees the execution of the other), then we can combine the3447// noalias scopes here and do better than the general conservative3448// answer used in combineMetadata().34493450// In general, GVN unifies expressions over different control-flow3451// regions, and so we need a conservative combination of the noalias3452// scopes.3453combineMetadataForCSE(ReplInst, I, false);3454}34553456template <typename RootType, typename ShouldReplaceFn>3457static unsigned replaceDominatedUsesWith(Value *From, Value *To,3458const RootType &Root,3459const ShouldReplaceFn &ShouldReplace) {3460assert(From->getType() == To->getType());34613462unsigned Count = 0;3463for (Use &U : llvm::make_early_inc_range(From->uses())) {3464if (!ShouldReplace(Root, U))3465continue;3466LLVM_DEBUG(dbgs() << "Replace dominated use of '";3467From->printAsOperand(dbgs());3468dbgs() << "' with " << *To << " in " << *U.getUser() << "\n");3469U.set(To);3470++Count;3471}3472return Count;3473}34743475unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {3476assert(From->getType() == To->getType());3477auto *BB = From->getParent();3478unsigned Count = 0;34793480for (Use &U : llvm::make_early_inc_range(From->uses())) {3481auto *I = cast<Instruction>(U.getUser());3482if (I->getParent() == BB)3483continue;3484U.set(To);3485++Count;3486}3487return Count;3488}34893490unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,3491DominatorTree &DT,3492const BasicBlockEdge &Root) {3493auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {3494return DT.dominates(Root, U);3495};3496return ::replaceDominatedUsesWith(From, To, Root, Dominates);3497}34983499unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,3500DominatorTree &DT,3501const BasicBlock *BB) {3502auto Dominates = [&DT](const BasicBlock *BB, const Use &U) {3503return DT.dominates(BB, U);3504};3505return ::replaceDominatedUsesWith(From, To, BB, Dominates);3506}35073508unsigned llvm::replaceDominatedUsesWithIf(3509Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Root,3510function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {3511auto DominatesAndShouldReplace =3512[&DT, &ShouldReplace, To](const BasicBlockEdge &Root, const Use &U) {3513return DT.dominates(Root, U) && ShouldReplace(U, To);3514};3515return ::replaceDominatedUsesWith(From, To, Root, DominatesAndShouldReplace);3516}35173518unsigned llvm::replaceDominatedUsesWithIf(3519Value *From, Value *To, DominatorTree &DT, const BasicBlock *BB,3520function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {3521auto DominatesAndShouldReplace = [&DT, &ShouldReplace,3522To](const BasicBlock *BB, const Use &U) {3523return DT.dominates(BB, U) && ShouldReplace(U, To);3524};3525return ::replaceDominatedUsesWith(From, To, BB, DominatesAndShouldReplace);3526}35273528bool llvm::callsGCLeafFunction(const CallBase *Call,3529const TargetLibraryInfo &TLI) {3530// Check if the function is specifically marked as a gc leaf function.3531if (Call->hasFnAttr("gc-leaf-function"))3532return true;3533if (const Function *F = Call->getCalledFunction()) {3534if (F->hasFnAttribute("gc-leaf-function"))3535return true;35363537if (auto IID = F->getIntrinsicID()) {3538// Most LLVM intrinsics do not take safepoints.3539return IID != Intrinsic::experimental_gc_statepoint &&3540IID != Intrinsic::experimental_deoptimize &&3541IID != Intrinsic::memcpy_element_unordered_atomic &&3542IID != Intrinsic::memmove_element_unordered_atomic;3543}3544}35453546// Lib calls can be materialized by some passes, and won't be3547// marked as 'gc-leaf-function.' All available Libcalls are3548// GC-leaf.3549LibFunc LF;3550if (TLI.getLibFunc(*Call, LF)) {3551return TLI.has(LF);3552}35533554return false;3555}35563557void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,3558LoadInst &NewLI) {3559auto *NewTy = NewLI.getType();35603561// This only directly applies if the new type is also a pointer.3562if (NewTy->isPointerTy()) {3563NewLI.setMetadata(LLVMContext::MD_nonnull, N);3564return;3565}35663567// The only other translation we can do is to integral loads with !range3568// metadata.3569if (!NewTy->isIntegerTy())3570return;35713572MDBuilder MDB(NewLI.getContext());3573const Value *Ptr = OldLI.getPointerOperand();3574auto *ITy = cast<IntegerType>(NewTy);3575auto *NullInt = ConstantExpr::getPtrToInt(3576ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);3577auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));3578NewLI.setMetadata(LLVMContext::MD_range,3579MDB.createRange(NonNullInt, NullInt));3580}35813582void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,3583MDNode *N, LoadInst &NewLI) {3584auto *NewTy = NewLI.getType();3585// Simply copy the metadata if the type did not change.3586if (NewTy == OldLI.getType()) {3587NewLI.setMetadata(LLVMContext::MD_range, N);3588return;3589}35903591// Give up unless it is converted to a pointer where there is a single very3592// valuable mapping we can do reliably.3593// FIXME: It would be nice to propagate this in more ways, but the type3594// conversions make it hard.3595if (!NewTy->isPointerTy())3596return;35973598unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);3599if (BitWidth == OldLI.getType()->getScalarSizeInBits() &&3600!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {3601MDNode *NN = MDNode::get(OldLI.getContext(), std::nullopt);3602NewLI.setMetadata(LLVMContext::MD_nonnull, NN);3603}3604}36053606void llvm::dropDebugUsers(Instruction &I) {3607SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;3608SmallVector<DbgVariableRecord *, 1> DPUsers;3609findDbgUsers(DbgUsers, &I, &DPUsers);3610for (auto *DII : DbgUsers)3611DII->eraseFromParent();3612for (auto *DVR : DPUsers)3613DVR->eraseFromParent();3614}36153616void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,3617BasicBlock *BB) {3618// Since we are moving the instructions out of its basic block, we do not3619// retain their original debug locations (DILocations) and debug intrinsic3620// instructions.3621//3622// Doing so would degrade the debugging experience and adversely affect the3623// accuracy of profiling information.3624//3625// Currently, when hoisting the instructions, we take the following actions:3626// - Remove their debug intrinsic instructions.3627// - Set their debug locations to the values from the insertion point.3628//3629// As per PR39141 (comment #8), the more fundamental reason why the dbg.values3630// need to be deleted, is because there will not be any instructions with a3631// DILocation in either branch left after performing the transformation. We3632// can only insert a dbg.value after the two branches are joined again.3633//3634// See PR38762, PR39243 for more details.3635//3636// TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to3637// encode predicated DIExpressions that yield different results on different3638// code paths.36393640for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {3641Instruction *I = &*II;3642I->dropUBImplyingAttrsAndMetadata();3643if (I->isUsedByMetadata())3644dropDebugUsers(*I);3645// RemoveDIs: drop debug-info too as the following code does.3646I->dropDbgRecords();3647if (I->isDebugOrPseudoInst()) {3648// Remove DbgInfo and pseudo probe Intrinsics.3649II = I->eraseFromParent();3650continue;3651}3652I->setDebugLoc(InsertPt->getDebugLoc());3653++II;3654}3655DomBlock->splice(InsertPt->getIterator(), BB, BB->begin(),3656BB->getTerminator()->getIterator());3657}36583659DIExpression *llvm::getExpressionForConstant(DIBuilder &DIB, const Constant &C,3660Type &Ty) {3661// Create integer constant expression.3662auto createIntegerExpression = [&DIB](const Constant &CV) -> DIExpression * {3663const APInt &API = cast<ConstantInt>(&CV)->getValue();3664std::optional<int64_t> InitIntOpt = API.trySExtValue();3665return InitIntOpt ? DIB.createConstantValueExpression(3666static_cast<uint64_t>(*InitIntOpt))3667: nullptr;3668};36693670if (isa<ConstantInt>(C))3671return createIntegerExpression(C);36723673auto *FP = dyn_cast<ConstantFP>(&C);3674if (FP && Ty.isFloatingPointTy() && Ty.getScalarSizeInBits() <= 64) {3675const APFloat &APF = FP->getValueAPF();3676APInt const &API = APF.bitcastToAPInt();3677if (auto Temp = API.getZExtValue())3678return DIB.createConstantValueExpression(static_cast<uint64_t>(Temp));3679return DIB.createConstantValueExpression(*API.getRawData());3680}36813682if (!Ty.isPointerTy())3683return nullptr;36843685if (isa<ConstantPointerNull>(C))3686return DIB.createConstantValueExpression(0);36873688if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(&C))3689if (CE->getOpcode() == Instruction::IntToPtr) {3690const Value *V = CE->getOperand(0);3691if (auto CI = dyn_cast_or_null<ConstantInt>(V))3692return createIntegerExpression(*CI);3693}3694return nullptr;3695}36963697void llvm::remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst) {3698auto RemapDebugOperands = [&Mapping](auto *DV, auto Set) {3699for (auto *Op : Set) {3700auto I = Mapping.find(Op);3701if (I != Mapping.end())3702DV->replaceVariableLocationOp(Op, I->second, /*AllowEmpty=*/true);3703}3704};3705auto RemapAssignAddress = [&Mapping](auto *DA) {3706auto I = Mapping.find(DA->getAddress());3707if (I != Mapping.end())3708DA->setAddress(I->second);3709};3710if (auto DVI = dyn_cast<DbgVariableIntrinsic>(Inst))3711RemapDebugOperands(DVI, DVI->location_ops());3712if (auto DAI = dyn_cast<DbgAssignIntrinsic>(Inst))3713RemapAssignAddress(DAI);3714for (DbgVariableRecord &DVR : filterDbgVars(Inst->getDbgRecordRange())) {3715RemapDebugOperands(&DVR, DVR.location_ops());3716if (DVR.isDbgAssign())3717RemapAssignAddress(&DVR);3718}3719}37203721namespace {37223723/// A potential constituent of a bitreverse or bswap expression. See3724/// collectBitParts for a fuller explanation.3725struct BitPart {3726BitPart(Value *P, unsigned BW) : Provider(P) {3727Provenance.resize(BW);3728}37293730/// The Value that this is a bitreverse/bswap of.3731Value *Provider;37323733/// The "provenance" of each bit. Provenance[A] = B means that bit A3734/// in Provider becomes bit B in the result of this expression.3735SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.37363737enum { Unset = -1 };3738};37393740} // end anonymous namespace37413742/// Analyze the specified subexpression and see if it is capable of providing3743/// pieces of a bswap or bitreverse. The subexpression provides a potential3744/// piece of a bswap or bitreverse if it can be proved that each non-zero bit in3745/// the output of the expression came from a corresponding bit in some other3746/// value. This function is recursive, and the end result is a mapping of3747/// bitnumber to bitnumber. It is the caller's responsibility to validate that3748/// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.3749///3750/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know3751/// that the expression deposits the low byte of %X into the high byte of the3752/// result and that all other bits are zero. This expression is accepted and a3753/// BitPart is returned with Provider set to %X and Provenance[24-31] set to3754/// [0-7].3755///3756/// For vector types, all analysis is performed at the per-element level. No3757/// cross-element analysis is supported (shuffle/insertion/reduction), and all3758/// constant masks must be splatted across all elements.3759///3760/// To avoid revisiting values, the BitPart results are memoized into the3761/// provided map. To avoid unnecessary copying of BitParts, BitParts are3762/// constructed in-place in the \c BPS map. Because of this \c BPS needs to3763/// store BitParts objects, not pointers. As we need the concept of a nullptr3764/// BitParts (Value has been analyzed and the analysis failed), we an Optional3765/// type instead to provide the same functionality.3766///3767/// Because we pass around references into \c BPS, we must use a container that3768/// does not invalidate internal references (std::map instead of DenseMap).3769static const std::optional<BitPart> &3770collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,3771std::map<Value *, std::optional<BitPart>> &BPS, int Depth,3772bool &FoundRoot) {3773auto I = BPS.find(V);3774if (I != BPS.end())3775return I->second;37763777auto &Result = BPS[V] = std::nullopt;3778auto BitWidth = V->getType()->getScalarSizeInBits();37793780// Can't do integer/elements > 128 bits.3781if (BitWidth > 128)3782return Result;37833784// Prevent stack overflow by limiting the recursion depth3785if (Depth == BitPartRecursionMaxDepth) {3786LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");3787return Result;3788}37893790if (auto *I = dyn_cast<Instruction>(V)) {3791Value *X, *Y;3792const APInt *C;37933794// If this is an or instruction, it may be an inner node of the bswap.3795if (match(V, m_Or(m_Value(X), m_Value(Y)))) {3796// Check we have both sources and they are from the same provider.3797const auto &A = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,3798Depth + 1, FoundRoot);3799if (!A || !A->Provider)3800return Result;38013802const auto &B = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,3803Depth + 1, FoundRoot);3804if (!B || A->Provider != B->Provider)3805return Result;38063807// Try and merge the two together.3808Result = BitPart(A->Provider, BitWidth);3809for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx) {3810if (A->Provenance[BitIdx] != BitPart::Unset &&3811B->Provenance[BitIdx] != BitPart::Unset &&3812A->Provenance[BitIdx] != B->Provenance[BitIdx])3813return Result = std::nullopt;38143815if (A->Provenance[BitIdx] == BitPart::Unset)3816Result->Provenance[BitIdx] = B->Provenance[BitIdx];3817else3818Result->Provenance[BitIdx] = A->Provenance[BitIdx];3819}38203821return Result;3822}38233824// If this is a logical shift by a constant, recurse then shift the result.3825if (match(V, m_LogicalShift(m_Value(X), m_APInt(C)))) {3826const APInt &BitShift = *C;38273828// Ensure the shift amount is defined.3829if (BitShift.uge(BitWidth))3830return Result;38313832// For bswap-only, limit shift amounts to whole bytes, for an early exit.3833if (!MatchBitReversals && (BitShift.getZExtValue() % 8) != 0)3834return Result;38353836const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,3837Depth + 1, FoundRoot);3838if (!Res)3839return Result;3840Result = Res;38413842// Perform the "shift" on BitProvenance.3843auto &P = Result->Provenance;3844if (I->getOpcode() == Instruction::Shl) {3845P.erase(std::prev(P.end(), BitShift.getZExtValue()), P.end());3846P.insert(P.begin(), BitShift.getZExtValue(), BitPart::Unset);3847} else {3848P.erase(P.begin(), std::next(P.begin(), BitShift.getZExtValue()));3849P.insert(P.end(), BitShift.getZExtValue(), BitPart::Unset);3850}38513852return Result;3853}38543855// If this is a logical 'and' with a mask that clears bits, recurse then3856// unset the appropriate bits.3857if (match(V, m_And(m_Value(X), m_APInt(C)))) {3858const APInt &AndMask = *C;38593860// Check that the mask allows a multiple of 8 bits for a bswap, for an3861// early exit.3862unsigned NumMaskedBits = AndMask.popcount();3863if (!MatchBitReversals && (NumMaskedBits % 8) != 0)3864return Result;38653866const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,3867Depth + 1, FoundRoot);3868if (!Res)3869return Result;3870Result = Res;38713872for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)3873// If the AndMask is zero for this bit, clear the bit.3874if (AndMask[BitIdx] == 0)3875Result->Provenance[BitIdx] = BitPart::Unset;3876return Result;3877}38783879// If this is a zext instruction zero extend the result.3880if (match(V, m_ZExt(m_Value(X)))) {3881const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,3882Depth + 1, FoundRoot);3883if (!Res)3884return Result;38853886Result = BitPart(Res->Provider, BitWidth);3887auto NarrowBitWidth = X->getType()->getScalarSizeInBits();3888for (unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)3889Result->Provenance[BitIdx] = Res->Provenance[BitIdx];3890for (unsigned BitIdx = NarrowBitWidth; BitIdx < BitWidth; ++BitIdx)3891Result->Provenance[BitIdx] = BitPart::Unset;3892return Result;3893}38943895// If this is a truncate instruction, extract the lower bits.3896if (match(V, m_Trunc(m_Value(X)))) {3897const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,3898Depth + 1, FoundRoot);3899if (!Res)3900return Result;39013902Result = BitPart(Res->Provider, BitWidth);3903for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)3904Result->Provenance[BitIdx] = Res->Provenance[BitIdx];3905return Result;3906}39073908// BITREVERSE - most likely due to us previous matching a partial3909// bitreverse.3910if (match(V, m_BitReverse(m_Value(X)))) {3911const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,3912Depth + 1, FoundRoot);3913if (!Res)3914return Result;39153916Result = BitPart(Res->Provider, BitWidth);3917for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)3918Result->Provenance[(BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];3919return Result;3920}39213922// BSWAP - most likely due to us previous matching a partial bswap.3923if (match(V, m_BSwap(m_Value(X)))) {3924const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,3925Depth + 1, FoundRoot);3926if (!Res)3927return Result;39283929unsigned ByteWidth = BitWidth / 8;3930Result = BitPart(Res->Provider, BitWidth);3931for (unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {3932unsigned ByteBitOfs = ByteIdx * 8;3933for (unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)3934Result->Provenance[(BitWidth - 8 - ByteBitOfs) + BitIdx] =3935Res->Provenance[ByteBitOfs + BitIdx];3936}3937return Result;3938}39393940// Funnel 'double' shifts take 3 operands, 2 inputs and the shift3941// amount (modulo).3942// fshl(X,Y,Z): (X << (Z % BW)) | (Y >> (BW - (Z % BW)))3943// fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))3944if (match(V, m_FShl(m_Value(X), m_Value(Y), m_APInt(C))) ||3945match(V, m_FShr(m_Value(X), m_Value(Y), m_APInt(C)))) {3946// We can treat fshr as a fshl by flipping the modulo amount.3947unsigned ModAmt = C->urem(BitWidth);3948if (cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fshr)3949ModAmt = BitWidth - ModAmt;39503951// For bswap-only, limit shift amounts to whole bytes, for an early exit.3952if (!MatchBitReversals && (ModAmt % 8) != 0)3953return Result;39543955// Check we have both sources and they are from the same provider.3956const auto &LHS = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,3957Depth + 1, FoundRoot);3958if (!LHS || !LHS->Provider)3959return Result;39603961const auto &RHS = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,3962Depth + 1, FoundRoot);3963if (!RHS || LHS->Provider != RHS->Provider)3964return Result;39653966unsigned StartBitRHS = BitWidth - ModAmt;3967Result = BitPart(LHS->Provider, BitWidth);3968for (unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)3969Result->Provenance[BitIdx + ModAmt] = LHS->Provenance[BitIdx];3970for (unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)3971Result->Provenance[BitIdx] = RHS->Provenance[BitIdx + StartBitRHS];3972return Result;3973}3974}39753976// If we've already found a root input value then we're never going to merge3977// these back together.3978if (FoundRoot)3979return Result;39803981// Okay, we got to something that isn't a shift, 'or', 'and', etc. This must3982// be the root input value to the bswap/bitreverse.3983FoundRoot = true;3984Result = BitPart(V, BitWidth);3985for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)3986Result->Provenance[BitIdx] = BitIdx;3987return Result;3988}39893990static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,3991unsigned BitWidth) {3992if (From % 8 != To % 8)3993return false;3994// Convert from bit indices to byte indices and check for a byte reversal.3995From >>= 3;3996To >>= 3;3997BitWidth >>= 3;3998return From == BitWidth - To - 1;3999}40004001static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,4002unsigned BitWidth) {4003return From == BitWidth - To - 1;4004}40054006bool llvm::recognizeBSwapOrBitReverseIdiom(4007Instruction *I, bool MatchBSwaps, bool MatchBitReversals,4008SmallVectorImpl<Instruction *> &InsertedInsts) {4009if (!match(I, m_Or(m_Value(), m_Value())) &&4010!match(I, m_FShl(m_Value(), m_Value(), m_Value())) &&4011!match(I, m_FShr(m_Value(), m_Value(), m_Value())) &&4012!match(I, m_BSwap(m_Value())))4013return false;4014if (!MatchBSwaps && !MatchBitReversals)4015return false;4016Type *ITy = I->getType();4017if (!ITy->isIntOrIntVectorTy() || ITy->getScalarSizeInBits() > 128)4018return false; // Can't do integer/elements > 128 bits.40194020// Try to find all the pieces corresponding to the bswap.4021bool FoundRoot = false;4022std::map<Value *, std::optional<BitPart>> BPS;4023const auto &Res =4024collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0, FoundRoot);4025if (!Res)4026return false;4027ArrayRef<int8_t> BitProvenance = Res->Provenance;4028assert(all_of(BitProvenance,4029[](int8_t I) { return I == BitPart::Unset || 0 <= I; }) &&4030"Illegal bit provenance index");40314032// If the upper bits are zero, then attempt to perform as a truncated op.4033Type *DemandedTy = ITy;4034if (BitProvenance.back() == BitPart::Unset) {4035while (!BitProvenance.empty() && BitProvenance.back() == BitPart::Unset)4036BitProvenance = BitProvenance.drop_back();4037if (BitProvenance.empty())4038return false; // TODO - handle null value?4039DemandedTy = Type::getIntNTy(I->getContext(), BitProvenance.size());4040if (auto *IVecTy = dyn_cast<VectorType>(ITy))4041DemandedTy = VectorType::get(DemandedTy, IVecTy);4042}40434044// Check BitProvenance hasn't found a source larger than the result type.4045unsigned DemandedBW = DemandedTy->getScalarSizeInBits();4046if (DemandedBW > ITy->getScalarSizeInBits())4047return false;40484049// Now, is the bit permutation correct for a bswap or a bitreverse? We can4050// only byteswap values with an even number of bytes.4051APInt DemandedMask = APInt::getAllOnes(DemandedBW);4052bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;4053bool OKForBitReverse = MatchBitReversals;4054for (unsigned BitIdx = 0;4055(BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {4056if (BitProvenance[BitIdx] == BitPart::Unset) {4057DemandedMask.clearBit(BitIdx);4058continue;4059}4060OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[BitIdx], BitIdx,4061DemandedBW);4062OKForBitReverse &= bitTransformIsCorrectForBitReverse(BitProvenance[BitIdx],4063BitIdx, DemandedBW);4064}40654066Intrinsic::ID Intrin;4067if (OKForBSwap)4068Intrin = Intrinsic::bswap;4069else if (OKForBitReverse)4070Intrin = Intrinsic::bitreverse;4071else4072return false;40734074Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);4075Value *Provider = Res->Provider;40764077// We may need to truncate the provider.4078if (DemandedTy != Provider->getType()) {4079auto *Trunc =4080CastInst::CreateIntegerCast(Provider, DemandedTy, false, "trunc", I->getIterator());4081InsertedInsts.push_back(Trunc);4082Provider = Trunc;4083}40844085Instruction *Result = CallInst::Create(F, Provider, "rev", I->getIterator());4086InsertedInsts.push_back(Result);40874088if (!DemandedMask.isAllOnes()) {4089auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);4090Result = BinaryOperator::Create(Instruction::And, Result, Mask, "mask", I->getIterator());4091InsertedInsts.push_back(Result);4092}40934094// We may need to zeroextend back to the result type.4095if (ITy != Result->getType()) {4096auto *ExtInst = CastInst::CreateIntegerCast(Result, ITy, false, "zext", I->getIterator());4097InsertedInsts.push_back(ExtInst);4098}40994100return true;4101}41024103// CodeGen has special handling for some string functions that may replace4104// them with target-specific intrinsics. Since that'd skip our interceptors4105// in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,4106// we mark affected calls as NoBuiltin, which will disable optimization4107// in CodeGen.4108void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(4109CallInst *CI, const TargetLibraryInfo *TLI) {4110Function *F = CI->getCalledFunction();4111LibFunc Func;4112if (F && !F->hasLocalLinkage() && F->hasName() &&4113TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&4114!F->doesNotAccessMemory())4115CI->addFnAttr(Attribute::NoBuiltin);4116}41174118bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {4119// We can't have a PHI with a metadata type.4120if (I->getOperand(OpIdx)->getType()->isMetadataTy())4121return false;41224123// Early exit.4124if (!isa<Constant>(I->getOperand(OpIdx)))4125return true;41264127switch (I->getOpcode()) {4128default:4129return true;4130case Instruction::Call:4131case Instruction::Invoke: {4132const auto &CB = cast<CallBase>(*I);41334134// Can't handle inline asm. Skip it.4135if (CB.isInlineAsm())4136return false;41374138// Constant bundle operands may need to retain their constant-ness for4139// correctness.4140if (CB.isBundleOperand(OpIdx))4141return false;41424143if (OpIdx < CB.arg_size()) {4144// Some variadic intrinsics require constants in the variadic arguments,4145// which currently aren't markable as immarg.4146if (isa<IntrinsicInst>(CB) &&4147OpIdx >= CB.getFunctionType()->getNumParams()) {4148// This is known to be OK for stackmap.4149return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;4150}41514152// gcroot is a special case, since it requires a constant argument which4153// isn't also required to be a simple ConstantInt.4154if (CB.getIntrinsicID() == Intrinsic::gcroot)4155return false;41564157// Some intrinsic operands are required to be immediates.4158return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);4159}41604161// It is never allowed to replace the call argument to an intrinsic, but it4162// may be possible for a call.4163return !isa<IntrinsicInst>(CB);4164}4165case Instruction::ShuffleVector:4166// Shufflevector masks are constant.4167return OpIdx != 2;4168case Instruction::Switch:4169case Instruction::ExtractValue:4170// All operands apart from the first are constant.4171return OpIdx == 0;4172case Instruction::InsertValue:4173// All operands apart from the first and the second are constant.4174return OpIdx < 2;4175case Instruction::Alloca:4176// Static allocas (constant size in the entry block) are handled by4177// prologue/epilogue insertion so they're free anyway. We definitely don't4178// want to make them non-constant.4179return !cast<AllocaInst>(I)->isStaticAlloca();4180case Instruction::GetElementPtr:4181if (OpIdx == 0)4182return true;4183gep_type_iterator It = gep_type_begin(I);4184for (auto E = std::next(It, OpIdx); It != E; ++It)4185if (It.isStruct())4186return false;4187return true;4188}4189}41904191Value *llvm::invertCondition(Value *Condition) {4192// First: Check if it's a constant4193if (Constant *C = dyn_cast<Constant>(Condition))4194return ConstantExpr::getNot(C);41954196// Second: If the condition is already inverted, return the original value4197Value *NotCondition;4198if (match(Condition, m_Not(m_Value(NotCondition))))4199return NotCondition;42004201BasicBlock *Parent = nullptr;4202Instruction *Inst = dyn_cast<Instruction>(Condition);4203if (Inst)4204Parent = Inst->getParent();4205else if (Argument *Arg = dyn_cast<Argument>(Condition))4206Parent = &Arg->getParent()->getEntryBlock();4207assert(Parent && "Unsupported condition to invert");42084209// Third: Check all the users for an invert4210for (User *U : Condition->users())4211if (Instruction *I = dyn_cast<Instruction>(U))4212if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))4213return I;42144215// Last option: Create a new instruction4216auto *Inverted =4217BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv");4218if (Inst && !isa<PHINode>(Inst))4219Inverted->insertAfter(Inst);4220else4221Inverted->insertBefore(&*Parent->getFirstInsertionPt());4222return Inverted;4223}42244225bool llvm::inferAttributesFromOthers(Function &F) {4226// Note: We explicitly check for attributes rather than using cover functions4227// because some of the cover functions include the logic being implemented.42284229bool Changed = false;4230// readnone + not convergent implies nosync4231if (!F.hasFnAttribute(Attribute::NoSync) &&4232F.doesNotAccessMemory() && !F.isConvergent()) {4233F.setNoSync();4234Changed = true;4235}42364237// readonly implies nofree4238if (!F.hasFnAttribute(Attribute::NoFree) && F.onlyReadsMemory()) {4239F.setDoesNotFreeMemory();4240Changed = true;4241}42424243// willreturn implies mustprogress4244if (!F.hasFnAttribute(Attribute::MustProgress) && F.willReturn()) {4245F.setMustProgress();4246Changed = true;4247}42484249// TODO: There are a bunch of cases of restrictive memory effects we4250// can infer by inspecting arguments of argmemonly-ish functions.42514252return Changed;4253}425442554256