74#define DEBUG_TYPE "globalopt"
76STATISTIC(NumMarked ,
"Number of globals marked constant");
77STATISTIC(NumUnnamed ,
"Number of globals marked unnamed_addr");
78STATISTIC(NumSRA ,
"Number of aggregate globals broken into scalars");
79STATISTIC(NumSubstitute,
"Number of globals with initializers stored into them");
81STATISTIC(NumGlobUses ,
"Number of global uses devirtualized");
82STATISTIC(NumLocalized ,
"Number of globals localized");
83STATISTIC(NumShrunkToBool ,
"Number of global vars shrunk to booleans");
84STATISTIC(NumFastCallFns ,
"Number of functions converted to fastcc");
85STATISTIC(NumCtorsEvaluated,
"Number of static ctors evaluated");
86STATISTIC(NumNestRemoved ,
"Number of nest attributes removed");
87STATISTIC(NumAliasesResolved,
"Number of global aliases resolved");
88STATISTIC(NumAliasesRemoved,
"Number of global aliases eliminated");
89STATISTIC(NumCXXDtorsRemoved,
"Number of global C++ destructors removed");
90STATISTIC(NumAtExitRemoved,
"Number of atexit handlers removed");
91STATISTIC(NumInternalFunc,
"Number of internal functions");
92STATISTIC(NumColdCC,
"Number of functions marked coldcc");
93STATISTIC(NumIFuncsResolved,
"Number of statically resolved IFuncs");
94STATISTIC(NumIFuncsDeleted,
"Number of IFuncs removed");
115 Type *Ty = Types.pop_back_val();
116 switch (Ty->getTypeID()) {
135 Types.push_back(InnerTy);
140 if (--Limit == 0)
return true;
141 }
while (!Types.empty());
161 if (
I->mayHaveSideEffects())
164 if (!
GEP->hasAllConstantIndices())
166 }
else if (
I->getNumOperands() != 1) {
170 V =
I->getOperand(0);
195 while (!Worklist.
empty()) {
201 SI->eraseFromParent();
204 Dead.push_back(std::make_pair(
I,
SI));
209 MSI->eraseFromParent();
212 Dead.push_back(std::make_pair(
I, MSI));
218 MTI->eraseFromParent();
221 Dead.push_back(std::make_pair(
I, MTI));
231 Store->eraseFromParent();
239 I->eraseFromParent();
242 I->eraseFromParent();
266 I->eraseFromParent();
269 while (!WorkList.
empty()) {
271 if (!Visited.
insert(U).second)
283 Type *Ty = LI->getType();
285 LI->replaceAllUsesWith(Res);
290 Value *PtrOp = LI->getPointerOperand();
295 if (
II->getIntrinsicID() == Intrinsic::threadlocal_address)
296 PtrOp =
II->getArgOperand(0);
300 LI->replaceAllUsesWith(
Value);
311 if (
II->getIntrinsicID() == Intrinsic::threadlocal_address)
337 auto AppendUses = [&](
Value *
V) {
338 for (
Use &U :
V->uses())
339 if (Visited.
insert(&U).second)
343 while (!Worklist.
empty()) {
345 User *
V = U->getUser();
349 (
GEP &&
GEP->hasAllConstantIndices())) {
361 Ptr = Ptr->stripAndAccumulateConstantOffsets(
DL,
Offset,
363 if (Ptr != GV ||
Offset.getActiveBits() >= 64)
369 const auto &[It, Inserted] =
371 if (Ty != It->second.Ty)
375 It->second.Initializer =
377 if (!It->second.Initializer) {
378 LLVM_DEBUG(
dbgs() <<
"Global SRA: Failed to evaluate initializer of "
379 << *GV <<
" with type " << *Ty <<
" at offset "
380 <<
Offset.getZExtValue());
386 if (Ty->isScalableTy())
399 return Initializer != StoredConst;
403 It->second.IsStored |= IsStored(
V, It->second.Initializer);
428 for (
auto *GVE : GVs) {
431 int64_t CurVarOffsetInBytes = 0;
433 uint64_t FragmentEndInBits = FragmentOffsetInBits + FragmentSizeInBits;
440 if (CurVarOffsetInBytes < 0)
444 CurVarOffsetInBits = CHAR_BIT * (
uint64_t)CurVarOffsetInBytes;
447 if (CurVarOffsetInBits >= FragmentEndInBits)
451 uint64_t CurVarEndInBits = CurVarOffsetInBits + CurVarSize;
453 if (CurVarSize != 0 &&
454 CurVarEndInBits <= FragmentOffsetInBits)
459 if (CurVarSize != 0 &&
460 CurVarOffsetInBits >= FragmentOffsetInBits &&
461 CurVarEndInBits <= FragmentEndInBits) {
463 (CurVarOffsetInBits - FragmentOffsetInBits) / 8;
464 if (CurVarOffsetInFragment != 0)
466 CurVarOffsetInFragment});
476 if (FragmentSizeInBits < VarSize) {
477 if (CurVarOffsetInBits > FragmentOffsetInBits)
479 uint64_t CurVarFragmentOffsetInBits =
480 FragmentOffsetInBits - CurVarOffsetInBits;
481 uint64_t CurVarFragmentSizeInBits = FragmentSizeInBits;
482 if (CurVarSize != 0 && CurVarEndInBits < FragmentEndInBits)
483 CurVarFragmentSizeInBits -= (FragmentEndInBits - CurVarEndInBits);
484 if (CurVarOffsetInBits)
487 Expr, CurVarFragmentOffsetInBits, CurVarFragmentSizeInBits))
518 return Pair.second.IsLoaded && Pair.second.IsStored;
525 for (
const auto &Pair : Parts) {
527 {Pair.first, Pair.second.Ty, Pair.second.Initializer});
533 for (
const auto &[OffsetForTy, Ty,
_] : TypesVector) {
538 Offset = OffsetForTy +
DL.getTypeAllocSize(Ty);
545 LLVM_DEBUG(
dbgs() <<
"PERFORMING GLOBAL SRA ON: " << *GV <<
"\n");
548 Align StartAlignment =
554 unsigned NameSuffix = 0;
555 for (
auto &[OffsetForTy, Ty, Initializer] : TypesVector) {
558 Initializer, GV->
getName() +
"." +
Twine(NameSuffix++), GV,
562 NewGlobals.
insert({OffsetForTy, NGV});
573 DL.getTypeAllocSizeInBits(Ty), VarSize);
580 auto AppendUsers = [&](
Value *
V) {
581 for (
User *U :
V->users())
582 if (Visited.
insert(U).second)
586 while (!Worklist.
empty()) {
598 Ptr = Ptr->stripAndAccumulateConstantOffsets(
DL,
Offset,
600 assert(Ptr == GV &&
"Load/store must be from/to global");
602 assert(NGV &&
"Must have replacement global for this offset");
610 LI->setOperand(0, NGV);
611 LI->setAlignment(NewAlign);
614 SI->setOperand(1, NGV);
615 SI->setAlignment(NewAlign);
621 "Other users can only be dead constants");
631 return NewGlobals.
begin()->second;
644 LI->setOperand(0, NewV);
647 if (
SI->getOperand(1) ==
V) {
648 SI->setOperand(1, NewV);
658 for (
unsigned i = 0, e = CB->
arg_size(); i != e; ++i)
665 if (CI->use_empty()) {
667 CI->eraseFromParent();
672 Idxs.
reserve(GEPI->getNumOperands()-1);
679 if (Idxs.
size() == GEPI->getNumOperands() - 1) {
681 V->getDataLayout(), GEPI->getSourceElementType(), NewV, Idxs))
684 if (GEPI->use_empty()) {
686 GEPI->eraseFromParent();
704 bool AllNonStoreUsesGone =
true;
711 if (LI->use_empty()) {
712 LI->eraseFromParent();
715 AllNonStoreUsesGone =
false;
719 assert(GlobalUser->getOperand(1) == GV &&
720 "Must be storing *to* the global");
722 AllNonStoreUsesGone =
false;
727 LLVM_DEBUG(
dbgs() <<
"OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV
734 if (AllNonStoreUsesGone) {
816 "No reason to shrink to bool!");
823 bool IsOneZero =
false;
824 bool EmitOneOrZero =
true;
826 if (CI && CI->getValue().getActiveBits() <= 64) {
830 if (CIInit && CIInit->getValue().getActiveBits() <= 64) {
831 uint64_t ValInit = CIInit->getZExtValue();
832 uint64_t ValOther = CI->getZExtValue();
833 uint64_t ValMinus = ValOther - ValInit;
835 for(
auto *GVe : GVs){
850 dwarf::DW_OP_deref_size, SizeInOctets,
851 dwarf::DW_OP_constu, ValMinus,
852 dwarf::DW_OP_mul, dwarf::DW_OP_constu, ValInit,
854 bool WithStackValue =
true;
860 EmitOneOrZero =
false;
875 bool StoringOther =
SI->getOperand(0) == OtherVal;
878 if (StoringOther ||
SI->getOperand(0) == InitVal) {
891 assert(LI->getOperand(0) == GV &&
"Not a copy!");
895 false,
Align(1), LI->getOrdering(),
896 LI->getSyncScopeID(), LI->getIterator());
900 "This is not a form that we understand!");
907 SI->getSyncScopeID(),
SI->getIterator());
954 Dead = (
F->isDeclaration() &&
F->use_empty()) ||
F->isDefTriviallyDead();
962 if (DeleteFnCallback)
963 DeleteFnCallback(*
F);
987 for (
auto *U : GV->
users()) {
991 assert(
I->getParent()->getParent() ==
F);
1005 auto &DT = LookupDomTree(*
const_cast<Function *
>(
F));
1016 const unsigned Threshold = 100;
1017 if (Loads.
size() * Stores.
size() > Threshold)
1020 for (
auto *L : Loads) {
1021 auto *LTy = L->getType();
1027 return DT.dominates(S, L) &&
1028 DL.getTypeStoreSize(LTy).getFixedValue() <=
1029 DL.getTypeStoreSize(STy).getFixedValue();
1053 if (LI->getFunction() ==
F &&
1054 LI->getType() == StoredOnceValue->
getType() && LI->isSimple())
1059 bool MadeChange =
false;
1060 if (!Loads.
empty()) {
1061 auto &DT = LookupDomTree(*
const_cast<Function *
>(
F));
1062 for (
auto *LI : Loads) {
1063 if (DT.dominates(StoredOnceStore, LI)) {
1064 LI->replaceAllUsesWith(
const_cast<Value *
>(StoredOnceValue));
1065 LI->eraseFromParent();
1088 if (!GS.HasMultipleAccessingFunctions &&
1089 GS.AccessingFunction &&
1093 GS.AccessingFunction->doesNotRecurse() &&
1100 GS.AccessingFunction->getEntryBlock().begin().getNonConst();
1104 nullptr, GV->
getName(), FirstI);
1162 LLVM_DEBUG(
dbgs() <<
" *** Marking constant allowed us to simplify "
1163 <<
"all users and delete global!\n");
1177 Value *StoredOnceValue = GS.getStoredOnceValue();
1180 const_cast<Function &
>(*GS.StoredOnceStore->getFunction());
1181 bool CanHaveNonUndefGlobalInitializer =
1182 GetTTI(StoreFn).canHaveNonUndefGlobalInitializerInAddressSpace(
1193 DL.getTypeAllocSize(SOVConstant->getType()).getFixedValue() ==
1195 CanHaveNonUndefGlobalInitializer) {
1206 NGV->copyAttributesFrom(GV);
1216 LLVM_DEBUG(
dbgs() <<
" *** Substituting initializer allowed us to "
1217 <<
"simplify all users and delete global!\n");
1232 if (GS.NumStores == 1)
1240 CanHaveNonUndefGlobalInitializer)) {
1291 if (GVar->isConstant() || !GVar->hasInitializer())
1300 for (
User *U :
F->users())
1302 if (
Call->getCalledOperand() ==
F)
1309 if (Attrs.hasAttrSomewhere(
A, &AttrIndex))
1310 return Attrs.removeAttributeAtIndex(
C, AttrIndex,
A);
1315 F->setAttributes(
StripAttr(
F->getContext(),
F->getAttributes(),
A));
1316 for (
User *U :
F->users()) {
1333 if (!
F->canChangeSignature())
1343 for (
User *U :
F->users()) {
1353 if (BB.getTerminatingMustTailCall())
1356 return !
F->hasAddressTaken();
1365 return Res.first->second;
1374 auto CallSiteFreq = CallerBFI.
getBlockFreq(CallSiteBB);
1375 auto CallerEntryFreq =
1377 return CallSiteFreq < CallerEntryFreq * ColdProb;
1392 for (
User *U :
F.users()) {
1400 if (!HasOnlyColdCalls(*CallerFunc))
1407 for (
User *U :
F->users())
1409 if (
Call->getCalledOperand() ==
F)
1424 if (CI->isInlineAsm())
1426 Function *CalledFn = CI->getCalledFunction();
1450 for (
User *U :
F->users()) {
1459 for (
User *U :
F->users())
1468 auto *M =
F->getParent();
1476 !CB->isMustTailCall() &&
1477 "Shouldn't call RemotePreallocated() on a musttail preallocated call");
1480 CB->getOperandBundlesAsDefs(OpBundles);
1481 CallBase *PreallocatedSetup =
nullptr;
1482 for (
auto *It = OpBundles.
begin(); It != OpBundles.
end(); ++It) {
1483 if (It->getTag() ==
"preallocated") {
1485 OpBundles.
erase(It);
1489 assert(PreallocatedSetup &&
"Did not find preallocated bundle");
1494 "Unknown indirect call type");
1496 CB->replaceAllUsesWith(NewCB);
1498 CB->eraseFromParent();
1500 Builder.SetInsertPoint(PreallocatedSetup);
1501 auto *StackSave = Builder.CreateStackSave();
1503 Builder.CreateStackRestore(StackSave);
1514 for (
auto *
User : PreallocatedArgs) {
1516 assert(UseCall->getCalledFunction()->getIntrinsicID() ==
1517 Intrinsic::call_preallocated_arg &&
1518 "preallocated token use was not a llvm.call.preallocated.arg");
1521 Value *AllocaReplacement = ArgAllocas[AllocArgIndex];
1522 if (!AllocaReplacement) {
1523 auto AddressSpace = UseCall->getType()->getPointerAddressSpace();
1525 UseCall->getFnAttr(Attribute::Preallocated).getValueAsType();
1526 auto *InsertBefore = PreallocatedSetup->
getNextNode();
1527 Builder.SetInsertPoint(InsertBefore);
1529 Builder.CreateAlloca(ArgType,
AddressSpace,
nullptr,
"paarg");
1530 ArgAllocas[AllocArgIndex] = Alloca;
1531 AllocaReplacement = Alloca;
1534 UseCall->replaceAllUsesWith(AllocaReplacement);
1535 UseCall->eraseFromParent();
1546 if (!
F.hasExactDefinition())
1551 for (
unsigned ArgNo = 0; ArgNo <
F.arg_size(); ++ArgNo) {
1552 if (!
F.getArg(ArgNo)->getType()->isIntegerTy())
1563 if (IntArgWithoutExtAttr.
empty())
1567 for (
Use &U :
F.uses()) {
1569 if (!CB || !CB->isCallee(&U) ||
1570 CB->getFunctionType() !=
F.getFunctionType())
1573 for (
unsigned ArgNo : IntArgWithoutExtAttr) {
1574 if (CB->paramHasAttr(ArgNo, Attribute::ZExt)) {
1575 CB->removeParamAttr(ArgNo, Attribute::ZExt);
1578 if (CB->paramHasAttr(ArgNo, Attribute::SExt)) {
1579 CB->removeParamAttr(ArgNo, Attribute::SExt);
1604 auto HasOnlyColdCalls = [&](
Function &Caller) {
1605 auto Res = AllCallsColdCache.
try_emplace(&Caller,
false);
1609 return Res.first->second;
1616 if (
F.hasFnAttribute(Attribute::Naked))
1620 if (!
F.hasName() && !
F.isDeclaration() && !
F.hasLocalLinkage())
1623 if (
deleteIfDead(
F, NotDiscardableComdats, DeleteFnCallback)) {
1637 if (!
F.isDeclaration()) {
1640 ChangedCFGCallback(
F);
1648 if (!
F.hasLocalLinkage())
1652 if (!
F.isDefinitionExact())
1660 if (
F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) &&
1668 if (
F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) {
1684 if (Opts.enable_coldcc_stress_test ||
1685 (
TTI.useColdCCForColdCall(
F) &&
1687 ChangeableCCCache.
erase(&
F);
1700 if (
TTI.useFastCCForInternalCall(
F)) {
1708 if (
F.getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1709 !
F.hasAddressTaken()) {
1732 if (GV.hasInitializer()) {
1733 const Constant *
C = GV.getInitializer();
1734 auto &
DL = M.getDataLayout();
1740 GV.setInitializer(New);
1759 if (
F->isDeclaration())
1768 ++NumCtorsEvaluated;
1773 <<
F->getName() <<
"' to " << NewInitializers.size()
1775 for (
const auto &Pair : NewInitializers)
1776 Pair.first->setInitializer(Pair.second);
1778 GV->setConstant(
true);
1793 V.eraseFromParent();
1798 const Type *UsedArrayType =
V.getValueType();
1817 V.removeFromParent();
1823 NV->setSection(
"llvm.metadata");
1831 SmallPtrSet<GlobalValue *, 4> Used;
1832 SmallPtrSet<GlobalValue *, 4> CompilerUsed;
1833 GlobalVariable *UsedV;
1834 GlobalVariable *CompilerUsedV;
1846 using iterator = SmallPtrSet<GlobalValue *, 4>::iterator;
1847 using used_iterator_range = iterator_range<iterator>;
1849 iterator usedBegin() {
return Used.begin(); }
1850 iterator usedEnd() {
return Used.end(); }
1852 used_iterator_range
used() {
1853 return used_iterator_range(usedBegin(), usedEnd());
1856 iterator compilerUsedBegin() {
return CompilerUsed.begin(); }
1857 iterator compilerUsedEnd() {
return CompilerUsed.end(); }
1859 used_iterator_range compilerUsed() {
1860 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
1863 bool usedCount(GlobalValue *GV)
const {
return Used.count(GV); }
1865 bool compilerUsedCount(GlobalValue *GV)
const {
1866 return CompilerUsed.count(GV);
1869 bool usedErase(GlobalValue *GV) {
return Used.erase(GV); }
1870 bool compilerUsedErase(GlobalValue *GV) {
return CompilerUsed.erase(GV); }
1871 bool usedInsert(GlobalValue *GV) {
return Used.insert(GV).second; }
1873 bool compilerUsedInsert(GlobalValue *GV) {
1874 return CompilerUsed.insert(GV).second;
1877 void syncVariablesAndSets() {
1891 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
1892 "We should have removed the duplicated "
1893 "element from llvm.compiler.used");
1900 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
1907 return U.usedCount(&GV) || U.compilerUsedCount(&GV);
1911 bool &RenameTarget) {
1915 RenameTarget =
false;
1936 RenameTarget =
true;
1947 Used.compilerUsedErase(GV);
1958 if (!J.hasName() && !J.isDeclaration() && !J.hasLocalLinkage())
1967 if (!IsModuleLocal(J))
1970 Constant *Aliasee = J.getAliasee();
1981 Target->removeDeadConstantUsers();
1988 J.replaceAllUsesWith(Aliasee);
1989 ++NumAliasesResolved;
1995 Target->setLinkage(J.getLinkage());
1996 Target->setDSOLocal(J.isDSOLocal());
1997 Target->setVisibility(J.getVisibility());
1998 Target->setDLLStorageClass(J.getDLLStorageClass());
2000 if (Used.usedErase(&J))
2003 if (Used.compilerUsedErase(&J))
2004 Used.compilerUsedInsert(
Target);
2010 ++NumAliasesRemoved;
2014 Used.syncVariablesAndSets();
2024 auto FuncIter = M.
begin();
2025 if (FuncIter == M.end())
2027 auto *
TLI = &GetTLI(*FuncIter);
2029 if (!
TLI->has(Func))
2040 if (
TLI->getLibFunc(*Fn) != Func)
2101 ++NumCXXDtorsRemoved;
2145 if (!IF.use_empty() &&
2146 (!Callee->isDeclaration() ||
2147 none_of(IF.users(), [](
User *U) { return isa<GlobalAlias>(U); }))) {
2148 IF.replaceAllUsesWith(Callee);
2149 NumIFuncsResolved++;
2174 if (!GetTTI(*F).isMultiversionedFunction(*
F))
2183 for (
unsigned I = 0,
E = Phi->getNumIncomingValues();
I !=
E; ++
I)
2231 LLVM_DEBUG(
dbgs() <<
"Examining IFUNC " << IF.getName() <<
"\n");
2233 if (IF.isInterposable())
2253 if (Versions.
empty())
2258 auto [FeatIt, FeatInserted] = FeatureMask.
try_emplace(
V);
2260 FeatIt->second = GetTTI(*V).getFeatureMask(*
V);
2261 auto [PriorIt, PriorInserted] = PriorityMask.
try_emplace(
V);
2263 PriorIt->second = GetTTI(*V).getPriorityMask(*
V);
2268 return PriorityMask[
LHS].ugt(PriorityMask[
RHS]);
2272 VersionedFuncs.
try_emplace(&IF, std::move(Versions));
2283 if (CB->getCalledOperand() == CalleeIF) {
2284 Function *Caller = CB->getFunction();
2287 bool CallerIsFMV =
TTI.isMultiversionedFunction(*Caller);
2289 if (
auto It = VersionOf.
find(Caller); It != VersionOf.
end())
2290 CallerIF = It->second;
2291 else if (!CallerIsFMV && Opts.optimize_non_fmv_callers) {
2293 auto [It, Inserted] = FeatureMask.
try_emplace(Caller);
2295 It->second =
TTI.getFeatureMask(*Caller);
2299 auto [It, Inserted] = CallSites.
try_emplace(Caller);
2302 CallerIFuncs.
insert(CallerIF);
2306 It->second.push_back(CB);
2311 if (CallSites.
empty())
2315 << CalleeIF->getResolverFunction()->getName() <<
"\n");
2323 bool AllowExpensiveChecks = CallerIsFMV &&
2324 Callers.
size() <= Opts.max_ifunc_versions &&
2325 Callees.
size() <= Opts.max_ifunc_versions;
2329 for (
unsigned I = 0,
E = Callers.
size();
I <
E; ++
I) {
2331 if (J == Callees.
size())
2335 APInt CallerBits = FeatureMask[Caller];
2342 auto eliminateAvailableFeatures = [&](
unsigned BestCandidate) {
2344 while (
K <
I && BestCandidate < Callees.
size()) {
2345 APInt MissingBits = FeatureMask[Callers[
K]] & ~CallerBits;
2346 if (MissingBits.
isSubsetOf(FeatureMask[Callees[BestCandidate]])) {
2353 return BestCandidate;
2356 unsigned BestCandidate =
2357 AllowExpensiveChecks ? eliminateAvailableFeatures(J) : J;
2359 if (BestCandidate == Callees.
size())
2363 << (CallerIsFMV ?
"FMV" :
"regular") <<
" caller "
2364 << Caller->getName() <<
"\n");
2366 Function *Callee = Callees[BestCandidate];
2367 APInt CalleeBits = FeatureMask[Callee];
2374 if (
auto It = CallSites.
find(Caller); It != CallSites.
end()) {
2377 <<
" -> " << Callee->getName() <<
"\n");
2392 while (CallerBits.
isSubsetOf(FeatureMask[Callees[J]]) &&
2393 ++J < Callees.
size())
2398 auto &Callees = VersionedFuncs[CalleeIF];
2401 if (Opts.optimize_non_fmv_callers)
2402 staticallyResolveCalls(NonFMVCallers, Callees,
false);
2406 auto &Callers = VersionedFuncs[CallerIF];
2407 staticallyResolveCalls(Callers, Callees,
true);
2410 if (CalleeIF->use_empty() ||
2411 all_of(CalleeIF->users(), [](
User *U) { return isa<GlobalAlias>(U); }))
2412 NumIFuncsResolved++;
2427 bool LocalChange =
true;
2428 std::optional<uint32_t> FirstNotFullyEvaluatedPriority;
2430 while (LocalChange) {
2431 LocalChange =
false;
2433 NotDiscardableComdats.
clear();
2437 NotDiscardableComdats.
insert(
C);
2439 if (
const Comdat *
C =
F.getComdat())
2440 if (!
F.isDefTriviallyDead())
2441 NotDiscardableComdats.
insert(
C);
2443 if (
const Comdat *
C = GA.getComdat())
2444 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
2445 NotDiscardableComdats.
insert(
C);
2449 NotDiscardableComdats, ChangedCFGCallback,
2455 if (FirstNotFullyEvaluatedPriority &&
2456 *FirstNotFullyEvaluatedPriority != Priority)
2460 FirstNotFullyEvaluatedPriority = Priority;
2499 auto &
DL = M.getDataLayout();
2521 ChangedCFGCallback, DeleteFnCallback))
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
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 contains constants used for implementing Dwarf debug support.
static bool isValidCandidateForColdCC(const IPOOptions &Opts, Function &F, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, function_ref< bool(Function &)> HasOnlyColdCalls)
static Function * FindAtExitLibFunc(Module &M, function_ref< TargetLibraryInfo &(Function &)> GetTLI, LibFunc Func)
static Function * hasSideeffectFreeStaticResolution(GlobalIFunc &IF)
static bool processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
Evaluate static constructors in the function, if we can.
static bool OptimizeStaticIFuncs(Module &M)
Find IFuncs that have resolvers that always point at the same statically known callee,...
static bool hasChangeableCCImpl(Function *F)
Return true if this is a calling convention that we'd like to change.
static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV, const DataLayout &DL)
The specified global has only one non-null value stored into it.
static bool collectVersions(Value *V, SmallVectorImpl< Function * > &Versions, function_ref< TargetTransformInfo &(Function &)> GetTTI)
static bool IsEmptyAtExitFunction(const Function &Fn)
Returns whether the given function is an empty C++ destructor or atexit handler and can therefore be ...
static bool collectSRATypes(DenseMap< uint64_t, GlobalPart > &Parts, GlobalVariable *GV, const DataLayout &DL)
Look at all uses of the global and determine which (offset, type) pairs it can be split into.
static bool DeleteDeadIFuncs(Module &M, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats)
static bool hasOnlyColdCalls(const IPOOptions &Opts, Function &F, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, ChangeableCCCacheTy &ChangeableCCCache)
static void RemoveAttribute(Function *F, Attribute::AttrKind A)
static bool hasChangeableCC(Function *F, ChangeableCCCacheTy &ChangeableCCCache)
static bool deleteIfDead(GlobalValue &GV, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats, function_ref< void(Function &)> DeleteFnCallback=nullptr)
static void RemovePreallocated(Function *F)
static bool isColdCallSite(const IPOOptions &Opts, CallBase &CB, BlockFrequencyInfo &CallerBFI)
Return true if the block containing the call site has a BlockFrequency of less than -coldcc-rel-freq ...
static void transferSRADebugInfo(GlobalVariable *GV, GlobalVariable *NGV, uint64_t FragmentOffsetInBits, uint64_t FragmentSizeInBits, uint64_t VarSize)
Copy over the debug info for a variable to its SRA replacements.
static bool OptimizeGlobalAliases(Module &M, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats)
static bool OptimizeGlobalVars(Module &M, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< DominatorTree &(Function &)> LookupDomTree, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats)
static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal)
At this point, we have learned that the only two values ever stored into GV are its initializer and O...
static bool processGlobal(GlobalValue &GV, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
static void ChangeCalleesToFastCall(Function *F)
Walk all of the direct calls of the specified function, changing them to FastCC.
static bool hasMustTailCallers(Function *F)
static bool IsSafeComputationToRemove(Value *V)
Given a value that is stored to a global but never read, determine whether it's safe to remove the st...
static bool OptimizeNonTrivialIFuncs(Module &M, function_ref< TargetTransformInfo &(Function &)> GetTTI)
static bool OptimizeEmptyGlobalAtExitDtors(Function *CXAAtExitFn, bool isCXX)
static bool mayHaveOtherReferences(GlobalValue &GV, const LLVMUsed &U)
static void changeCallSitesToColdCC(Function *F)
static AttributeList StripAttr(LLVMContext &C, AttributeList Attrs, Attribute::AttrKind A)
static bool hasInvokeCallers(Function *F)
static bool OptimizeAwayTrappingUsesOfValue(Instruction *V, Constant *NewV)
static void setUsedInitializer(GlobalVariable &V, const SmallPtrSetImpl< GlobalValue * > &Init)
static bool optimizeGlobalsInModule(Module &M, const DataLayout &DL, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, function_ref< DominatorTree &(Function &)> LookupDomTree, function_ref< void(Function &F)> ChangedCFGCallback, function_ref< void(Function &F)> DeleteFnCallback)
static bool removeUnnecessaryCallSiteExtends(Function &F)
zeroext/signext argument attributes that are present at the call-site, but not at the (exact) definit...
static bool CleanupConstantGlobalUsers(GlobalVariable *GV, const DataLayout &DL)
We just marked GV constant.
SmallDenseMap< Function *, bool, 8 > ChangeableCCCacheTy
static bool CleanupPointerRootUsers(GlobalVariable *GV)
This GV is a pointer root.
static bool OptimizeFunctions(Module &M, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, function_ref< DominatorTree &(Function &)> LookupDomTree, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats, function_ref< void(Function &F)> ChangedCFGCallback, function_ref< void(Function &F)> DeleteFnCallback)
static bool isLeakCheckerRoot(GlobalVariable *GV)
Is this global variable possibly used by a leak checker as a root?
static bool forwardStoredOnceStore(GlobalVariable *GV, const StoreInst *StoredOnceStore, function_ref< DominatorTree &(Function &)> LookupDomTree)
static int compareNames(Constant *const *A, Constant *const *B)
static bool isPointerValueDeadOnEntryToFunction(const Function *F, GlobalValue *GV, function_ref< DominatorTree &(Function &)> LookupDomTree)
static bool optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, const DataLayout &DL)
static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U, bool &RenameTarget)
static GlobalVariable * SRAGlobal(GlobalVariable *GV, const DataLayout &DL)
Perform scalar replacement of aggregates on the specified global variable.
static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U)
Module.h This file contains the declarations for the Module class.
This defines the Use class.
iv Induction Variable Users
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
This file contains the declarations for profiling metadata utility functions.
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)
Class for arbitrary precision integers.
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
This class holds the attributes for a particular argument, parameter, function, or return value.
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
LLVM Basic Block Representation.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Represents analyses that only rely on functions' control flow.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
static LLVM_ABI CallBase * Create(CallBase *CB, ArrayRef< OperandBundleDef > Bundles, InsertPosition InsertPt=nullptr)
Create a clone of CB with a different set of operand bundles and insert it before InsertPt.
void setCalledOperand(Value *V)
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
This class represents a function call, abstracting a target machine's calling convention.
bool isMustTailCall() const
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A constant value that is initialized with an expression using other constant values.
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
const Constant * stripPointerCasts() const
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool extractIfOffset(int64_t &Offset) const
If this is a constant offset, extract it.
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static LLVM_ABI 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.
A pair of DIGlobalVariable and DIExpression.
uint64_t getSizeInBits() const
Base class for variables.
A parsed version of the target data layout string in and methods for querying it.
static DebugLoc getCompilerGenerated()
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Implements a dense probed hash-table based set.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
This class evaluates LLVM IR, producing the Constant representing each SSA instruction.
DenseMap< GlobalVariable *, Constant * > getMutatedInitializers() const
LLVM_ABI bool EvaluateFunction(Function *F, Constant *&RetVal, const SmallVectorImpl< Constant * > &ActualArgs)
Evaluate a call to function F, returning true if successful, false if we can't evaluate it.
const SmallPtrSetImpl< GlobalVariable * > & getInvariants() const
const BasicBlock & getEntryBlock() const
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
const Function & getFunction() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
const Constant * getAliasee() const
LLVM_ABI const Function * getResolverFunction() const
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
LinkageTypes getLinkage() const
void setUnnamedAddr(UnnamedAddr Val)
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
LLVM_ABI const Comdat * getComdat() const
ThreadLocalMode getThreadLocalMode() const
void setLinkage(LinkageTypes LT)
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time.
bool hasAtLeastLocalUnnamedAddr() const
Returns true if this value's address is not significant in this module.
bool hasGlobalUnnamedAddr() const
UnnamedAddr getUnnamedAddr() const
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit.
@ InternalLinkage
Rename collisions when linking (static functions).
@ AppendingLinkage
Special purpose, only applies to global arrays.
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
bool isExternallyInitialized() const
MaybeAlign getAlign() const
Returns the alignment of the given variable.
void setConstant(bool Val)
LLVM_ABI void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
LLVM_ABI void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression * > &GVs) const
Fill the vector with all debug info attachements.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
LLVMContext & getContext() const
This is the common base class for memset/memcpy/memmove.
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
This class wraps the llvm.memcpy/memmove intrinsics.
A Module instance is used to store all the information related to an LLVM module.
void insertGlobalVariable(GlobalVariable *GV)
Insert global variable GV at the end of the global variable list and take ownership.
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
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.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Value * getValueOperand()
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
int compare(StringRef RHS) const
Compare two strings; the result is negative, zero, or positive if this string is lexicographically le...
Class to represent struct types.
ArrayRef< Type * > elements() const
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ScalableVectorTyID
Scalable SIMD vector type.
@ FixedVectorTyID
Fixed width SIMD vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use 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 const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
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.
This class represents zero extension of integer types.
std::pair< iterator, bool > insert(const ValueT &V)
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.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
@ X86_ThisCall
Similar to X86_StdCall.
@ Fast
Attempts to make calls as fast as possible (e.g.
@ C
The default llvm calling convention, compatible with C.
bool used(const UsedT *U, size_t I)
This is an optimization pass for GlobalISel generic memory operations.
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.
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...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Store
The extracted value is stored (ExtractElement only).
constexpr from_range_t from_range
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
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...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
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.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
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 IPOOptions & getIPOOptions(const LLVMContext &C)
LLVM_ABI Constant * ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty, const DataLayout &DL)
If C is a uniform value where all bits are the same (either all zero, all ones, all undef or all pois...
LLVM_ABI bool isSafeToDestroyConstant(const Constant *C)
It is safe to destroy a constant iff it is only used by constants itself.
LLVM_ABI bool optimizeGlobalCtorsList(Module &M, function_ref< bool(uint32_t, Function *)> ShouldRemove)
Call "ShouldRemove" for every entry in M's global_ctor list and remove the entries for which it retur...
void sort(IteratorTy Start, IteratorTy End)
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 raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isPointerTy(const Type *T)
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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...
LLVM_ABI bool isAllocationFn(const Value *V)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
DWARFExpression::Operation Op
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...
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.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Part of the global at a specific offset, which is only accessed through loads and stores with the giv...
This struct is a compact representation of a valid (non-zero power of two) alignment.
As we analyze each global or thread-local variable, keep track of some information about it.
@ InitializerStored
This global is stored to, but the only thing stored is the constant it was initialized with.
@ StoredOnce
This global is stored to, but only its initializer and one other value is ever stored to it.
static LLVM_ABI bool analyzeGlobal(const Value *V, GlobalStatus &GS)
Look at all uses of the global and fill in the GlobalStatus structure.
Function object to check whether the first component of a container supported by std::get (like std::...