90 #define DEBUG_TYPE "local" 92 STATISTIC(NumRemoved,
"Number of unreachable basic blocks removed");
116 if (
auto *BI = dyn_cast<BranchInst>(T)) {
117 if (BI->isUnconditional())
return false;
121 if (
auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
124 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
125 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
139 if (Dest2 == Dest1) {
145 assert(BI->getParent() &&
"Terminator not inserted in block!");
150 Value *Cond = BI->getCondition();
151 BI->eraseFromParent();
152 if (DeleteDeadConditions)
159 if (
auto *
SI = dyn_cast<SwitchInst>(T)) {
167 if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
168 SI->getNumCases() > 0) {
169 TheOnlyDest =
SI->case_begin()->getCaseSuccessor();
173 for (
auto i =
SI->case_begin(),
e =
SI->case_end(); i !=
e;) {
175 if (i->getCaseValue() == CI) {
176 TheOnlyDest = i->getCaseSuccessor();
182 if (i->getCaseSuccessor() == DefaultDest) {
183 MDNode *MD =
SI->getMetadata(LLVMContext::MD_prof);
184 unsigned NCases =
SI->getNumCases();
192 auto *CI = mdconst::extract<ConstantInt>(MD->
getOperand(MD_i));
193 Weights.
push_back(CI->getValue().getZExtValue());
196 unsigned idx = i->getCaseIndex();
197 Weights[0] += Weights[idx+1];
201 SI->setMetadata(LLVMContext::MD_prof,
203 createBranchWeights(Weights));
207 DefaultDest->removePredecessor(ParentBB);
208 i =
SI->removeCase(i);
219 if (i->getCaseSuccessor() != TheOnlyDest)
220 TheOnlyDest =
nullptr;
226 if (CI && !TheOnlyDest) {
229 TheOnlyDest =
SI->getDefaultDest();
238 std::vector <DominatorTree::UpdateType> Updates;
240 Updates.reserve(
SI->getNumSuccessors() - 1);
245 if (Succ == TheOnlyDest) {
246 TheOnlyDest =
nullptr;
255 Value *Cond =
SI->getCondition();
256 SI->eraseFromParent();
257 if (DeleteDeadConditions)
264 if (
SI->getNumCases() == 1) {
267 auto FirstCase = *
SI->case_begin();
269 FirstCase.getCaseValue(),
"cond");
273 FirstCase.getCaseSuccessor(),
274 SI->getDefaultDest());
275 MDNode *MD =
SI->getMetadata(LLVMContext::MD_prof);
278 mdconst::dyn_extract<ConstantInt>(MD->
getOperand(2));
280 mdconst::dyn_extract<ConstantInt>(MD->
getOperand(1));
286 SIDef->getValue().getZExtValue()));
290 MDNode *MakeImplicitMD =
SI->getMetadata(LLVMContext::MD_make_implicit);
292 NewBr->
setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
295 SI->eraseFromParent();
301 if (
auto *IBI = dyn_cast<IndirectBrInst>(T)) {
304 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
305 BasicBlock *TheOnlyDest = BA->getBasicBlock();
306 std::vector <DominatorTree::UpdateType> Updates;
308 Updates.reserve(IBI->getNumDestinations() - 1);
313 for (
unsigned i = 0,
e = IBI->getNumDestinations(); i !=
e; ++i) {
314 if (IBI->getDestination(i) == TheOnlyDest) {
315 TheOnlyDest =
nullptr;
325 IBI->eraseFromParent();
326 if (DeleteDeadConditions)
333 BA->destroyConstant();
379 if (DDI->getAddress())
401 if (II->getIntrinsicID() == Intrinsic::stacksave ||
402 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
406 if (II->isLifetimeStartOrEnd())
407 return isa<UndefValue>(II->getArgOperand(1));
413 if (II->getIntrinsicID() == Intrinsic::assume ||
414 II->getIntrinsicID() == Intrinsic::experimental_guard) {
415 if (
ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
416 return !Cond->isZero();
426 if (
Constant *
C = dyn_cast<Constant>(CI->getArgOperand(0)))
427 return C->isNullValue() || isa<UndefValue>(
C);
429 if (
auto *Call = dyn_cast<CallBase>(I))
457 while (!DeadInsts.
empty()) {
461 "Live instruction found in dead worklist!");
469 Value *OpV = OpU.get();
492 for (
auto *DII : DbgUsers) {
497 return !DbgUsers.empty();
511 for (++UI; UI != UE; ++UI) {
527 I = cast<Instruction>(*
I->user_begin())) {
533 if (!Visited.
insert(
I).second) {
578 WorkList.
insert(cast<Instruction>(U));
583 bool Changed =
false;
604 bool MadeChange =
false;
621 assert(!BI->isTerminator());
627 if (!WorkList.count(I))
631 while (!WorkList.empty()) {
645 if (!isa<PHINode>(BB->
begin()))
654 while (
PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
656 Value *OldPhiIt = PhiIt;
664 if (PhiIt != OldPhiIt) PhiIt = &BB->
front();
674 while (
PHINode *PN = dyn_cast<PHINode>(DestBB->
begin())) {
675 Value *NewVal = PN->getIncomingValue(0);
679 PN->eraseFromParent();
683 assert(PredBB &&
"Block doesn't have a single predecessor!");
685 bool ReplaceEntryBB =
false;
687 ReplaceEntryBB =
true;
730 "The successor list of PredBB isn't empty before " 731 "applying corresponding DTU updates.");
752 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
780 if (BBPN && BBPN->getParent() == BB) {
783 if (BBPreds.
count(IBB) &&
787 <<
"Can't fold, phi node " << PN->
getName() <<
" in " 788 << Succ->
getName() <<
" is conflicting with " 789 << BBPN->getName() <<
" with regard to common predecessor " 801 if (BBPreds.
count(IBB) &&
805 <<
" is conflicting with regard to common " 806 <<
"predecessor " << IBB->
getName() <<
"\n");
833 if (!isa<UndefValue>(OldVal)) {
835 IncomingValues.
find(BB)->second == OldVal) &&
836 "Expected OldVal to match incoming value from BB!");
838 IncomingValues.
insert(std::make_pair(BB, OldVal));
843 if (It != IncomingValues.
end())
return It->second;
862 if (!isa<UndefValue>(V))
863 IncomingValues.
insert(std::make_pair(BB, V));
877 if (!isa<UndefValue>(V))
continue;
881 if (It == IncomingValues.
end())
continue;
898 assert(OldVal &&
"No entry in PHI for Pred BB!");
915 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->
getParent() == BB) {
916 PHINode *OldValPN = cast<PHINode>(OldVal);
933 for (
unsigned i = 0,
e = BBPreds.
size(); i !=
e; ++i) {
952 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
956 if (BB == Succ)
return false;
974 if (!Succ->getSinglePredecessor()) {
976 while (isa<PHINode>(*BBI)) {
977 for (
Use &U : BBI->uses()) {
978 if (
PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
979 if (PN->getIncomingBlock(U) != BB)
992 if (
auto *CBI = dyn_cast<CallBrInst>((*I)->getTerminator())) {
993 if (Succ == CBI->getDefaultDest())
995 for (
unsigned i = 0,
e = CBI->getNumIndirectDests(); i !=
e; ++i)
996 if (Succ == CBI->getIndirectDest(i))
1015 if (isa<PHINode>(Succ->begin())) {
1029 if (Succ->getSinglePredecessor()) {
1035 Succ->getInstList().
splice(Succ->getFirstNonPHI()->getIterator(),
1038 while (
PHINode *PN = dyn_cast<PHINode>(&BB->
front())) {
1040 assert(PN->use_empty() &&
"There shouldn't be any uses here!");
1041 PN->eraseFromParent();
1058 if (!Succ->hasName()) Succ->takeName(BB);
1065 "applying corresponding DTU updates.");
1081 struct PHIDenseMapInfo {
1082 static PHINode *getEmptyKey() {
1086 static PHINode *getTombstoneKey() {
1090 static unsigned getHashValue(
PHINode *PN) {
1100 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1101 RHS == getEmptyKey() || RHS == getTombstoneKey())
1111 bool Changed =
false;
1113 auto Inserted = PHISet.
insert(PN);
1114 if (!Inserted.second) {
1138 assert(PrefAlign > Alignment);
1142 if (
AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1149 Alignment =
std::max(AI->getAlignment(), Alignment);
1150 if (PrefAlign <= Alignment)
1161 if (
auto *GO = dyn_cast<GlobalObject>(V)) {
1163 Alignment =
std::max(GO->getAlignment(), Alignment);
1164 if (PrefAlign <= Alignment)
1171 if (!GO->canIncreaseAlignment())
1187 "getOrEnforceKnownAlignment expects a pointer!");
1190 unsigned TrailZ = Known.countMinTrailingZeros();
1194 TrailZ = std::min(TrailZ,
unsigned(
sizeof(
unsigned) * CHAR_BIT - 1));
1196 unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
1201 if (PrefAlign > Align)
1223 DVI->getVariable() == DIVar &&
1224 DVI->getExpression() == DIExpr)
1239 for (
auto *DVI : DbgValues) {
1240 assert(DVI->getValue() == APN);
1241 if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1260 return ValueSize >= *FragmentSize;
1266 if (
auto FragmentSize = AI->getAllocationSizeInBits(DL))
1267 return ValueSize >= *FragmentSize;
1291 assert(DIVar &&
"Missing variable");
1300 LLVM_DEBUG(
dbgs() <<
"Failed to convert dbg.declare to dbg.value: " 1307 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1312 Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
1321 assert(DIVar &&
"Missing variable");
1330 LLVM_DEBUG(
dbgs() <<
"Failed to convert dbg.declare to dbg.value: " 1341 Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
1342 LI, DIVar, DIExpr, NewLoc, (
Instruction *)
nullptr);
1352 assert(DIVar &&
"Missing variable");
1361 LLVM_DEBUG(
dbgs() <<
"Failed to convert dbg.declare to dbg.value: " 1374 if (InsertionPt != BB->
end())
1375 Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, NewLoc, &*InsertionPt);
1396 if (
auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1402 for (
auto &
I : Dbgs) {
1416 if (
LoadInst *LI = dyn_cast<LoadInst>(U))
1417 return LI->isVolatile();
1419 return SI->isVolatile();
1426 while (!WorkList.
empty()) {
1428 for (
auto &AIUse : V->
uses()) {
1429 User *U = AIUse.getUser();
1431 if (AIUse.getOperandNo() == 1)
1433 }
else if (
LoadInst *LI = dyn_cast<LoadInst>(U)) {
1435 }
else if (
CallInst *CI = dyn_cast<CallInst>(U)) {
1439 if (!CI->isLifetimeStartOrEnd()) {
1443 DIB.insertDbgValueIntrinsic(AI, DDI->
getVariable(), DerefExpr,
1446 }
else if (
BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
1447 if (BI->getType()->isPointerTy())
1460 assert(BB &&
"No BasicBlock to clone dbg.value(s) from.");
1461 if (InsertedPHIs.
size() == 0)
1466 for (
auto &
I : *BB) {
1467 if (
auto DbgII = dyn_cast<DbgVariableIntrinsic>(&
I)) {
1468 if (
auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
1469 DbgValueMap.
insert({Loc, DbgII});
1472 if (DbgValueMap.
size() == 0)
1479 for (
auto PHI : InsertedPHIs) {
1485 for (
auto VI : PHI->operand_values()) {
1486 auto V = DbgValueMap.
find(
VI);
1487 if (V != DbgValueMap.
end()) {
1488 auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
1492 assert(InsertionPt != Parent->
end() &&
"Ill-formed basic block");
1493 NewDbgII->insertBefore(&*InsertionPt);
1516 if (
auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
1517 if (DII->isAddressOfVariable())
1551 uint8_t DIExprFlags,
int Offset) {
1555 auto *DIVar = DII->getVariable();
1556 auto *DIExpr = DII->getExpression();
1557 assert(DIVar &&
"Missing variable");
1561 Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
1562 if (DII == InsertBefore)
1566 return !DbgAddrs.empty();
1570 DIBuilder &Builder, uint8_t DIExprFlags,
1581 assert(DIVar &&
"Missing variable");
1586 if (!DIExpr || DIExpr->getNumElements() < 1 ||
1587 DIExpr->getElement(0) != dwarf::DW_OP_deref)
1595 Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
1603 for (
auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1605 if (
auto *DVI = dyn_cast<DbgValueInst>(U.
getUser()))
1618 if (DbgUsers.
empty())
1634 for (
auto *DII : DbgUsers) {
1638 bool StackValue = isa<DbgValueInst>(DII);
1658 bool WithStackValue) {
1660 auto &DL = M.getDataLayout();
1675 return doSalvage(Ops);
1681 return doSalvage(Ops);
1684 if (
auto *CI = dyn_cast<CastInst>(&I)) {
1686 if (CI->isNoopCast(DL) || isa<ZExtInst>(&
I))
1691 if (Type->
isVectorTy() || (!isa<TruncInst>(&
I) && !isa<SExtInst>(&I)))
1694 Value *FromValue = CI->getOperand(0);
1699 isa<SExtInst>(&I)));
1702 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(&I)) {
1704 M.getDataLayout().getIndexSizeInBits(
GEP->getPointerAddressSpace());
1707 if (
GEP->accumulateConstantOffset(M.getDataLayout(),
Offset)) {
1712 }
else if (
auto *BI = dyn_cast<BinaryOperator>(&I)) {
1715 if (!ConstInt || ConstInt->getBitWidth() > 64)
1719 switch (BI->getOpcode()) {
1721 return applyOffset(Val);
1722 case Instruction::Sub:
1723 return applyOffset(-int64_t(Val));
1724 case Instruction::Mul:
1725 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
1726 case Instruction::SDiv:
1727 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
1728 case Instruction::SRem:
1729 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
1730 case Instruction::Or:
1731 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
1732 case Instruction::And:
1733 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
1734 case Instruction::Xor:
1735 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
1736 case Instruction::Shl:
1737 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
1738 case Instruction::LShr:
1739 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
1740 case Instruction::AShr:
1741 return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
1769 bool Changed =
false;
1771 if (isa<Instruction>(&To)) {
1774 for (
auto *DII : Users) {
1784 }
else if (!DT.
dominates(&DomPoint, DII)) {
1785 UndefOrSalvage.
insert(DII);
1791 for (
auto *DII : Users) {
1792 if (UndefOrSalvage.
count(DII))
1806 if (!UndefOrSalvage.
empty()) {
1833 return SameSize && LosslessConversion;
1846 assert(&From != &To &&
"Can't replace something with itself");
1852 return DII.getExpression();
1866 assert(FromBits != ToBits &&
"Unexpected no-op conversion");
1870 if (FromBits < ToBits)
1895 unsigned NumDeadInst = 0;
1899 while (EndInst != &BB->
front()) {
1908 if (!isa<DbgInfoIntrinsic>(Inst))
1919 std::vector <DominatorTree::UpdateType> Updates;
1929 Successor->removePredecessor(BB, PreserveLCSSA);
1945 unsigned NumInstrsRemoved = 0;
1947 while (BBI != BBE) {
1948 if (!BBI->use_empty())
1955 return NumInstrsRemoved;
2015 UnwindEdge, InvokeArgs, OpBundles, CI->
getName(), BB);
2036 bool Changed =
false;
2044 if (
auto *CI = dyn_cast<CallInst>(&
I)) {
2047 if (
Function *F = dyn_cast<Function>(Callee)) {
2053 if (IntrinsicID == Intrinsic::assume) {
2060 }
else if (IntrinsicID == Intrinsic::experimental_guard) {
2071 if (!isa<UnreachableInst>(CI->getNextNode())) {
2078 }
else if ((isa<ConstantPointerNull>(Callee) &&
2080 isa<UndefValue>(Callee)) {
2085 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2089 if (!isa<UnreachableInst>(CI->getNextNode())) {
2096 }
else if (
auto *
SI = dyn_cast<StoreInst>(&
I)) {
2102 if (
SI->isVolatile())
continue;
2104 Value *Ptr =
SI->getOperand(1);
2106 if (isa<UndefValue>(Ptr) ||
2107 (isa<ConstantPointerNull>(Ptr) &&
2109 SI->getPointerAddressSpace()))) {
2118 if (
auto *II = dyn_cast<InvokeInst>(Terminator)) {
2121 if ((isa<ConstantPointerNull>(Callee) &&
2123 isa<UndefValue>(Callee)) {
2127 if (II->use_empty() && II->onlyReadsMemory()) {
2129 BasicBlock *NormalDestBB = II->getNormalDest();
2130 BasicBlock *UnwindDestBB = II->getUnwindDest();
2133 II->eraseFromParent();
2135 DTU->applyUpdatesPermissive(
2141 }
else if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2143 struct CatchPadDenseMapInfo {
2158 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
2159 RHS == getEmptyKey() || RHS == getTombstoneKey())
2169 detail::DenseSetEmpty Empty;
2171 E = CatchSwitch->handler_end();
2174 auto *CatchPad = cast<CatchPadInst>(HandlerBB->
getFirstNonPHI());
2175 if (!HandlerSet.insert({CatchPad, Empty}).second) {
2176 CatchSwitch->removeHandler(
I);
2188 }
while (!Worklist.
empty());
2195 if (
auto *II = dyn_cast<InvokeInst>(TI)) {
2203 if (
auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2205 UnwindDest = CRI->getUnwindDest();
2206 }
else if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2208 CatchSwitch->getParentPad(),
nullptr, CatchSwitch->getNumHandlers(),
2209 CatchSwitch->getName(), CatchSwitch);
2210 for (
BasicBlock *PadBB : CatchSwitch->handlers())
2213 NewTI = NewCatchSwitch;
2214 UnwindDest = CatchSwitch->getUnwindDest();
2241 NumRemoved += F.
size() - Reachable.
size();
2246 if (Reachable.
find(&BB) != Reachable.
end())
2248 DeadBlockSet.
insert(&BB);
2256 std::vector<DominatorTree::UpdateType> Updates;
2257 for (
auto *BB : DeadBlockSet) {
2264 BB->dropAllReferences();
2267 assert(TI &&
"Basic block should have a terminator");
2275 "applying corresponding DTU updates.");
2282 for (
auto *BB : DeadBlockSet) {
2292 for (
auto *BB : DeadBlockSet)
2293 BB->eraseFromParent();
2304 for (
const auto &MD : Metadata) {
2305 unsigned Kind = MD.first;
2313 case LLVMContext::MD_dbg:
2315 case LLVMContext::MD_tbaa:
2318 case LLVMContext::MD_alias_scope:
2321 case LLVMContext::MD_noalias:
2322 case LLVMContext::MD_mem_parallel_loop_access:
2325 case LLVMContext::MD_access_group:
2329 case LLVMContext::MD_range:
2340 case LLVMContext::MD_fpmath:
2343 case LLVMContext::MD_invariant_load:
2347 case LLVMContext::MD_nonnull:
2352 case LLVMContext::MD_invariant_group:
2355 case LLVMContext::MD_align:
2359 case LLVMContext::MD_dereferenceable:
2360 case LLVMContext::MD_dereferenceable_or_null:
2364 case LLVMContext::MD_preserve_access_index:
2375 if (
auto *JMD = J->
getMetadata(LLVMContext::MD_invariant_group))
2376 if (isa<LoadInst>(K) || isa<StoreInst>(K))
2377 K->
setMetadata(LLVMContext::MD_invariant_group, JMD);
2382 unsigned KnownIDs[] = {
2383 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2384 LLVMContext::MD_noalias, LLVMContext::MD_range,
2385 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
2386 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2387 LLVMContext::MD_dereferenceable,
2388 LLVMContext::MD_dereferenceable_or_null,
2389 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
2399 for (
const auto &MDPair : MD) {
2400 unsigned ID = MDPair.first;
2410 case LLVMContext::MD_dbg:
2411 case LLVMContext::MD_tbaa:
2412 case LLVMContext::MD_prof:
2413 case LLVMContext::MD_fpmath:
2414 case LLVMContext::MD_tbaa_struct:
2415 case LLVMContext::MD_invariant_load:
2416 case LLVMContext::MD_alias_scope:
2417 case LLVMContext::MD_noalias:
2418 case LLVMContext::MD_nontemporal:
2419 case LLVMContext::MD_mem_parallel_loop_access:
2420 case LLVMContext::MD_access_group:
2425 case LLVMContext::MD_nonnull:
2429 case LLVMContext::MD_align:
2430 case LLVMContext::MD_dereferenceable:
2431 case LLVMContext::MD_dereferenceable_or_null:
2433 if (NewType->isPointerTy())
2437 case LLVMContext::MD_range:
2455 if (!isa<LoadInst>(I))
2467 static const unsigned KnownIDs[] = {
2468 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2469 LLVMContext::MD_noalias, LLVMContext::MD_range,
2470 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2471 LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
2472 LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
2476 template <
typename RootType,
typename DominatesFn>
2478 const RootType &Root,
2479 const DominatesFn &Dominates) {
2486 if (!Dominates(Root, U))
2490 <<
"' as " << *To <<
" in " << *U <<
"\n");
2504 auto *
I = cast<Instruction>(U.
getUser());
2505 if (
I->getParent() == BB)
2525 auto ProperlyDominates = [&DT](
const BasicBlock *BB,
const Use &U) {
2526 auto *
I = cast<Instruction>(U.getUser())->
getParent();
2535 if (Call->
hasFnAttr(
"gc-leaf-function"))
2538 if (
F->hasFnAttribute(
"gc-leaf-function"))
2541 if (
auto IID =
F->getIntrinsicID())
2543 return IID != Intrinsic::experimental_gc_statepoint &&
2544 IID != Intrinsic::experimental_deoptimize;
2560 auto *NewTy = NewLI.
getType();
2563 if (NewTy->isPointerTy()) {
2570 if (!NewTy->isIntegerTy())
2575 auto *ITy = cast<IntegerType>(NewTy);
2580 MDB.createRange(NonNullInt, NullInt));
2585 auto *NewTy = NewLI.
getType();
2591 if (!NewTy->isPointerTy())
2604 for (
auto *DII : DbgUsers)
2605 DII->eraseFromParent();
2636 if (isa<DbgInfoIntrinsic>(I)) {
2654 BitPart(
Value *
P,
unsigned BW) : Provider(P) {
2655 Provenance.resize(BW);
2665 enum { Unset = -1 };
2696 auto I = BPS.find(V);
2700 auto &Result = BPS[V] =
None;
2704 if (Depth == BitPartRecursionMaxDepth) {
2705 LLVM_DEBUG(
dbgs() <<
"collectBitParts max recursion depth reached.\n");
2711 if (
I->getOpcode() == Instruction::Or) {
2713 MatchBitReversals, BPS, Depth + 1);
2715 MatchBitReversals, BPS, Depth + 1);
2720 if (!A->Provider || A->Provider != B->Provider)
2723 Result = BitPart(A->Provider, BitWidth);
2724 for (
unsigned i = 0; i < A->Provenance.size(); ++i) {
2725 if (A->Provenance[i] != BitPart::Unset &&
2726 B->Provenance[i] != BitPart::Unset &&
2727 A->Provenance[i] != B->Provenance[i])
2728 return Result =
None;
2730 if (A->Provenance[i] == BitPart::Unset)
2731 Result->Provenance[i] = B->Provenance[i];
2733 Result->Provenance[i] = A->Provenance[i];
2740 if (
I->isLogicalShift() && isa<ConstantInt>(
I->getOperand(1))) {
2742 cast<ConstantInt>(
I->getOperand(1))->getLimitedValue(~0U);
2744 if (BitShift > BitWidth)
2748 MatchBitReversals, BPS, Depth + 1);
2754 auto &
P = Result->Provenance;
2755 if (
I->getOpcode() == Instruction::Shl) {
2756 P.erase(std::prev(
P.end(), BitShift),
P.end());
2757 P.insert(
P.begin(), BitShift, BitPart::Unset);
2759 P.erase(
P.begin(), std::next(
P.begin(), BitShift));
2760 P.insert(
P.end(), BitShift, BitPart::Unset);
2768 if (
I->getOpcode() == Instruction::And &&
2769 isa<ConstantInt>(
I->getOperand(1))) {
2770 APInt Bit(
I->getType()->getPrimitiveSizeInBits(), 1);
2771 const APInt &AndMask = cast<ConstantInt>(
I->getOperand(1))->getValue();
2775 unsigned NumMaskedBits = AndMask.countPopulation();
2776 if (!MatchBitReversals && NumMaskedBits % 8 != 0)
2780 MatchBitReversals, BPS, Depth + 1);
2785 for (
unsigned i = 0; i < BitWidth; ++i,
Bit <<= 1)
2787 if ((AndMask & Bit) == 0)
2788 Result->Provenance[i] = BitPart::Unset;
2793 if (
I->getOpcode() == Instruction::ZExt) {
2795 MatchBitReversals, BPS, Depth + 1);
2799 Result = BitPart(Res->Provider, BitWidth);
2800 auto NarrowBitWidth =
2801 cast<IntegerType>(cast<ZExtInst>(
I)->getSrcTy())->
getBitWidth();
2802 for (
unsigned i = 0; i < NarrowBitWidth; ++i)
2803 Result->Provenance[i] = Res->Provenance[i];
2804 for (
unsigned i = NarrowBitWidth; i < BitWidth; ++i)
2805 Result->Provenance[i] = BitPart::Unset;
2812 Result = BitPart(V, BitWidth);
2813 for (
unsigned i = 0; i < BitWidth; ++i)
2814 Result->Provenance[i] = i;
2819 unsigned BitWidth) {
2820 if (From % 8 != To % 8)
2826 return From == BitWidth - To - 1;
2830 unsigned BitWidth) {
2831 return From == BitWidth - To - 1;
2835 Instruction *
I,
bool MatchBSwaps,
bool MatchBitReversals,
2839 if (!MatchBSwaps && !MatchBitReversals)
2846 unsigned DemandedBW = BW;
2850 DemandedTy = cast<IntegerType>(Trunc->getType());
2856 std::map<Value *, Optional<BitPart>> BPS;
2857 auto Res =
collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0);
2860 auto &BitProvenance = Res->Provenance;
2864 bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse =
true;
2865 for (
unsigned i = 0; i < DemandedBW; ++i) {
2873 if (OKForBSwap && MatchBSwaps)
2874 Intrin = Intrinsic::bswap;
2875 else if (OKForBitReverse && MatchBitReversals)
2876 Intrin = Intrinsic::bitreverse;
2880 if (ITy != DemandedTy) {
2882 Value *Provider = Res->Provider;
2883 IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2885 if (DemandedTy != ProviderTy) {
2931 case Instruction::Invoke:
2938 if (isa<IntrinsicInst>(I))
2946 case Instruction::ShuffleVector:
2949 case Instruction::Switch:
2950 case Instruction::ExtractValue:
2953 case Instruction::InsertValue:
2956 case Instruction::Alloca:
2960 return !cast<AllocaInst>(
I)->isStaticAlloca();
2961 case Instruction::GetElementPtr:
2965 for (
auto E = std::next(It, OpIdx); It !=
E; ++It)
2975 if (
AllocaInst *AI = dyn_cast<AllocaInst>(V))
2980 if (I != AllocaForValue.
end())
2984 AllocaForValue[V] =
nullptr;
2988 else if (
PHINode *PN = dyn_cast<PHINode>(V)) {
2989 for (
Value *IncValue : PN->incoming_values()) {
2995 if (IncValueAI ==
nullptr || (Res !=
nullptr && IncValueAI != Res))
3002 LLVM_DEBUG(
dbgs() <<
"Alloca search cancelled on unknown instruction: " 3006 AllocaForValue[V] = Res;
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface ...
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
Like BasicBlock::removePredecessor, this method is called when we're about to delete Pred as a predec...
class_match< UndefValue > m_Undef()
Match an arbitrary undef constant.
iterator_range< use_iterator > uses()
bool hasLocalLinkage() const
DILocation * get() const
Get the underlying DILocation.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
uint64_t getZExtValue() const
Get zero extended value.
unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, int Offset=0)
Replaces multiple llvm.dbg.value instructions when the alloca it describes is replaced with a new val...
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
This represents the llvm.dbg.label instruction.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
bool isMetadataTy() const
Return true if this is 'metadata'.
iterator erase(iterator where)
static const unsigned BitPartRecursionMaxDepth
This class represents lattice values for constants.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
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...
A Module instance is used to store all the information related to an LLVM module. ...
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ)
Return true if we can fold BB, an almost-empty BB ending in an unconditional branch to Succ...
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static MetadataAsValue * wrapValueInMetadata(LLVMContext &C, Value *V)
Wrap V in a ValueAsMetadata instance.
Implements a dense probed hash-table based set.
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
void push_back(const T &Elt)
value_op_iterator value_op_begin()
void changeToUnreachable(const Instruction *I)
Instruction I will be changed to an unreachable.
static MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
void findDbgUsers(SmallVectorImpl< DbgVariableIntrinsic *> &DbgInsts, Value *V)
Finds the debug info intrinsics describing a value.
This class represents a function call, abstracting a target machine's calling convention.
static DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII, Instruction *Src)
Produce a DebugLoc to use for each dbg.declare/inst pair that are promoted to a dbg.value.
An efficient, type-erasing, non-owning reference to a callable.
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
A cache of @llvm.assume calls within a function.
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
LLVMContext & getContext() const
All values hold a context through their type.
bool isTerminator() const
bool replaceDbgUsesWithUndef(Instruction *I)
Replace all the uses of an SSA value in .dbg intrinsics with undef.
value_op_iterator value_op_end()
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
STATISTIC(NumFunctions, "Total number of functions")
static void replaceUndefValuesInPhi(PHINode *PN, const IncomingValueMap &IncomingValues)
Replace the incoming undef values to a phi with the values from a block-to-value map.
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...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Optional< DIBasicType::Signedness > getSignedness() const
Return the signedness of this variable's type, or None if this type is neither signed nor unsigned...
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
const MDOperand & getOperand(unsigned I) const
Optional< DIExpression * > DbgValReplacement
A replacement for a dbg.value expression.
An instruction for reading from memory.
void setOperand(unsigned I, Metadata *New)
Set an operand.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isVectorTy() const
True if this is an instance of VectorType.
iv Induction Variable Users
bool exceedsNaturalStackAlignment(Align Alignment) const
Returns true if the given alignment exceeds the natural stack alignment.
static Value * selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB, IncomingValueMap &IncomingValues)
Determines the value to use as the phi node input for a block.
This defines the Use class.
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
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.
LLVMContext & getContext() const
Get the context in which this basic block lives.
static unsigned enforceKnownAlignment(Value *V, unsigned Alignment, unsigned PrefAlign, const DataLayout &DL)
enforceKnownAlignment - If the specified pointer points to an object that we control, modify the object's alignment to PrefAlign.
Optional< uint64_t > getFragmentSizeInBits() const
Get the size (in bits) of the variable, or fragment of the variable that is described.
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
block_iterator block_end()
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static 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 ...
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
The address of a basic block.
bool match(Val *V, const Pattern &P)
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
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...
bool isMathLibCallNoop(const CallBase *Call, const TargetLibraryInfo *TLI)
Check whether the given call has no side-effects.
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!)...
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
static constexpr UpdateKind Delete
This is the base class for all instructions that perform data casts.
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
A Use represents the edge between a Value definition and its users.
iterator find(ConstPtrType Ptr) const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isIntegerTy() const
True if this is an instance of IntegerType.
This file contains the simple types necessary to represent the attributes associated with functions a...
bool canSimplifyInvokeNoUnwind(const Function *F)
static const unsigned MaximumAlignment
block_iterator block_begin()
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
This file implements a class to represent arbitrary precision integral constant values and operations...
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress, DIBuilder &Builder, int Offset)
void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode *> &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
void addHandler(BasicBlock *Dest)
Add an entry to the switch instruction...
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
void findDbgValues(SmallVectorImpl< DbgValueInst *> &DbgValues, Value *V)
Finds the llvm.dbg.value intrinsics describing a value.
int64_t getSExtValue() const
Get sign extended value.
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a nonnull metadata node to a new load instruction.
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
static DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes...
This is the common base class for debug info intrinsics for variables.
void salvageDebugInfoOrMarkUndef(Instruction &I)
Salvage all debug users of the instruction I or mark it as undef if it cannot be salvaged.
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
bool has(LibFunc F) const
Tests whether a library function is available.
iterator find(const KeyT &Val)
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
This class represents a no-op cast from one type to another.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
static bool areAllUsesEqual(Instruction *I)
areAllUsesEqual - Check whether the uses of a value are all the same.
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static MDNode * intersect(MDNode *A, MDNode *B)
void dropDebugUsers(Instruction &I)
Remove the debug intrinsic instructions for the given instruction.
An instruction for storing to memory.
bool replaceDbgDeclare(Value *Address, Value *NewAddress, Instruction *InsertBefore, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces llvm.dbg.declare instruction when the address it describes is replaced with a new value...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
static void gatherIncomingValuesToPhi(PHINode *PN, IncomingValueMap &IncomingValues)
Create a map from block to value for the operands of a given phi.
static bool markAliveBlocks(Function &F, SmallPtrSetImpl< BasicBlock *> &Reachable, DomTreeUpdater *DTU=nullptr)
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
This class represents a truncation of integer types.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
MDNode * intersectAccessGroups(const Instruction *Inst1, const Instruction *Inst2)
Compute the access-group list of access groups that Inst1 and Inst2 are both in.
Interval::succ_iterator succ_end(Interval *I)
use_iterator_impl< Use > use_iterator
iterator find(const_arg_type_t< KeyT > Val)
bool doesNotAccessMemory() const
Determine if the function does not access memory.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII)
Check if the alloc size of ValTy is large enough to cover the variable (or fragment of the variable) ...
static MDNode * getMostGenericRange(MDNode *A, MDNode *B)
static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy, Type *ToTy)
Check if a bitcast between a value of type FromTy to type ToTy would losslessly preserve the bits and...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Value * getCalledValue() const
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
void push_back(EltTy NewVal)
The instances of the Type class are immutable: once they are created, they are never changed...
static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr, Instruction *I)
===---------------------------------------------------------------——===// Dbg Intrinsic utilities ...
void deleteBB(BasicBlock *DelBB)
Delete DelBB.
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
static MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Value * getAddress() const
This function has undefined behavior.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
const Instruction & front() const
FunctionType * getFunctionType() const
std::pair< iterator, bool > insert(const ValueT &V)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
DIExpression * getExpression() const
static bool CanMergeValues(Value *First, Value *Second)
Return true if we can choose one of these values to use in place of the other.
const Instruction * getNextNonDebugInstruction() const
Return a pointer to the next non-debug instruction in the same basic block as 'this', or nullptr if no such instruction exists.
AllocaInst * findAllocaForValue(Value *V, DenseMap< Value *, AllocaInst *> &AllocaForValue)
Finds alloca where the value comes from.
void splice(iterator where, iplist_impl &L2)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
const Instruction & back() const
static ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed)
Returns the ops for a zero- or sign-extension in a DIExpression.
void setCallingConv(CallingConv::ID CC)
static DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
void copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a range metadata node to a new load instruction.
Interval::pred_iterator pred_end(Interval *I)
Value * getPointerOperand()
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
static bool isStructure(AllocaInst *AI)
Determine whether this alloca is a structure.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
void applyUpdatesPermissive(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
Class to represent integer types.
DIExpression * salvageDebugInfoImpl(Instruction &I, DIExpression *DIExpr, bool StackVal)
Given an instruction I and DIExpression DIExpr operating on it, write the effects of I into the retur...
static bool rewriteDebugUsers(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT, function_ref< DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr)
Point debug users of From to To using exprs given by RewriteExpr, possibly moving/undefing users to p...
MDNode * getScope() const
bool succ_empty(const Instruction *I)
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
static MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To, unsigned BitWidth)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
bool LowerDbgDeclare(Function &F)
Lowers llvm.dbg.declare intrinsics into appropriate set of llvm.dbg.value intrinsics.
DILocation * getInlinedAt() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB, const PredBlockVector &BBPreds, PHINode *PN)
Replace a value flowing from a block to a phi with potentially multiple instances of that value flowi...
bool recursivelySimplifyInstruction(Instruction *I, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
Recursively attempt to simplify an instruction.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
BasicBlock * getNormalDest() const
const InstListType & getInstList() const
Return the underlying instruction list container.
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
base_list_type::iterator iterator
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
void changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoek into a normall call.
This is the shared class of boolean and integer constants.
TinyPtrVector< DbgVariableIntrinsic * > FindDbgAddrUses(Value *V)
Finds all intrinsics declaring local variables as living in the memory that 'V' points to...
BlockVerifier::State From
Align max(MaybeAlign Lhs, Align Rhs)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static unsigned replaceDominatedUsesWith(Value *From, Value *To, const RootType &Root, const DominatesFn &Dominates)
static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To, unsigned BitWidth)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
bool callsGCLeafFunction(const CallBase *Call, const TargetLibraryInfo &TLI)
Return true if this call calls a gc leaf function.
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Provides information about what library functions are available for the current target.
bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
LLVM_NODISCARD T pop_back_val()
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
bool hasOptimizedCodeGen(LibFunc F) const
Tests if the function is both available and a candidate for optimized code generation.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than it's terminator and any present EH pad instruct...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AttributeList getAttributes() const
Return the parameter attributes for this call.
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
Get all metadata attached to this Instruction.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
bool isUsedByMetadata() const
Return true if there is metadata referencing this value.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
This file contains constants used for implementing Dwarf debug support.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
void removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
amdgpu Simplify well known AMD library false FunctionCallee Callee
iterator_range< user_iterator > users()
InstListType::iterator iterator
Instruction iterators...
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
bool isNonIntegralPointerType(PointerType *PT) const
bool isBundleOperand(Value::const_user_iterator UI) const
Determine whether the passed iterator points to a bundle operand.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Value * getVariableLocation(bool AllowNullOp=true) const
Get the location corresponding to the variable referenced by the debug info intrinsic.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
void recalculate(Function &F)
Notify DTU that the entry block was replaced.
static bool simplifyAndDCEInstruction(Instruction *I, SmallSetVector< Instruction *, 16 > &WorkList, const DataLayout &DL, const TargetLibraryInfo *TLI)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
CallInst * createCallMatchingInvoke(InvokeInst *II)
Create a call that matches the invoke II in terms of arguments, attributes, debug information...
static IntegerType * getInt32Ty(LLVMContext &C)
LLVM_NODISCARD bool empty() const
This represents the llvm.dbg.value instruction.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
static DIExpression * appendExt(const DIExpression *Expr, unsigned FromSize, unsigned ToSize, bool Signed)
Append a zero- or sign-extension to Expr.
bool isAddressOfVariable() const
Does this describe the address of a local variable.
bool isTokenTy() const
Return true if this is 'token'.
CallingConv::ID getCallingConv() const
StringRef getName() const
Return a constant reference to the value's name.
Establish a view to a call site for examination.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
const Function * getParent() const
Return the enclosing method, or null if none.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
user_iterator_impl< User > user_iterator
void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc...
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void destroyConstant()
Called if some element of this constant is no longer valid.
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...
bool isBBPendingDeletion(BasicBlock *DelBB) const
Returns true if DelBB is awaiting deletion.
DILocalVariable * getVariable() const
static bool PhiHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr, PHINode *APN)
See if there is a dbg.value intrinsic for DIVar for the PHI node.
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
TypeSize getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
static bool isArray(AllocaInst *AI)
Determine whether this alloca is either a VLA or an array.
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces llvm.dbg.declare instruction when the alloca it describes is replaced with a new value...
void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void removeBlocks(const SmallSetVector< BasicBlock *, 8 > &DeadBlocks)
Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
user_iterator user_begin()
const BasicBlock & front() const
static const Optional< BitPart > & collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals, std::map< Value *, Optional< BitPart >> &BPS, int Depth)
Analyze the specified subexpression and see if it is capable of providing pieces of a bswap or bitrev...
BasicBlock * getUnwindDest() const
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
succ_range successors(Instruction *I)
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, Instruction *InsertBefore=nullptr)
static const Function * getParent(const Value *V)
void ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII, StoreInst *SI, DIBuilder &Builder)
===---------------------------------------------------------------——===// Dbg Intrinsic utilities ...
BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
bool wouldInstructionBeTriviallyDead(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...
void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
bool hasOneUse() const
Return true if there is exactly one user of this value.
bool hasDomTree() const
Returns true if it holds a DominatorTree.
bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction *> &InsertedInsts)
Try to match a bswap or bitreverse idiom.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
void setIncomingValue(unsigned i, Value *V)
unsigned getNumOperands() const
Return number of MDNode operands.
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
static MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
This represents the llvm.dbg.declare instruction.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, 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...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
bool isStructTy() const
True if this is an instance of StructType.
bool isArrayTy() const
True if this is an instance of ArrayType.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
gep_type_iterator gep_type_begin(const User *GEP)
bool salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableIntrinsic *> Insns)
Implementation of salvageDebugInfo, applying only to instructions in Insns, rather than all debug use...