57#include "llvm/IR/IntrinsicsWebAssembly.h"
90#define DEBUG_TYPE "local"
92STATISTIC(NumRemoved,
"Number of unreachable basic blocks removed");
93STATISTIC(NumPHICSEs,
"Number of PHI's that got CSE'd");
97#ifdef EXPENSIVE_CHECKS
103 cl::desc(
"Perform extra assertion checking to verify that PHINodes's hash "
104 "function is well-behaved w.r.t. its isEqual predicate"));
109 "When the basic block contains not more than this number of PHI nodes, "
110 "perform a (faster!) exhaustive search instead of set-driven one."));
113 "max-phi-entries-increase-after-removing-empty-block",
cl::init(1000),
115 cl::desc(
"Stop removing an empty block if removing it will introduce more "
116 "than this number of phi entries in its successor"));
143 if (Dest2 == Dest1) {
149 assert(BI->getParent() &&
"Terminator not inserted in block!");
157 NewBI->
copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
158 LLVMContext::MD_annotation});
161 BI->eraseFromParent();
162 if (DeleteDeadConditions)
182 NewBI->
copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
183 LLVMContext::MD_annotation});
185 BI->eraseFromParent();
202 if (
SI->defaultDestUnreachable() &&
SI->getNumCases() > 0)
203 TheOnlyDest =
SI->case_begin()->getCaseSuccessor();
208 for (
auto It =
SI->case_begin(),
End =
SI->case_end(); It !=
End;) {
210 if (It->getCaseValue() == CI) {
211 TheOnlyDest = It->getCaseSuccessor();
217 if (It->getCaseSuccessor() == DefaultDest) {
219 unsigned NCases =
SI->getNumCases();
222 if (NCases > 1 && MD) {
228 unsigned Idx = It->getCaseIndex();
231 if (Weights[0] >
UINT64_MAX - Weights[Idx + 1])
234 Weights[0] += Weights[Idx + 1];
243 It =
SI->removeCase(It);
244 End =
SI->case_end();
250 It =
SI->case_begin();
260 if (It->getCaseSuccessor() != TheOnlyDest)
261 TheOnlyDest =
nullptr;
267 if (CI && !TheOnlyDest) {
270 TheOnlyDest =
SI->getDefaultDest();
278 Builder.CreateBr(TheOnlyDest);
286 if (DTU && Succ != TheOnlyDest)
287 RemovedSuccessors.
insert(Succ);
289 if (Succ == SuccToKeep) {
290 SuccToKeep =
nullptr;
292 Succ->removePredecessor(BB);
298 SI->eraseFromParent();
299 if (DeleteDeadConditions)
302 std::vector<DominatorTree::UpdateType> Updates;
303 Updates.reserve(RemovedSuccessors.
size());
304 for (
auto *RemovedSuccessor : RemovedSuccessors)
311 if (
SI->getNumCases() == 1) {
314 auto FirstCase = *
SI->case_begin();
316 Value *
Cond = Builder.CreateICmpEQ(
SI->getCondition(),
317 FirstCase.getCaseValue(),
"cond");
321 Cond, FirstCase.getCaseSuccessor(),
SI->getDefaultDest());
335 MDNode *MakeImplicitMD =
SI->getMetadata(LLVMContext::MD_make_implicit);
337 NewBr->
setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
340 SI->eraseFromParent();
350 BasicBlock *TheOnlyDest = BA->getBasicBlock();
355 Builder.CreateBr(TheOnlyDest);
358 for (
unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
360 if (DTU && DestBB != TheOnlyDest)
361 RemovedSuccessors.
insert(DestBB);
362 if (IBI->getDestination(i) == SuccToKeep) {
363 SuccToKeep =
nullptr;
369 IBI->eraseFromParent();
370 if (DeleteDeadConditions)
377 BA->destroyConstant();
388 std::vector<DominatorTree::UpdateType> Updates;
389 Updates.reserve(RemovedSuccessors.
size());
390 for (
auto *RemovedSuccessor : RemovedSuccessors)
417 if (
I->isTerminator())
429 if (!
I->willReturn()) {
434 switch (
II->getIntrinsicID()) {
435 case Intrinsic::experimental_guard: {
444 case Intrinsic::wasm_trunc_signed:
445 case Intrinsic::wasm_trunc_unsigned:
446 case Intrinsic::ptrauth_auth:
447 case Intrinsic::ptrauth_resign:
448 case Intrinsic::ptrauth_resign_load_relative:
455 if (!
I->mayHaveSideEffects())
462 if (
II->getIntrinsicID() == Intrinsic::stacksave ||
463 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
468 if (
II->getIntrinsicID() == Intrinsic::allow_runtime_check ||
469 II->getIntrinsicID() == Intrinsic::allow_ubsan_check)
472 if (
II->isLifetimeStartOrEnd()) {
473 auto *Arg =
II->getArgOperand(0);
480 return isa<LifetimeIntrinsic>(Use.getUser());
485 if (
II->getIntrinsicID() == Intrinsic::assume &&
488 return !
Cond->isZero();
494 std::optional<fp::ExceptionBehavior> ExBehavior =
495 FPI->getExceptionBehavior();
511 LI->getPointerOperand()->stripPointerCasts()))
512 if (!LI->isVolatile() && GV->isConstant())
524 std::function<
void(
Value *)> AboutToDeleteCallback) {
532 AboutToDeleteCallback);
540 std::function<
void(
Value *)> AboutToDeleteCallback) {
541 unsigned S = 0, E = DeadInsts.
size(), Alive = 0;
542 for (; S != E; ++S) {
545 DeadInsts[S] =
nullptr;
552 AboutToDeleteCallback);
559 std::function<
void(
Value *)> AboutToDeleteCallback) {
561 while (!DeadInsts.
empty()) {
567 "Live instruction found in dead worklist!");
568 assert(
I->use_empty() &&
"Instructions with uses are not dead.");
573 if (AboutToDeleteCallback)
574 AboutToDeleteCallback(
I);
578 for (
Use &OpU :
I->operands()) {
579 Value *OpV = OpU.get();
595 I->eraseFromParent();
610 for (++UI; UI != UE; ++UI) {
635 if (!Visited.
insert(
I).second) {
643 if (KnownNonDeadPHIs && KnownNonDeadPHIs->
contains(CurPN))
649 if (KnownNonDeadPHIs)
650 for (
PHINode *VisitedPN : VisitedPHIs)
651 KnownNonDeadPHIs->
insert(VisitedPN);
666 for (
unsigned i = 0, e =
I->getNumOperands(); i != e; ++i) {
667 Value *OpV =
I->getOperand(i);
668 I->setOperand(i,
nullptr);
681 I->eraseFromParent();
689 for (
User *U :
I->users()) {
697 if (!
I->use_empty()) {
698 I->replaceAllUsesWith(SimpleV);
702 I->eraseFromParent();
717 bool MadeChange =
false;
734 assert(!BI->isTerminator());
744 while (!WorkList.
empty()) {
760 Value *NewVal = PN->getIncomingValue(0);
763 PN->replaceAllUsesWith(NewVal);
764 PN->eraseFromParent();
768 assert(PredBB &&
"Block doesn't have a single predecessor!");
782 if (PredOfPredBB != PredBB)
783 if (SeenPreds.
insert(PredOfPredBB).second)
787 if (SeenPreds.
insert(PredOfPredBB).second)
819 "The successor list of PredBB isn't empty before "
820 "applying corresponding DTU updates.");
850 unsigned Budget = 16;
854 if (NumSuccs > Budget)
891 if (BBPreds.
count(IBB) &&
895 <<
"Can't fold, phi node " << PN->
getName() <<
" in "
896 << Succ->
getName() <<
" is conflicting with "
897 << BBPN->
getName() <<
" with regard to common predecessor "
909 if (BBPreds.
count(IBB) &&
913 <<
" is conflicting with regard to common "
914 <<
"predecessor " << IBB->
getName() <<
"\n");
944 (!(It->second) || It->second == OldVal)) &&
945 "Expected OldVal to match incoming value from BB!");
951 if (It != IncomingValues.
end() && It->second)
970 auto It = IncomingValues.
find(BB);
971 if (It != IncomingValues.
end())
986 unsigned PoisonCount =
count_if(UndefOps, [&](
unsigned I) {
990 if (PoisonCount == 0 || PoisonCount == UndefOps.
size())
993 for (
unsigned I : UndefOps)
1012 if (It == IncomingValues.
end())
1041 if (BB->
phis().empty() || Succ->
phis().empty())
1056 if (BBPreds.
count(SuccPred)) {
1059 CommonPred = SuccPred;
1075 unsigned NumChangedPhi = 0;
1076 for (
auto &Phi : Succ->
phis()) {
1080 if (IncomingPhi->getParent() == BB)
1089 return (NumPreds - 1) * NumChangedPhi >
1107 bool HasSharedPreds) {
1108 assert((HasSharedPreds || !CommonPred) &&
"Unexpected CommonPred!");
1110 assert(OldVal &&
"No entry in PHI for Pred BB!");
1115 IncomingValues[
Pred] =
nullptr;
1143 if (PredBB == CommonPred)
1163 if (PredBB == CommonPred)
1188 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
1210 BB, Succ, BBPreds, CommonPred);
1235 if (PN->getIncomingBlock(U) != BB)
1245 if (BBPhisMergeable && CommonPred)
1247 <<
" and " << Succ->
getName() <<
" : "
1248 << CommonPred->
getName() <<
"\n");
1316 if (TI->hasNonDebugLocLoopMetadata())
1318 if (
Instruction *PredTI = Pred->getTerminatorOrNull())
1319 if (PredTI->hasNonDebugLocLoopMetadata())
1324 else if (BBPhisMergeable)
1341 if (SeenPreds.
insert(PredOfBB).second)
1350 if (SeenPreds.
insert(PredOfBB).second && PredOfBB != CommonPred)
1380 assert(PN->use_empty() &&
"There shouldn't be any uses here!");
1381 PN->eraseFromParent();
1389 if (TI->hasNonDebugLocLoopMetadata()) {
1390 MDNode *LoopMD = TI->getMetadata(LLVMContext::MD_loop);
1392 Pred->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopMD);
1410 "applying corresponding DTU updates.");
1411 }
else if (BBPhisMergeable) {
1415 return UseInst->getParent() != CommonPred &&
1416 BBPreds.
contains(UseInst->getParent());
1448 if (
ToRemove.contains(DuplicatePN))
1454 PN->andIRFlags(DuplicatePN);
1474 struct PHIDenseMapInfo {
1481 return static_cast<unsigned>(
1486 static unsigned getHashValue(
PHINode *PN) {
1499 return LHS->isIdenticalToWhenDefined(
RHS);
1520 auto Inserted = PHISet.
insert(PN);
1521 if (!Inserted.second) {
1524 (*Inserted.first)->andIRFlags(PN);
1525 PN->replaceAllUsesWith(*Inserted.first);
1554 PN->eraseFromParent();
1560 V = V->stripPointerCasts();
1568 Align CurrentAlign = AI->getAlign();
1569 if (PrefAlign <= CurrentAlign)
1570 return CurrentAlign;
1575 if (StackAlign && PrefAlign > *StackAlign)
1576 return CurrentAlign;
1577 AI->setAlignment(PrefAlign);
1583 Align CurrentAlign = GV->getPointerAlignment(
DL);
1584 if (PrefAlign <= CurrentAlign)
1585 return CurrentAlign;
1591 if (!GV->canIncreaseAlignment())
1592 return CurrentAlign;
1594 if (GV->isThreadLocal()) {
1595 unsigned MaxTLSAlign = GV->getParent()->getMaxTLSAlignment() / CHAR_BIT;
1596 if (MaxTLSAlign && PrefAlign >
Align(MaxTLSAlign))
1597 PrefAlign =
Align(MaxTLSAlign);
1600 GV->setAlignment(PrefAlign);
1612 assert(V->getType()->isPointerTy() &&
1613 "getOrEnforceKnownAlignment expects a pointer!");
1616 unsigned TrailZ =
Known.countMinTrailingZeros();
1625 if (PrefAlign && *PrefAlign > Alignment)
1647 if ((DVR->getVariable() == DIVar) && (DVR->getExpression() == DIExpr))
1663 TypeSize ValueSize =
DL.getTypeAllocSizeInBits(ValTy);
1664 if (std::optional<uint64_t> FragmentSize =
1674 "address of variable must have exactly 1 location operand.");
1677 if (std::optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(
DL)) {
1694 Instr->getParent()->insertDbgRecordBefore(DVRec, Instr);
1707 assert(DIVar &&
"Missing variable");
1709 Value *DV =
SI->getValueOperand();
1729 DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
1739 LLVM_DEBUG(
dbgs() <<
"Failed to convert dbg.declare to dbg.value: " << *DVR
1749 SI->getParent()->insertDbgRecordBefore(NewDVR,
SI->getIterator());
1755 assert(DIVar &&
"Missing variable");
1758 Value *DV =
SI->getValueOperand();
1773 assert(DIVar &&
"Missing variable");
1779 LLVM_DEBUG(
dbgs() <<
"Failed to convert dbg.declare to DbgVariableRecord: "
1795 LI->
getParent()->insertDbgRecordAfter(DV, LI);
1808 switch (DTy->getTag()) {
1809 case dwarf::DW_TAG_pointer_type:
1810 case dwarf::DW_TAG_reference_type:
1811 case dwarf::DW_TAG_rvalue_reference_type:
1812 case dwarf::DW_TAG_ptr_to_member_type:
1813 case dwarf::DW_TAG_LLVM_ptrauth_type:
1815 case dwarf::DW_TAG_typedef:
1816 case dwarf::DW_TAG_const_type:
1817 case dwarf::DW_TAG_volatile_type:
1818 case dwarf::DW_TAG_restrict_type:
1819 case dwarf::DW_TAG_atomic_type:
1820 case dwarf::DW_TAG_immutable_type:
1821 Ty = DTy->getBaseType();
1835 assert(DIVar &&
"Missing variable");
1844 LLVM_DEBUG(
dbgs() <<
"Failed to convert dbg.declare to DbgVariableRecord: "
1857 if (InsertionPt != BB->
end()) {
1869 for (
auto &FI :
F) {
1898 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1899 return LI->isVolatile();
1900 if (StoreInst *SI = dyn_cast<StoreInst>(U))
1901 return SI->isVolatile();
1908 while (!WorkList.
empty()) {
1910 for (
const auto &AIUse : V->uses()) {
1911 User *U = AIUse.getUser();
1913 if (AIUse.getOperandNo() == 1)
1921 if (!CI->isLifetimeStartOrEnd()) {
1930 if (BI->getType()->isPointerTy())
1935 DDI->eraseFromParent();
1951 assert(BB &&
"No BasicBlock to clone DbgVariableRecord(s) from.");
1952 if (InsertedPHIs.
size() == 0)
1957 for (
auto &
I : *BB) {
1959 for (
Value *V : DVR.location_ops())
1964 if (DbgValueMap.
size() == 0)
1979 for (
auto PHI : InsertedPHIs) {
1984 for (
auto VI :
PHI->operand_values()) {
1985 auto V = DbgValueMap.
find(VI);
1986 if (V != DbgValueMap.
end()) {
1988 auto NewDI = NewDbgValueMap.
find({Parent, DbgII});
1989 if (NewDI == NewDbgValueMap.
end()) {
1991 NewDI = NewDbgValueMap.
insert({{Parent, DbgII}, NewDbgII}).first;
2002 for (
auto DI : NewDbgValueMap) {
2006 assert(InsertionPt != Parent->
end() &&
"Ill-formed basic block");
2018 assert(DII->getVariable() &&
"Missing variable");
2019 auto *DIExpr = DII->getExpression();
2021 DII->setExpression(DIExpr);
2022 DII->replaceVariableLocationOp(
Address, NewAddress);
2027 return !DVRDeclares.
empty();
2035 assert(DIVar &&
"Missing variable");
2060 DVR->getExpression(), NewAllocaAddress, DVR,
2075 assert(Assign.isDbgAssign() && Assign.getAddress() == &
I &&
2076 "dbg.assign must use salvaged instruction as its address");
2077 assert(!Assign.getAddressExpression()->getFragmentInfo().has_value() &&
2078 "address-expression shouldn't have fragment info");
2093 Assign.getAddressExpression(),
Ops, 0,
false);
2095 "address-expression shouldn't have fragment info");
2100 if (AdditionalValues.
empty()) {
2101 Assign.setAddress(NewAddress);
2102 Assign.setAddressExpression(SalvagedExpr);
2104 Assign.setKillAddress();
2115 const unsigned MaxDebugArgs = 16;
2116 const unsigned MaxExpressionSize = 128;
2124 "DbgVariableRecord must use salvaged instruction as its location");
2130 Value *Replacement =
nullptr;
2132 auto LocIt =
find(LocationOps, &
I);
2133 while (SalvagedExpr && LocIt != LocationOps.end()) {
2135 unsigned LocationIndex = std::distance(LocationOps.begin(), LocIt);
2142 LocIt = std::find(++LocIt, LocationOps.end(), &
I);
2151 const bool FitsExpressionLimit =
2153 if (AdditionalValues.
empty() && FitsExpressionLimit) {
2172 bool ProcessedAnyUse =
false;
2174 for (
auto *DVR : DbgRecords) {
2177 if (DVR->isDbgAssign()) {
2178 if (DVR->getAddress() == &
I) {
2180 ProcessedAnyUse =
true;
2182 if (DVR->getValue() != &
I)
2187 ProcessedAnyUse =
true;
2190 if (ProcessedAnyUse)
2193 for (
auto *DVR : DbgRecords)
2194 DVR->setKillLocation();
2201 unsigned BitWidth =
DL.getIndexSizeInBits(
GEP->getPointerAddressSpace());
2205 if (!
GEP->collectOffset(
DL,
BitWidth, VariableOffsets, ConstantOffset))
2207 if (!VariableOffsets.
empty() && !CurrentLocOps) {
2208 Opcodes.
insert(Opcodes.
begin(), {dwarf::DW_OP_LLVM_arg, 0});
2211 for (
const auto &
Offset : VariableOffsets) {
2214 "Expected strictly positive multiplier for offset.");
2216 Offset.second.getZExtValue(), dwarf::DW_OP_mul,
2217 dwarf::DW_OP_plus});
2220 return GEP->getOperand(0);
2225 case Instruction::Add:
2226 return dwarf::DW_OP_plus;
2227 case Instruction::Sub:
2228 return dwarf::DW_OP_minus;
2229 case Instruction::Mul:
2230 return dwarf::DW_OP_mul;
2231 case Instruction::SDiv:
2232 return dwarf::DW_OP_div;
2233 case Instruction::SRem:
2234 return dwarf::DW_OP_mod;
2235 case Instruction::Or:
2236 return dwarf::DW_OP_or;
2237 case Instruction::And:
2238 return dwarf::DW_OP_and;
2239 case Instruction::Xor:
2240 return dwarf::DW_OP_xor;
2241 case Instruction::Shl:
2242 return dwarf::DW_OP_shl;
2243 case Instruction::LShr:
2244 return dwarf::DW_OP_shr;
2245 case Instruction::AShr:
2246 return dwarf::DW_OP_shra;
2257 if (!CurrentLocOps) {
2262 AdditionalValues.
push_back(
I->getOperand(1));
2271 if (ConstInt && ConstInt->getBitWidth() > 64)
2277 uint64_t Val = ConstInt->getSExtValue();
2280 if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {
2281 uint64_t Offset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);
2285 Opcodes.
append({dwarf::DW_OP_constu, Val});
2304 return dwarf::DW_OP_eq;
2306 return dwarf::DW_OP_ne;
2309 return dwarf::DW_OP_gt;
2312 return dwarf::DW_OP_ge;
2315 return dwarf::DW_OP_lt;
2318 return dwarf::DW_OP_le;
2330 if (ConstInt && ConstInt->getBitWidth() > 64)
2338 uint64_t Val = ConstInt->getSExtValue();
2356 auto &M = *
I.getModule();
2357 auto &
DL = M.getDataLayout();
2360 Value *FromValue = CI->getOperand(0);
2362 if (CI->isNoopCast(
DL)) {
2376 if (FromType->isPointerTy())
2377 FromType =
DL.getIntPtrType(FromType);
2379 unsigned FromTypeBitSize = FromType->getScalarSizeInBits();
2384 Ops.append(ExtOps.begin(), ExtOps.end());
2413 if (DPUsers.
empty())
2421 bool DomPointAfterFrom = From.
getNextNode() == &DomPoint;
2424 for (
auto *DVR : DPUsers) {
2430 if (DomPointAfterFrom && NextNonDebug == &DomPoint) {
2433 DomPoint.
getParent()->insertDbgRecordAfter(DVR, &DomPoint);
2438 }
else if (!DT.
dominates(&DomPoint, MarkedInstr)) {
2439 UndefOrSalvageDVR.
insert(DVR);
2445 for (
auto *DVR : DPUsers) {
2446 if (UndefOrSalvageDVR.
count(DVR))
2459 if (!UndefOrSalvageDVR.
empty()) {
2483 bool SameSize =
DL.getTypeSizeInBits(FromTy) ==
DL.getTypeSizeInBits(ToTy);
2484 bool LosslessConversion = !
DL.isNonIntegralPointerType(FromTy) &&
2485 !
DL.isNonIntegralPointerType(ToTy);
2486 return SameSize && LosslessConversion;
2499 assert(&From != &To &&
"Can't replace something with itself");
2505 return DVR.getExpression();
2519 assert(FromBits != ToBits &&
"Unexpected no-op conversion");
2523 if (FromBits < ToBits)
2534 return std::nullopt;
2551 I->dropDbgRecords();
2552 for (
Use &U :
I->operands()) {
2565 unsigned NumDeadInst = 0;
2572 while (EndInst != &BB->
front()) {
2605 Successor->removePredecessor(BB, PreserveLCSSA);
2610 UI->setDebugLoc(
I->getDebugLoc());
2613 unsigned NumInstrsRemoved = 0;
2615 while (BBI != BBE) {
2616 if (!BBI->use_empty())
2618 BBI++->eraseFromParent();
2624 for (
BasicBlock *UniqueSuccessor : UniqueSuccessors)
2629 return NumInstrsRemoved;
2635 II->getOperandBundlesAsDefs(OpBundles);
2637 II->getCalledOperand(), Args, OpBundles);
2643 uint64_t TotalWeight;
2647 auto NewWeights =
uint32_t(TotalWeight) != TotalWeight
2650 NewCall->
setMetadata(LLVMContext::MD_prof, NewWeights);
2661 II->replaceAllUsesWith(NewCall);
2669 BI->setDebugLoc(
II->getDebugLoc());
2675 II->eraseFromParent();
2706 UnwindEdge, InvokeArgs, OpBundles, CI->
getName(), BB);
2710 II->setMetadata(LLVMContext::MD_prof, CI->
getMetadata(LLVMContext::MD_prof));
2720 Split->front().eraseFromParent();
2739 if (FoldInstsToUnreachable) {
2742 Value *Callee = CI->getCalledOperand();
2745 auto IntrinsicID =
F->getIntrinsicID();
2750 if (IntrinsicID == Intrinsic::assume) {
2751 if (
match(CI->getArgOperand(0),
2759 }
else if (IntrinsicID == Intrinsic::experimental_guard) {
2779 ->getAddressSpace())) ||
2785 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2802 if (
SI->isVolatile())
2805 Value *Ptr =
SI->getOperand(1);
2810 SI->getPointerAddressSpace()))) {
2821 Value *Callee =
II->getCalledOperand();
2828 if (
II->doesNotReturn() &&
2839 Ctx, OrigNormalDest->
getName() +
".unreachable",
2840 II->getFunction(), OrigNormalDest);
2841 Reachable.resize(
II->getFunction()->getMaxBlockNumber());
2844 II->setNormalDest(UnreachableNormalDest);
2852 if (
II->use_empty() && !
II->mayHaveSideEffects()) {
2858 II->eraseFromParent();
2868 struct CatchPadDenseMapInfo {
2875 return LHS->isIdenticalTo(
RHS);
2882 CatchPadDenseMapInfo,
2887 E = CatchSwitch->handler_end();
2891 ++NumPerSuccessorCases[HandlerBB];
2893 if (!HandlerSet.insert({CatchPad, Empty}).second) {
2895 --NumPerSuccessorCases[HandlerBB];
2896 CatchSwitch->removeHandler(
I);
2903 std::vector<DominatorTree::UpdateType> Updates;
2904 for (
const auto &
I : NumPerSuccessorCases)
2914 if (!Reachable[
Successor->getNumber()]) {
2916 Reachable[
Successor->getNumber()] =
true;
2919 }
while (!Worklist.
empty());
2934 UnwindDest = CRI->getUnwindDest();
2937 CatchSwitch->getParentPad(),
nullptr, CatchSwitch->getNumHandlers(),
2938 CatchSwitch->getName(), CatchSwitch->getIterator());
2939 for (
BasicBlock *PadBB : CatchSwitch->handlers())
2940 NewCatchSwitch->addHandler(PadBB);
2942 NewTI = NewCatchSwitch;
2943 UnwindDest = CatchSwitch->getUnwindDest();
2963 bool FoldInstsToUnreachable) {
2971 if (Reachable[BB.getNumber()])
2976 BlocksToRemove.
insert(&BB);
2979 if (BlocksToRemove.
empty())
2983 NumRemoved += BlocksToRemove.
size();
2996 bool DoesKMove,
bool AAOnly =
false) {
2998 K->getAllMetadataOtherThanDebugLoc(
Metadata);
3000 unsigned Kind = MD.first;
3007 K->setMetadata(Kind,
nullptr);
3009 case LLVMContext::MD_dbg:
3011 case LLVMContext::MD_DIAssignID:
3013 K->mergeDIAssignID(J);
3015 case LLVMContext::MD_tbaa:
3019 case LLVMContext::MD_alias_scope:
3023 case LLVMContext::MD_noalias:
3024 case LLVMContext::MD_mem_parallel_loop_access:
3028 case LLVMContext::MD_access_group:
3030 K->setMetadata(LLVMContext::MD_access_group,
3033 case LLVMContext::MD_range:
3034 if (!AAOnly && (DoesKMove || !
K->hasMetadata(LLVMContext::MD_noundef)))
3037 case LLVMContext::MD_nofpclass:
3038 if (!AAOnly && (DoesKMove || !
K->hasMetadata(LLVMContext::MD_noundef)))
3041 case LLVMContext::MD_fpmath:
3045 case LLVMContext::MD_invariant_load:
3046 case LLVMContext::MD_invariant_group:
3052 K->setMetadata(Kind, JMD);
3054 case LLVMContext::MD_nonnull:
3055 if (!AAOnly && (DoesKMove || !
K->hasMetadata(LLVMContext::MD_noundef)))
3056 K->setMetadata(Kind, JMD);
3061 case LLVMContext::MD_prof:
3062 case LLVMContext::MD_mmra:
3063 case LLVMContext::MD_memprof:
3064 case LLVMContext::MD_callsite:
3066 case LLVMContext::MD_callee_type:
3068 K->setMetadata(LLVMContext::MD_callee_type,
3072 case LLVMContext::MD_callees:
3075 if (!AAOnly && DoesKMove)
3078 case LLVMContext::MD_align:
3079 if (!AAOnly && (DoesKMove || !
K->hasMetadata(LLVMContext::MD_noundef)))
3083 case LLVMContext::MD_dereferenceable:
3084 case LLVMContext::MD_dereferenceable_or_null:
3085 if (!AAOnly && DoesKMove)
3086 K->setMetadata(Kind,
3089 case LLVMContext::MD_preserve_access_index:
3092 case LLVMContext::MD_noundef:
3094 if (!AAOnly && DoesKMove)
3095 K->setMetadata(Kind, JMD);
3097 case LLVMContext::MD_nontemporal:
3100 K->setMetadata(Kind, JMD);
3102 case LLVMContext::MD_mem_cache_hint:
3105 if (!AAOnly && KMD != JMD)
3106 K->setMetadata(Kind,
nullptr);
3108 case LLVMContext::MD_noalias_addrspace:
3110 K->setMetadata(Kind,
3113 case LLVMContext::MD_nosanitize:
3115 K->setMetadata(Kind, JMD);
3117 case LLVMContext::MD_captures:
3123 case LLVMContext::MD_alloc_token:
3124 if (!AAOnly && KMD != JMD)
3133 auto JMMRA = J->
getMetadata(LLVMContext::MD_mmra);
3134 auto KMMRA =
K->getMetadata(LLVMContext::MD_mmra);
3135 if (JMMRA || KMMRA) {
3136 K->setMetadata(LLVMContext::MD_mmra,
3143 auto *JMemProf = J->
getMetadata(LLVMContext::MD_memprof);
3144 auto *KMemProf =
K->getMetadata(LLVMContext::MD_memprof);
3145 if (!AAOnly && (JMemProf || KMemProf)) {
3146 K->setMetadata(LLVMContext::MD_memprof,
3153 auto *JCallSite = J->
getMetadata(LLVMContext::MD_callsite);
3154 auto *KCallSite =
K->getMetadata(LLVMContext::MD_callsite);
3155 if (!AAOnly && (JCallSite || KCallSite)) {
3156 K->setMetadata(LLVMContext::MD_callsite,
3163 auto *JProf = J->
getMetadata(LLVMContext::MD_prof);
3164 auto *KProf =
K->getMetadata(LLVMContext::MD_prof);
3165 if (!AAOnly && (JProf || KProf)) {
3171 K->setMetadata(LLVMContext::MD_prof,
3187 Source.getAllMetadata(MD);
3191 for (
const auto &MDPair : MD) {
3192 unsigned ID = MDPair.first;
3202 case LLVMContext::MD_dbg:
3203 case LLVMContext::MD_tbaa:
3204 case LLVMContext::MD_prof:
3205 case LLVMContext::MD_fpmath:
3206 case LLVMContext::MD_tbaa_struct:
3207 case LLVMContext::MD_invariant_load:
3208 case LLVMContext::MD_alias_scope:
3209 case LLVMContext::MD_noalias:
3210 case LLVMContext::MD_nontemporal:
3211 case LLVMContext::MD_mem_cache_hint:
3212 case LLVMContext::MD_mem_parallel_loop_access:
3213 case LLVMContext::MD_access_group:
3214 case LLVMContext::MD_noundef:
3215 case LLVMContext::MD_noalias_addrspace:
3216 case LLVMContext::MD_invariant_group:
3217 case LLVMContext::MD_mmra:
3222 case LLVMContext::MD_nonnull:
3226 case LLVMContext::MD_align:
3227 case LLVMContext::MD_dereferenceable:
3228 case LLVMContext::MD_dereferenceable_or_null:
3234 case LLVMContext::MD_range:
3238 case LLVMContext::MD_nofpclass:
3242 if (NewType->
getScalarType() == Source.getType()->getScalarType())
3268 ReplInst->andIRFlags(
I);
3273 bool Success = CB1->tryIntersectAttributes(CB2);
3274 assert(
Success &&
"We should not be trying to sink callbases "
3275 "with non-intersectable attributes");
3293template <
typename ShouldReplaceFn>
3295 const ShouldReplaceFn &ShouldReplace) {
3301 if (
II &&
II->getIntrinsicID() == Intrinsic::fake_use)
3303 if (!ShouldReplace(U))
3307 dbgs() <<
"' with " << *To <<
" in " << *U.getUser() <<
"\n");
3321 if (
I->getParent() == BB)
3332 auto Dominates = [&](
const Use &U) {
return DT.
dominates(Root, U); };
3333 return ::replaceDominatedUsesWith(From, To, Dominates);
3339 auto Dominates = [&](
const Use &U) {
return DT.
dominates(BB, U); };
3340 return ::replaceDominatedUsesWith(From, To, Dominates);
3346 auto Dominates = [&](
const Use &U) {
return DT.
dominates(
I, U); };
3347 return ::replaceDominatedUsesWith(From, To, Dominates);
3353 auto DominatesAndShouldReplace = [&](
const Use &U) {
3354 return DT.
dominates(Root, U) && ShouldReplace(U, To);
3356 return ::replaceDominatedUsesWith(From, To, DominatesAndShouldReplace);
3362 auto DominatesAndShouldReplace = [&](
const Use &U) {
3363 return DT.
dominates(BB, U) && ShouldReplace(U, To);
3365 return ::replaceDominatedUsesWith(From, To, DominatesAndShouldReplace);
3371 auto DominatesAndShouldReplace = [&](
const Use &U) {
3372 return DT.
dominates(
I, U) && ShouldReplace(U, To);
3374 return ::replaceDominatedUsesWith(From, To, DominatesAndShouldReplace);
3380 if (
Call->hasFnAttr(
"gc-leaf-function"))
3383 if (
F->hasFnAttribute(
"gc-leaf-function"))
3386 if (
auto IID =
F->getIntrinsicID()) {
3388 return IID != Intrinsic::experimental_gc_statepoint &&
3389 IID != Intrinsic::experimental_deoptimize &&
3390 IID != Intrinsic::memcpy_element_unordered_atomic &&
3391 IID != Intrinsic::memmove_element_unordered_atomic;
3403 auto *NewTy = NewLI.
getType();
3406 if (NewTy->isPointerTy()) {
3413 if (!NewTy->isIntegerTy())
3428 auto *NewTy = NewLI.
getType();
3430 if (NewTy == OldLI.
getType()) {
3439 if (!NewTy->isPointerTy())
3442 unsigned BitWidth =
DL.getPointerTypeSizeInBits(NewTy);
3453 for (
auto *DVR : DPUsers)
3454 DVR->eraseFromParent();
3486 I->dropUBImplyingAttrsAndMetadata();
3487 if (
I->isUsedByMetadata())
3490 I->dropDbgRecords();
3493 II =
I->eraseFromParent();
3508 std::optional<int64_t> InitIntOpt;
3514 static_cast<uint64_t
>(*InitIntOpt))
3519 return createIntegerExpression(
C);
3522 if (
FP && Ty.isFloatingPointTy() && Ty.getScalarSizeInBits() <= 64) {
3530 if (!Ty.isPointerTy())
3537 if (CE->getOpcode() == Instruction::IntToPtr) {
3538 const Value *V = CE->getOperand(0);
3540 return createIntegerExpression(*CI);
3546 auto RemapDebugOperands = [&Mapping](
auto *DV,
auto Set) {
3547 for (
auto *
Op : Set) {
3549 if (
I != Mapping.
end())
3550 DV->replaceVariableLocationOp(
Op,
I->second,
true);
3553 auto RemapAssignAddress = [&Mapping](
auto *DA) {
3554 auto I = Mapping.
find(DA->getAddress());
3555 if (
I != Mapping.
end())
3556 DA->setAddress(
I->second);
3559 RemapDebugOperands(&DVR, DVR.location_ops());
3560 if (DVR.isDbgAssign())
3561 RemapAssignAddress(&DVR);
3570 BitPart(
Value *
P,
unsigned BW) : Provider(
P) {
3581 enum { Unset = -1 };
3613static const std::optional<BitPart> &
3615 std::map<
Value *, std::optional<BitPart>> &BPS,
int Depth,
3617 auto [
I, Inserted] = BPS.try_emplace(
V);
3621 auto &Result =
I->second;
3622 auto BitWidth =
V->getType()->getScalarSizeInBits();
3630 LLVM_DEBUG(
dbgs() <<
"collectBitParts max recursion depth reached.\n");
3642 Depth + 1, FoundRoot);
3643 if (!
A || !
A->Provider)
3647 Depth + 1, FoundRoot);
3648 if (!
B ||
A->Provider !=
B->Provider)
3652 Result = BitPart(
A->Provider,
BitWidth);
3653 for (
unsigned BitIdx = 0; BitIdx <
BitWidth; ++BitIdx) {
3654 if (
A->Provenance[BitIdx] != BitPart::Unset &&
3655 B->Provenance[BitIdx] != BitPart::Unset &&
3656 A->Provenance[BitIdx] !=
B->Provenance[BitIdx])
3657 return Result = std::nullopt;
3659 if (
A->Provenance[BitIdx] == BitPart::Unset)
3660 Result->Provenance[BitIdx] =
B->Provenance[BitIdx];
3662 Result->Provenance[BitIdx] =
A->Provenance[BitIdx];
3670 const APInt &BitShift = *
C;
3677 if (!MatchBitReversals && (BitShift.
getZExtValue() % 8) != 0)
3681 Depth + 1, FoundRoot);
3687 auto &
P = Result->Provenance;
3688 if (
I->getOpcode() == Instruction::Shl) {
3702 const APInt &AndMask = *
C;
3706 unsigned NumMaskedBits = AndMask.
popcount();
3707 if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
3711 Depth + 1, FoundRoot);
3716 for (
unsigned BitIdx = 0; BitIdx <
BitWidth; ++BitIdx)
3718 if (AndMask[BitIdx] == 0)
3719 Result->Provenance[BitIdx] = BitPart::Unset;
3726 Depth + 1, FoundRoot);
3730 Result = BitPart(Res->Provider,
BitWidth);
3731 auto NarrowBitWidth =
X->getType()->getScalarSizeInBits();
3732 for (
unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
3733 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3734 for (
unsigned BitIdx = NarrowBitWidth; BitIdx <
BitWidth; ++BitIdx)
3735 Result->Provenance[BitIdx] = BitPart::Unset;
3742 Depth + 1, FoundRoot);
3746 Result = BitPart(Res->Provider,
BitWidth);
3747 for (
unsigned BitIdx = 0; BitIdx <
BitWidth; ++BitIdx)
3748 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3756 Depth + 1, FoundRoot);
3760 Result = BitPart(Res->Provider,
BitWidth);
3761 for (
unsigned BitIdx = 0; BitIdx <
BitWidth; ++BitIdx)
3762 Result->Provenance[(
BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
3769 Depth + 1, FoundRoot);
3774 Result = BitPart(Res->Provider,
BitWidth);
3775 for (
unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
3776 unsigned ByteBitOfs = ByteIdx * 8;
3777 for (
unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
3778 Result->Provenance[(
BitWidth - 8 - ByteBitOfs) + BitIdx] =
3779 Res->Provenance[ByteBitOfs + BitIdx];
3796 if (!MatchBitReversals && (ModAmt % 8) != 0)
3801 Depth + 1, FoundRoot);
3802 if (!
LHS || !
LHS->Provider)
3806 Depth + 1, FoundRoot);
3807 if (!
RHS ||
LHS->Provider !=
RHS->Provider)
3810 unsigned StartBitRHS =
BitWidth - ModAmt;
3812 for (
unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
3813 Result->Provenance[BitIdx + ModAmt] =
LHS->Provenance[BitIdx];
3814 for (
unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
3815 Result->Provenance[BitIdx] =
RHS->Provenance[BitIdx + StartBitRHS];
3829 for (
unsigned BitIdx = 0; BitIdx <
BitWidth; ++BitIdx)
3830 Result->Provenance[BitIdx] = BitIdx;
3836 if (From % 8 != To % 8)
3851 Instruction *
I,
bool MatchBSwaps,
bool MatchBitReversals,
3858 if (!MatchBSwaps && !MatchBitReversals)
3860 Type *ITy =
I->getType();
3866 bool FoundRoot =
false;
3867 std::map<Value *, std::optional<BitPart>> BPS;
3874 [](int8_t
I) {
return I == BitPart::Unset || 0 <=
I; }) &&
3875 "Illegal bit provenance index");
3878 Type *DemandedTy = ITy;
3879 if (BitProvenance.
back() == BitPart::Unset) {
3880 while (!BitProvenance.
empty() && BitProvenance.
back() == BitPart::Unset)
3881 BitProvenance = BitProvenance.
drop_back();
3882 if (BitProvenance.
empty())
3897 bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;
3898 bool OKForBitReverse = MatchBitReversals;
3899 for (
unsigned BitIdx = 0;
3900 (BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
3901 if (BitProvenance[BitIdx] == BitPart::Unset) {
3908 BitIdx, DemandedBW);
3913 Intrin = Intrinsic::bswap;
3914 else if (OKForBitReverse)
3915 Intrin = Intrinsic::bitreverse;
3921 Value *Provider = Res->Provider;
3924 if (DemandedTy != Provider->
getType()) {
3935 auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);
3941 if (ITy != Result->getType()) {
3957 if (
F && !
F->hasLocalLinkage() &&
F->hasName() &&
3958 TLI->hasOptimizedCodeGen(
TLI->getLibFunc(
F->getName())) &&
3959 !
F->doesNotAccessMemory())
3964 const auto *
Op =
I->getOperand(OpIdx);
3966 if (
Op->getType()->isMetadataTy() ||
Op->getType()->isTokenLikeTy())
3972 if (
Op->isSwiftError())
3976 if (
I->isLifetimeStartOrEnd())
3983 switch (
I->getOpcode()) {
3986 case Instruction::Call:
3987 case Instruction::Invoke: {
3991 if (CB.isInlineAsm())
3996 if (CB.isBundleOperand(OpIdx))
3999 if (OpIdx < CB.arg_size()) {
4003 OpIdx >= CB.getFunctionType()->getNumParams()) {
4005 return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
4010 if (CB.getIntrinsicID() == Intrinsic::gcroot)
4015 if (CB.getIntrinsicID() == Intrinsic::threadlocal_address)
4019 return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
4026 case Instruction::ShuffleVector:
4029 case Instruction::Switch:
4030 case Instruction::ExtractValue:
4033 case Instruction::InsertValue:
4036 case Instruction::Alloca:
4041 case Instruction::GetElementPtr:
4045 for (
auto E = std::next(It, OpIdx); It != E; ++It)
4058 Value *NotCondition;
4060 return NotCondition;
4068 assert(Parent &&
"Unsupported condition to invert");
4092 if (!
F.hasFnAttribute(Attribute::NoSync) &&
4093 F.doesNotAccessMemory() && !
F.isConvergent()) {
4099 if (!
F.hasFnAttribute(Attribute::NoFree) &&
F.onlyReadsMemory()) {
4100 F.setDoesNotFreeMemory();
4105 if (!
F.hasFnAttribute(Attribute::MustProgress) &&
F.willReturn()) {
4106 F.setMustProgress();
4120 "can only use mergeFlags on instructions with matching opcodes");
4125 HasNUW &=
I.hasNoUnsignedWrap();
4126 HasNSW &=
I.hasNoSignedWrap();
4133 I.dropPoisonGeneratingFlags();
4134 if (
I.getOpcode() == Instruction::Add ||
4137 I.setHasNoUnsignedWrap();
4139 I.setHasNoSignedWrap();
static unsigned getIntrinsicID(const SDNode *N)
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(const Function &Caller, const Function &Callee)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
static unsigned getHashValueImpl(SimpleValue Val)
static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
uint64_t IntrinsicInst * II
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
Remove Loads Into Fake Uses
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
APInt bitcastToAPInt() const
Class for arbitrary precision integers.
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
void clearBit(unsigned BitPosition)
Set a given bit to 0.
uint64_t getZExtValue() const
Get zero extended value.
unsigned popcount() const
Count the number of bits set.
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
unsigned getBitWidth() const
Return the number of bits in the APInt.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
int64_t getSExtValue() const
Get sign extended value.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
an instruction to allocate memory on the stack
const Value * getArraySize() const
Get the number of elements allocated.
This class represents an incoming formal argument to a Function.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & back() const
Get the last element.
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
size_t size() const
Get the array size.
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
bool empty() const
Check if the array is empty.
Value handle that asserts if the Value is deleted.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
unsigned getNumber() const
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
const Instruction & back() const
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
const Instruction * getTerminatorOrNull() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
LLVM_ABI void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
LLVM_ABI bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
BinaryOps getOpcode() const
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a no-op cast from one type to another.
The address of a basic block.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
FunctionType * getFunctionType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
mapped_iterator< op_iterator, DerefFnTy > handler_iterator
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
@ ICMP_ULE
unsigned less or equal
Predicate getPredicate() const
Return the predicate for this instruction.
Conditional Branch instruction.
A constant value that is initialized with an expression using other constant values.
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This is an important base class in LLVM.
LLVM_ABI void destroyConstant()
Called if some element of this constant is no longer valid.
DIExpression * createConstantValueExpression(uint64_t Val)
Create an expression for a variable that does not have an address, but does have a constant value.
static LLVM_ABI DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
unsigned getNumElements() const
static LLVM_ABI ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed)
Returns the ops for a zero- or sign-extension in a DIExpression.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
LLVM_ABI DIExpression * foldConstantMath()
Try to shorten an expression with constant math operations that can be evaluated at compile time.
LLVM_ABI uint64_t getNumLocationOperands() const
Return the number of unique location operands referred to (via DW_OP_LLVM_arg) in this expression; th...
ArrayRef< uint64_t > getElements() const
LLVM_ABI std::optional< uint64_t > getActiveBits(DIVariable *Var)
Return the number of bits that have an active value, i.e.
uint64_t getElement(unsigned I) const
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
static LLVM_ABI DIExpression * appendExt(const DIExpression *Expr, unsigned FromSize, unsigned ToSize, bool Signed)
Append a zero- or sign-extension to Expr.
std::optional< DIBasicType::Signedness > getSignedness() const
Return the signedness of this variable's type, or std::nullopt if this type is neither signed nor uns...
A parsed version of the target data layout string in and methods for querying it.
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
LLVM_ABI void removeFromParent()
LLVM_ABI Module * getModule()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void addVariableLocationOps(ArrayRef< Value * > NewValues, DIExpression *NewExpr)
Adding a new location operand will always result in this intrinsic using an ArgList,...
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
LLVM_ABI unsigned getNumVariableLocationOps() const
bool isAddressOfVariable() const
Does this describe the address of a local variable.
LLVM_ABI DbgVariableRecord * clone() const
void setExpression(DIExpression *NewExpr)
DIExpression * getExpression() const
DILocalVariable * getVariable() const
LLVM_ABI void setKillLocation()
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
DILocation * get() const
Get the underlying DILocation.
static DebugLoc getTemporary()
iterator find(const_arg_type_t< KeyT > Val)
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
std::pair< iterator, bool > insert_or_assign(const KeyT &Key, V &&Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
const BasicBlock & getEntryBlock() const
void applyUpdatesPermissive(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
bool hasDomTree() const
Returns true if it holds a DomTreeT.
void recalculate(FuncT &F)
Notify DTU that the entry block was replaced.
bool isBBPendingDeletion(BasicBlockT *DelBB) const
Returns true if DelBB is awaiting deletion.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
user_iterator_impl< Instruction > user_iterator
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void dropDbgRecords()
Erase any DbgRecords attached to this instruction.
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
Value * getPointerOperand()
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
LLVM_ABI MDNode * createRange(const APInt &Lo, const APInt &Hi)
Return metadata describing the range [Lo, Hi).
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMergedCallsiteMetadata(MDNode *A, MDNode *B)
static LLVM_ABI CaptureComponents toCaptureComponents(const MDNode *MD)
Convert !captures metadata to CaptureComponents. MD may be nullptr.
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMergedCalleesMetadata(MDNode *A, MDNode *B)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDNode * getMergedProfMetadata(MDNode *A, MDNode *B, const Instruction *AInstr, const Instruction *BInstr)
Merge !prof metadata from two instructions.
static LLVM_ABI MDNode * getMergedAllocTokenMetadata(const MDNode *A, const MDNode *B)
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericNoFPClass(MDNode *A, MDNode *B)
LLVMContext & getContext() const
static LLVM_ABI MDNode * fromCaptureComponents(LLVMContext &Ctx, CaptureComponents CC)
Convert CaptureComponents to !captures metadata.
static LLVM_ABI MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
LLVM_ABI void changeToUnreachable(const Instruction *I)
Instruction I will be changed to an unreachable.
LLVM_ABI void removeBlocks(const SmallSetVector< BasicBlock *, 8 > &DeadBlocks)
Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
A Module instance is used to store all the information related to an LLVM module.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
size_type size() const
Determine the number of elements in the SetVector.
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Vector takeVector()
Clear the SetVector and return the underlying vector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
value_type pop_back_val()
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Provides information about what library functions are available for the current target.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
static constexpr TypeSize getFixed(ScalarTy ExactSize)
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
value_op_iterator value_op_end()
Value * getOperand(unsigned i) const
value_op_iterator value_op_begin()
iterator_range< value_op_iterator > operand_values()
iterator find(const KeyT &Val)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< user_iterator > users()
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
bool isUsedByMetadata() const
Return true if there is metadata referencing this value.
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Represents an op.with.overflow intrinsic.
std::pair< iterator, bool > insert(const ValueT &V)
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_BSwap(const Opnd0 &Op0)
auto m_BitReverse(const Opnd0 &Op0)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
auto m_Value()
Match an arbitrary value and ignore it.
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
auto m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
auto m_Undef()
Match an arbitrary undef constant.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
auto m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
@ ebStrict
This corresponds to "fpexcept.strict".
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than its terminator and any present EH pad instructi...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
bool succ_empty(const Instruction *I)
LLVM_ABI BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge, DomTreeUpdater *DTU=nullptr)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
LLVM_ABI unsigned replaceDominatedUsesWithIf(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge, function_ref< bool(const Use &U, const Value *To)> ShouldReplace)
Replace each use of 'From' with 'To' if that use is dominated by the given edge and the callback Shou...
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
@ Known
Known to have no common set bits.
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool isRemovableAlloc(const CallBase *V, const TargetLibraryInfo *TLI)
Return true if this is a call to an allocation function that does not have side effects that we are r...
LLVM_ABI CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
LLVM_ABI bool isMathLibCallNoop(const CallBase *Call, const TargetLibraryInfo *TLI)
Check whether the given call has no side-effects.
LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
constexpr from_range_t from_range
bool hasNItemsOrLess(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;})
Returns true if the sequence [Begin, End) has N or less items.
LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst)
Remap the operands of the debug records attached to Inst, and the operands of Inst itself if it's a d...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
auto cast_or_null(const Y &Val)
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
LLVM_ABI bool isAssumeWithEmptyBundle(const AssumeInst &Assume)
Return true iff the operand bundles of the provided llvm.assume doesn't contain any valuable informat...
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
LLVM_ABI void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode * > &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI MDNode * intersectAccessGroups(const Instruction *Inst1, const Instruction *Inst2)
Compute the access-group list of access groups that Inst1 and Inst2 are both in.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI bool handleUnreachableTerminator(Instruction *I, SmallVectorImpl< Value * > &PoisonedValues)
If a terminator in an unreachable basic block has an operand of type Instruction, transform it into p...
LLVM_ABI bool canSimplifyInvokeNoUnwind(const Function *F)
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool FoldInstsToUnreachable=true)
Remove all blocks that can not be reached from the function's entry.
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
LLVM_ABI bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes,...
LLVM_ABI SmallVector< uint32_t > fitWeights(ArrayRef< uint64_t > Weights)
Push the weights right to fit in uint32_t.
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
LLVM_ABI MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
LLVM_ABI bool LowerDbgDeclare(Function &F)
Lowers dbg.declare records into appropriate set of dbg.value records.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI DIExpression * getExpressionForConstant(DIBuilder &DIB, const Constant &C, Type &Ty)
Given a constant, create a debug information expression.
LLVM_ABI CallInst * createCallMatchingInvoke(InvokeInst *II)
Create a call that matches the invoke II in terms of arguments, attributes, debug information,...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableRecord * > DbgRecords)
Salvage only the records in DbgRecords instead of finding every debug user of I.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
Inserts a dbg.value record before a store to an alloca'd value that has an associated dbg....
LLVM_ABI Instruction * removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl, bool DoesKMove=false)
Patch the replacement so that it is not more restrictive than the value being replaced.
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge)
Replace each use of 'From' with 'To' if that use is dominated by the given edge.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
@ Success
The lock was released successfully.
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
LLVM_ABI void dropDebugUsers(Instruction &I)
Remove the debug intrinsic instructions for the given instruction.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!...
LLVM_ABI void hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, BasicBlock *BB)
Hoist all of the instructions in the IfBlock to the dominant block DomBlock, by moving its instructio...
LLVM_ABI void copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a range metadata node to a new load instruction.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
LLVM_ABI DebugLoc getDebugValueLoc(DbgVariableRecord *DVR)
Produce a DebugLoc to use for each dbg.declare that is promoted to a dbg.value.
LLVM_ABI void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a nonnull metadata node to a new load instruction.
LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
DWARFExpression::Operation Op
LLVM_ABI void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, int Offset=0)
Replaces multiple dbg.value records when the alloca it describes is replaced with a new value.
LLVM_ABI Align tryEnforceAlignment(Value *V, Align PrefAlign, const DataLayout &DL)
If the specified pointer points to an object that we control, try to modify the object's alignment to...
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow instructions that are not...
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRDeclares(Value *V)
Finds dbg.declare records declaring local variables as living in the memory that 'V' points to.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
LLVM_ABI void combineAAMetadata(Instruction *K, const Instruction *J)
Combine metadata of two instructions, where instruction J is a memory access that has been merged int...
LLVM_ABI bool inferAttributesFromOthers(Function &F)
If we can infer one attribute from another on the declaration of a function, explicitly materialize t...
LLVM_ABI Value * invertCondition(Value *Condition)
Invert the given true/false value, possibly reusing an existing copy.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
LLVM_ABI void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
LLVM_ABI bool callsGCLeafFunction(const CallBase *Call, const TargetLibraryInfo &TLI)
Return true if this call calls a gc leaf function.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
LLVM_ABI bool replaceDbgDeclare(Value *Address, Value *NewAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces dbg.declare record when the address it describes is replaced with a new value.
LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData, SmallVectorImpl< uint64_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
This struct is a compact representation of a valid (non-zero power of two) alignment.
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
std::optional< unsigned > Opcode
Opcode of merged instructions.
LLVM_ABI void mergeFlags(Instruction &I)
Merge in the no-wrap flags from I.
LLVM_ABI void applyFlags(Instruction &I)
Apply the no-wrap flags to I if applicable.
A MapVector that performs no allocations if smaller than a certain size.