76 #define DEBUG_TYPE "globalopt" 78 STATISTIC(NumMarked ,
"Number of globals marked constant");
79 STATISTIC(NumUnnamed ,
"Number of globals marked unnamed_addr");
80 STATISTIC(NumSRA ,
"Number of aggregate globals broken into scalars");
81 STATISTIC(NumHeapSRA ,
"Number of heap objects SRA'd");
82 STATISTIC(NumSubstitute,
"Number of globals with initializers stored into them");
83 STATISTIC(NumDeleted ,
"Number of globals deleted");
84 STATISTIC(NumGlobUses ,
"Number of global uses devirtualized");
85 STATISTIC(NumLocalized ,
"Number of globals localized");
86 STATISTIC(NumShrunkToBool ,
"Number of global vars shrunk to booleans");
87 STATISTIC(NumFastCallFns ,
"Number of functions converted to fastcc");
88 STATISTIC(NumCtorsEvaluated,
"Number of static ctors evaluated");
89 STATISTIC(NumNestRemoved ,
"Number of nest attributes removed");
90 STATISTIC(NumAliasesResolved,
"Number of global aliases resolved");
91 STATISTIC(NumAliasesRemoved,
"Number of global aliases eliminated");
92 STATISTIC(NumCXXDtorsRemoved,
"Number of global C++ destructors removed");
93 STATISTIC(NumInternalFunc,
"Number of internal functions");
94 STATISTIC(NumColdCC,
"Number of functions marked coldcc");
98 cl::desc(
"Enable stress test of coldcc by adding " 99 "calling conv to all internal functions."),
105 "Maximum block frequency, expressed as a percentage of caller's " 106 "entry frequency, for a call site to be considered cold for enabling" 144 if (isa<PointerType>(InnerTy))
return true;
145 if (isa<CompositeType>(InnerTy))
151 if (--Limit == 0)
return true;
152 }
while (!Types.
empty());
161 if (isa<Constant>(V))
165 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
175 if (!
GEP->hasAllConstantIndices())
199 bool Changed =
false;
210 Value *V =
SI->getValueOperand();
211 if (isa<Constant>(V)) {
213 SI->eraseFromParent();
218 }
else if (
MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
219 if (isa<Constant>(MSI->getValue())) {
221 MSI->eraseFromParent();
222 }
else if (
Instruction *
I = dyn_cast<Instruction>(MSI->getValue())) {
230 MTI->eraseFromParent();
231 }
else if (
Instruction *
I = dyn_cast<Instruction>(MemSrc)) {
235 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
236 if (CE->use_empty()) {
237 CE->destroyConstant();
240 }
else if (
Constant *
C = dyn_cast<Constant>(U)) {
242 C->destroyConstant();
251 for (
int i = 0, e = Dead.
size(); i != e; ++i) {
253 Dead[i].second->eraseFromParent();
277 bool Changed =
false;
283 while (!WorkList.empty()) {
284 Value *UV = WorkList.pop_back_val();
288 User *U = cast<User>(UV);
290 if (
LoadInst *LI = dyn_cast<LoadInst>(U)) {
294 LI->eraseFromParent();
297 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(U)) {
299 SI->eraseFromParent();
301 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
302 if (CE->getOpcode() == Instruction::GetElementPtr) {
307 }
else if ((CE->getOpcode() == Instruction::BitCast &&
308 CE->getType()->isPointerTy()) ||
309 CE->getOpcode() == Instruction::AddrSpaceCast) {
314 if (CE->use_empty()) {
315 CE->destroyConstant();
323 if (!isa<ConstantExpr>(
GEP->getOperand(0))) {
326 if (Init && CE && CE->
getOpcode() == Instruction::GetElementPtr)
332 if (Init && isa<ConstantAggregateZero>(Init) &&
GEP->isInBounds())
337 if (
GEP->use_empty()) {
338 GEP->eraseFromParent();
342 if (
MI->getRawDest() == V) {
343 MI->eraseFromParent();
347 }
else if (
Constant *
C = dyn_cast<Constant>(U)) {
351 C->destroyConstant();
370 !cast<Constant>(U->
getOperand(1))->isNullValue())
381 for (; GEPI !=
E; ++GEPI) {
403 if (!I)
return false;
406 if (isa<LoadInst>(I))
return true;
410 return SI->getOperand(0) != V;
421 if (!isa<GetElementPtrInst>(U) &&
422 (!isa<ConstantExpr>(U) ||
423 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
436 uint64_t FragmentOffsetInBits,
437 uint64_t FragmentSizeInBits,
438 unsigned NumElements) {
441 for (
auto *GVE : GVs) {
444 if (NumElements > 1) {
446 Expr, FragmentOffsetInBits, FragmentSizeInBits))
468 Type *Ty = Init->getType();
470 std::vector<GlobalVariable *> NewGlobals;
475 if (StartAlignment == 0)
478 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
479 unsigned NumElements = STy->getNumElements();
480 NewGlobals.reserve(NumElements);
482 for (
unsigned i = 0, e = NumElements; i != e; ++i) {
484 assert(In &&
"Couldn't get element of initializer?");
493 NewGlobals.push_back(NGV);
509 unsigned NumElements = STy->getNumElements();
512 NewGlobals.reserve(NumElements);
513 auto ElTy = STy->getElementType();
517 for (
unsigned i = 0, e = NumElements; i != e; ++i) {
519 assert(In &&
"Couldn't get element of initializer?");
529 NewGlobals.push_back(NGV);
535 if (NewAlign > EltAlign)
542 if (NewGlobals.empty())
545 LLVM_DEBUG(
dbgs() <<
"PERFORMING GLOBAL SRA ON: " << *GV <<
"\n");
553 assert(((isa<ConstantExpr>(GEP) &&
554 cast<ConstantExpr>(GEP)->
getOpcode()==Instruction::GetElementPtr)||
555 isa<GetElementPtrInst>(GEP)) &&
"NonGEP CE's are not SRAable!");
560 unsigned Val = cast<ConstantInt>(GEP->
getOperand(2))->getZExtValue();
561 if (Val >= NewGlobals.size()) Val = 0;
563 Value *NewPtr = NewGlobals[Val];
564 Type *NewTy = NewGlobals[Val]->getValueType();
571 for (
unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
582 NewTy, NewPtr, Idxs, GEPI->
getName() +
"." +
Twine(Val), GEPI);
588 GEPI->eraseFromParent();
590 cast<ConstantExpr>(
GEP)->destroyConstant();
600 unsigned FirstGlobal = 0;
601 for (
unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
602 if (NewGlobals[i]->use_empty()) {
603 Globals.
erase(NewGlobals[i]);
604 if (FirstGlobal == i) ++FirstGlobal;
607 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] :
nullptr;
622 if (isa<LoadInst>(U)) {
624 }
else if (
const StoreInst *
SI = dyn_cast<StoreInst>(U)) {
625 if (
SI->getOperand(0) == V) {
629 }
else if (
const CallInst *CI = dyn_cast<CallInst>(U)) {
630 if (CI->getCalledValue() != V) {
634 }
else if (
const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
635 if (II->getCalledValue() != V) {
639 }
else if (
const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
643 }
else if (
const PHINode *PN = dyn_cast<PHINode>(U)) {
648 }
else if (isa<ICmpInst>(U) &&
649 isa<ConstantPointerNull>(U->getOperand(1))) {
664 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
668 }
else if (isa<StoreInst>(U)) {
679 bool Changed =
false;
686 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
687 LI->setOperand(0, NewV);
689 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(I)) {
690 if (
SI->getOperand(1) == V) {
691 SI->setOperand(1, NewV);
694 }
else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
701 bool PassedAsArg =
false;
702 for (
unsigned i = 0, e = CS.
arg_size(); i != e; ++i)
713 }
else if (
CastInst *CI = dyn_cast<CastInst>(I)) {
717 if (CI->use_empty()) {
719 CI->eraseFromParent();
724 Idxs.
reserve(GEPI->getNumOperands()-1);
727 if (
Constant *
C = dyn_cast<Constant>(*i))
731 if (Idxs.
size() == GEPI->getNumOperands()-1)
734 if (GEPI->use_empty()) {
736 GEPI->eraseFromParent();
751 bool Changed =
false;
755 bool AllNonStoreUsesGone =
true;
759 User *GlobalUser = *GUI++;
760 if (
LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
763 if (LI->use_empty()) {
764 LI->eraseFromParent();
767 AllNonStoreUsesGone =
false;
769 }
else if (isa<StoreInst>(GlobalUser)) {
772 "Must be storing *to* the global");
774 AllNonStoreUsesGone =
false;
778 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
779 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
780 isa<BitCastInst>(GlobalUser) ||
781 isa<GetElementPtrInst>(GlobalUser)) &&
782 "Only expect load and stores!");
787 LLVM_DEBUG(
dbgs() <<
"OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV
794 if (AllNonStoreUsesGone) {
818 I->replaceAllUsesWith(NewC);
822 while (UI !=
E && *UI ==
I)
825 I->eraseFromParent();
838 LLVM_DEBUG(
errs() <<
"PROMOTING GLOBAL: " << *GV <<
" CALL = " << *CI
843 GlobalType = AllocTy;
861 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
862 if (BCI->getType() == NewGV->getType()) {
864 BCI->eraseFromParent();
866 BCI->setOperand(0, NewGV);
883 GlobalValue::InternalLinkage,
886 bool InitBoolUsed =
false;
893 SI->getOrdering(),
SI->getSyncScopeID(),
SI);
894 SI->eraseFromParent();
940 cast<StoreInst>(InitBool->
user_back())->eraseFromParent();
953 if (RepValue != NewGV)
968 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
972 if (
const StoreInst *
SI = dyn_cast<StoreInst>(Inst)) {
973 if (
SI->getOperand(0) == V &&
SI->getOperand(1) != GV)
979 if (isa<GetElementPtrInst>(Inst) && Inst->
getNumOperands() >= 3) {
985 if (
const PHINode *PN = dyn_cast<PHINode>(Inst)) {
988 if (PHIs.
insert(PN).second)
994 if (
const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
1016 if (
SI->getOperand(1) == GV) {
1017 SI->eraseFromParent();
1020 }
else if (
PHINode *PN = dyn_cast<PHINode>(U)) {
1023 InsertPt = PN->getIncomingBlock(*Alloc->
use_begin())->getTerminator();
1024 }
else if (isa<BitCastInst>(U)) {
1032 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1033 if (
StoreInst *
SI = dyn_cast<StoreInst>(GEPI->user_back()))
1034 if (
SI->getOperand(1) == GV) {
1038 GEPI->eraseFromParent();
1061 if (
const ICmpInst *ICI = dyn_cast<ICmpInst>(UI)) {
1062 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1070 if (GEPI->getNumOperands() < 3)
1077 if (
const PHINode *PN = dyn_cast<PHINode>(UI)) {
1078 if (!LoadUsingPHIsPerLoad.
insert(PN).second)
1082 if (!LoadUsingPHIs.
insert(PN).second)
1088 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1108 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1110 LoadUsingPHIsPerLoad))
1112 LoadUsingPHIsPerLoad.
clear();
1120 for (
const PHINode *PN : LoadUsingPHIs) {
1121 for (
unsigned op = 0, e = PN->getNumIncomingValues();
op != e; ++
op) {
1122 Value *InVal = PN->getIncomingValue(
op);
1125 if (InVal == StoredVal)
continue;
1127 if (
const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1129 if (LoadUsingPHIs.count(InPN))
1135 if (
const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1136 if (LI->getOperand(0) == GV)
1150 DenseMap<
Value *, std::vector<Value *>> &InsertedScalarizedValues,
1151 std::vector<std::pair<PHINode *, unsigned>> &PHIsToRewrite) {
1152 std::vector<Value *> &FieldVals = InsertedScalarizedValues[V];
1154 if (FieldNo >= FieldVals.size())
1155 FieldVals.resize(FieldNo+1);
1159 if (
Value *FieldVal = FieldVals[FieldNo])
1164 if (
LoadInst *LI = dyn_cast<LoadInst>(V)) {
1168 InsertedScalarizedValues,
1172 PHINode *PN = cast<PHINode>(V);
1177 StructType *
ST = cast<StructType>(PTy->getElementType());
1179 unsigned AS = PTy->getAddressSpace();
1185 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1188 return FieldVals[FieldNo] = Result;
1194 DenseMap<
Value *, std::vector<Value *>> &InsertedScalarizedValues,
1195 std::vector<std::pair<PHINode *, unsigned>> &PHIsToRewrite) {
1197 if (
ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1198 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1202 InsertedScalarizedValues, PHIsToRewrite);
1208 SCI->eraseFromParent();
1214 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1215 &&
"Unexpected GEPI!");
1218 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1220 InsertedScalarizedValues, PHIsToRewrite);
1225 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1230 GEPI->eraseFromParent();
1240 PHINode *PN = cast<PHINode>(LoadUser);
1241 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1242 std::vector<Value *>())).second)
1257 DenseMap<
Value *, std::vector<Value *>> &InsertedScalarizedValues,
1258 std::vector<std::pair<PHINode *, unsigned> > &PHIsToRewrite) {
1266 InsertedScalarizedValues.
erase(Load);
1275 LLVM_DEBUG(
dbgs() <<
"SROA HEAP ALLOC: " << *GV <<
" MALLOC = " << *CI
1288 std::vector<Value *> FieldGlobals;
1289 std::vector<Value *> FieldMallocs;
1295 for (
unsigned FieldNo = 0, e = STy->
getNumElements(); FieldNo != e;++FieldNo){
1304 FieldGlobals.push_back(NGV);
1312 NElems, OpBundles,
nullptr,
1314 FieldMallocs.push_back(NMI);
1333 ConstantZero,
"isneg");
1334 for (
unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1338 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond,
"tmp", CI);
1359 for (
unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1360 Value *GVVal =
new LoadInst(FieldGlobals[i],
"tmp", NullPtrBlock);
1376 NullPtrBlock = NextBlock;
1387 InsertedScalarizedValues[GV] = FieldGlobals;
1389 std::vector<std::pair<PHINode *, unsigned>> PHIsToRewrite;
1397 if (
LoadInst *LI = dyn_cast<LoadInst>(User)) {
1405 "Unexpected heap-sra user!");
1408 for (
unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1409 Type *ValTy = cast<GlobalValue>(FieldGlobals[i])->getValueType();
1411 new StoreInst(Null, FieldGlobals[i], SI);
1418 while (!PHIsToRewrite.empty()) {
1419 PHINode *PN = PHIsToRewrite.back().first;
1420 unsigned FieldNo = PHIsToRewrite.back().second;
1421 PHIsToRewrite.pop_back();
1422 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1436 I = InsertedScalarizedValues.
begin(),
E = InsertedScalarizedValues.
end();
1438 if (
PHINode *PN = dyn_cast<PHINode>(
I->first))
1439 PN->dropAllReferences();
1440 else if (
LoadInst *LI = dyn_cast<LoadInst>(
I->first))
1441 LI->dropAllReferences();
1446 I = InsertedScalarizedValues.
begin(),
E = InsertedScalarizedValues.
end();
1448 if (
PHINode *PN = dyn_cast<PHINode>(
I->first))
1449 PN->eraseFromParent();
1450 else if (
LoadInst *LI = dyn_cast<LoadInst>(
I->first))
1451 LI->eraseFromParent();
1458 return cast<GlobalVariable>(FieldGlobals[0]);
1499 if (
ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1518 if (
ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1519 AllocTy = AT->getElementType();
1541 OpBundles,
nullptr, CI->
getName());
1545 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1546 CI = cast<CallInst>(BCI->getOperand(0));
1548 CI = cast<CallInst>(Malloc);
1577 if (
Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1615 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1633 "No reason to shrink to bool!");
1640 bool IsOneZero =
false;
1641 bool EmitOneOrZero =
true;
1642 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)){
1643 IsOneZero = InitVal->
isNullValue() && CI->isOne();
1646 uint64_t ValInit = CIInit->getZExtValue();
1647 uint64_t ValOther = CI->getZExtValue();
1648 uint64_t ValMinus = ValOther - ValInit;
1650 for(
auto *GVe : GVs){
1663 dwarf::DW_OP_deref, dwarf::DW_OP_constu, ValMinus,
1664 dwarf::DW_OP_mul, dwarf::DW_OP_constu, ValInit,
1671 EmitOneOrZero =
false;
1675 if (EmitOneOrZero) {
1686 bool StoringOther =
SI->getOperand(0) == OtherVal;
1689 if (StoringOther ||
SI->getOperand(0) == InitVal) {
1696 Instruction *StoredVal = cast<Instruction>(
SI->getOperand(0));
1701 if (
LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1702 assert(LI->getOperand(0) == GV &&
"Not a copy!");
1705 LI->getOrdering(), LI->getSyncScopeID(), LI);
1707 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1708 "This is not a form that we understand!");
1710 assert(isa<LoadInst>(StoreVal) &&
"Not a load of NewGV!");
1714 new StoreInst(StoreVal, NewGV,
false, 0,
SI->getOrdering(),
1715 SI->getSyncScopeID(),
SI);
1756 if (
auto *
F = dyn_cast<Function>(&GV))
1757 Dead = (
F->isDeclaration() &&
F->use_empty()) ||
F->isDefTriviallyDead();
1785 for (
auto *U : GV->
users()) {
1787 for (
auto *UU : U->users()) {
1788 if (
auto *LI = dyn_cast<LoadInst>(UU))
1790 else if (
auto *
SI = dyn_cast<StoreInst>(UU))
1803 if (
auto *LI = dyn_cast<LoadInst>(I))
1805 else if (
auto *
SI = dyn_cast<StoreInst>(I))
1815 auto &DT = LookupDomTree(*const_cast<Function *>(F));
1830 for (
auto *L : Loads) {
1831 auto *LTy = L->getType();
1837 return DT.dominates(S, L) &&
1855 for (
auto *U : C->
users()) {
1856 if (isa<Instruction>(U))
1858 if (!isa<ConstantExpr>(U))
1861 for (
auto *UU : U->users())
1862 if (!isa<Instruction>(UU))
1876 for (
auto *U : C->
users()) {
1877 if (isa<ConstantExpr>(U))
1883 isa<Instruction>(U) &&
1884 "Can't transform non-constantexpr non-instruction to instruction!");
1888 for (
auto *U : Users) {
1890 for (
auto *UU : U->users())
1892 for (
auto *UU : UUsers) {
1900 U->destroyConstant();
1980 LLVM_DEBUG(
dbgs() <<
" *** Marking constant allowed us to simplify " 1981 <<
"all users and delete global!\n");
2009 LLVM_DEBUG(
dbgs() <<
" *** Substituting initializer allowed us to " 2010 <<
"simplify all users and delete global!\n");
2051 bool Changed =
false;
2070 if (GVar->isConstant() || !GVar->hasInitializer())
2080 if (isa<BlockAddress>(U))
2098 if (isa<BlockAddress>(U))
2128 if (isa<BlockAddress>(U))
2139 if (BB.getTerminatingMustTailCall())
2150 auto CallSiteFreq = CallerBFI.
getBlockFreq(CallSiteBB);
2151 auto CallerEntryFreq =
2153 return CallSiteFreq < CallerEntryFreq * ColdProb;
2163 const std::vector<Function *> &AllCallsCold) {
2169 if (isa<BlockAddress>(U))
2177 auto It =
std::find(AllCallsCold.begin(), AllCallsCold.end(), CallerFunc);
2178 if (It == AllCallsCold.end())
2186 if (isa<BlockAddress>(U))
2201 if (
CallInst *CI = dyn_cast<CallInst>(&
I)) {
2202 CallSite CS(cast<Instruction>(CI));
2204 if (CI->isInlineAsm())
2206 Function *CalledFn = CI->getCalledFunction();
2234 bool Changed =
false;
2236 std::vector<Function *> AllCallsCold;
2240 AllCallsCold.push_back(F);
2273 auto &DT = LookupDomTree(*F);
2328 bool Changed =
false;
2341 if (New && New !=
C)
2369 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2375 assert(Idx < STy->getNumElements() &&
"Struct index out of range!");
2387 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2403 assert(GV->hasInitializer());
2404 GV->setInitializer(Val);
2460 for (
const auto &
I : Mem) {
2461 if (
auto *GV = dyn_cast<GlobalVariable>(
I.first)) {
2467 ComplexCEs.
push_back(std::make_pair(GEP,
I.second));
2469 SimpleCEs.
push_back(std::make_pair(GEP,
I.second));
2475 for (
auto ComplexCE : ComplexCEs)
2478 for (
auto GVPair : GVs) {
2479 assert(GVPair.first->hasInitializer());
2480 GVPair.first->setInitializer(GVPair.second);
2483 if (SimpleCEs.
empty())
2494 auto commitAndSetupCache = [&](
GlobalVariable *GV,
bool Update) {
2499 assert(CurrentGV &&
"Expected a GV to commit to!");
2502 if (
StructType *STy = dyn_cast<StructType>(CurrentInitTy))
2504 else if (
ArrayType *ArrTy = dyn_cast<ArrayType>(CurrentInitTy))
2509 if (CurrentGV == GV)
2515 if (
auto *STy = dyn_cast<StructType>(Ty))
2516 NumElts = STy->getNumElements();
2518 NumElts = cast<SequentialType>(Ty)->getNumElements();
2519 for (
unsigned i = 0, e = NumElts; i != e; ++i)
2524 for (
auto CEPair : SimpleCEs) {
2529 commitAndSetupCache(GV, GV != CurrentGV);
2535 commitAndSetupCache(CurrentGV,
true);
2549 ++NumCtorsEvaluated;
2557 GV->setConstant(
true);
2583 UsedArray.push_back(Cast);
2617 iterator usedBegin() {
return Used.
begin(); }
2618 iterator usedEnd() {
return Used.
end(); }
2620 used_iterator_range used() {
2621 return used_iterator_range(usedBegin(), usedEnd());
2624 iterator compilerUsedBegin() {
return CompilerUsed.
begin(); }
2625 iterator compilerUsedEnd() {
return CompilerUsed.
end(); }
2627 used_iterator_range compilerUsed() {
2628 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
2634 return CompilerUsed.
count(GV);
2642 return CompilerUsed.
insert(GV).second;
2645 void syncVariablesAndSets() {
2659 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2660 "We should have removed the duplicated " 2661 "element from llvm.compiler.used");
2668 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
2672 const LLVMUsed &U) {
2674 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2675 "We should have removed the duplicated " 2676 "element from llvm.compiler.used");
2677 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2686 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2690 bool &RenameTarget) {
2691 RenameTarget =
false;
2717 RenameTarget =
true;
2724 bool Changed =
false;
2728 Used.compilerUsedErase(GV);
2762 ++NumAliasesResolved;
2773 if (Used.usedErase(&*J))
2774 Used.usedInsert(Target);
2776 if (Used.compilerUsedErase(&*J))
2777 Used.compilerUsedInsert(Target);
2783 ++NumAliasesRemoved;
2787 Used.syncVariablesAndSets();
2793 LibFunc F = LibFunc_cxa_atexit;
2802 if (!TLI->
getLibFunc(*Fn, F) || F != LibFunc_cxa_atexit)
2827 if (
const CallInst *CI = dyn_cast<CallInst>(
I)) {
2829 if (isa<DbgInfoIntrinsic>(CI))
2832 const Function *CalledFn = CI->getCalledFunction();
2840 if (!NewCalledFunctions.
insert(CalledFn).second)
2845 }
else if (isa<ReturnInst>(*
I))
2847 else if (
I->mayHaveSideEffects())
2869 bool Changed =
false;
2893 ++NumCXXDtorsRemoved;
2907 bool Changed =
false;
2908 bool LocalChange =
true;
2909 while (LocalChange) {
2910 LocalChange =
false;
2912 NotDiscardableComdats.
clear();
2916 NotDiscardableComdats.
insert(
C);
2920 NotDiscardableComdats.
insert(
C);
2922 if (
const Comdat *
C = GA.getComdat())
2923 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
2924 NotDiscardableComdats.
insert(
C);
2928 NotDiscardableComdats);
2937 NotDiscardableComdats);
2948 Changed |= LocalChange;
2980 struct GlobalOptLegacyPass :
public ModulePass {
2987 bool runOnModule(
Module &M)
override {
2992 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2994 return this->getAnalysis<DominatorTreeWrapperPass>(
F).getDomTree();
2997 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3001 return this->getAnalysis<BlockFrequencyInfoWrapperPass>(
F).getBFI();
3020 "Global Variable Optimizer",
false,
false)
3029 return new GlobalOptLegacyPass();
void setVisibility(VisibilityTypes V)
bool isBoundedSequential() const
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getAlignment() const
bool isAllocationFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
ThreadLocalMode getThreadLocalMode() const
static bool CleanupConstantGlobalUsers(Value *V, Constant *Init, const DataLayout &DL, TargetLibraryInfo *TLI)
We just marked GV constant.
void initializeGlobalOptLegacyPassPass(PassRegistry &)
bool IsLoaded
True if the global is ever loaded.
static bool isLeakCheckerRoot(GlobalVariable *GV)
Is this global variable possibly used by a leak checker as a root? If so, we might not really want to...
static IntegerType * getInt1Ty(LLVMContext &C)
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool hasLocalLinkage() const
C - The default llvm calling convention, compatible with C.
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Special purpose, only applies to global arrays.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * StoredOnceValue
If only one value (besides the initializer constant) is ever stored to this global, keep track of what value it is.
const Function * AccessingFunction
These start out null/false.
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
DiagnosticInfoOptimizationBase::Argument NV
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
unsigned arg_size() const
Atomic ordering constants.
bool hasPrivateLinkage() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
iterator erase(iterator where)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI)
Given a value that is stored to a global but never read, determine whether it's safe to remove the st...
Type * getElementType(unsigned N) const
Constant * ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE)
ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a getelementptr constantexpr, return the constant value being addressed by the constant expression, or null if something is funny and we can't decide.
A Module instance is used to store all the information related to an LLVM module. ...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
static Value * GetHeapSROAValue(Value *V, unsigned FieldNo, DenseMap< Value *, std::vector< Value *>> &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned >> &PHIsToRewrite)
static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, GlobalVariable *GV)
The Alloc pointer is stored into GV somewhere.
This class represents zero extension of integer types.
unsigned getNumElements() const
Random access to the elements.
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
void push_back(const T &Elt)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
bool removeUnreachableBlocks(Function &F, LazyValueInfo *LVI=nullptr, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static bool isSafeSROAElementUse(Value *V)
Return true if the specified instruction is a safe user of a derived expression from a global that we...
static bool deleteIfDead(GlobalValue &GV, SmallPtrSetImpl< const Comdat *> &NotDiscardableComdats)
This class represents a function call, abstracting a target machine's calling convention.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
gep_type_iterator gep_type_end(const User *GEP)
static bool OptimizeGlobalVars(Module &M, TargetLibraryInfo *TLI, function_ref< DominatorTree &(Function &)> LookupDomTree, SmallPtrSetImpl< const Comdat *> &NotDiscardableComdats)
An efficient, type-erasing, non-owning reference to a callable.
static bool hasChangeableCC(Function *F)
Return true if this is a calling convention that we'd like to change.
static Constant * EvaluateStoreInto(Constant *Init, Constant *Val, ConstantExpr *Addr, unsigned OpNo)
Evaluate a piece of a constantexpr store into a global initializer.
StringRef getName(LibFunc F) const
Analysis pass providing the TargetTransformInfo.
static bool hasOnlyColdCalls(Function &F, function_ref< BlockFrequencyInfo &(Function &)> GetBFI)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
static GlobalVariable * OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy, ConstantInt *NElements, const DataLayout &DL, TargetLibraryInfo *TLI)
This function takes the specified global variable, and transforms the program as if it always contain...
static bool isSafeSROAGEP(User *U)
Return true if the specified GEP is a safe user of a derived expression from a global that we want to...
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
bool HasMultipleAccessingFunctions
LLVMContext & getContext() const
All values hold a context through their type.
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
This class wraps the llvm.memset intrinsic.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
STATISTIC(NumFunctions, "Total number of functions")
static cl::opt< bool > EnableColdCCStressTest("enable-coldcc-stress-test", cl::desc("Enable stress test of coldcc by adding " "calling conv to all internal functions."), cl::init(false), cl::Hidden)
Analysis pass which computes a DominatorTree.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
const GlobalListType & getGlobalList() const
Get the Module's list of global variables (constant).
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
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.
static Instruction * CreateFree(Value *Source, Instruction *InsertBefore)
Generate the IR for a call to the builtin free function.
iv Induction Variable Users
static GlobalVariable * PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI, Value *NElems, const DataLayout &DL, const TargetLibraryInfo *TLI)
CI is an allocation of an array of structures.
This defines the Use class.
void reserve(size_type N)
bool isMustTailCall() const
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...
void setAlignment(unsigned Align)
static bool processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS, TargetLibraryInfo *TLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
LLVMContext & getContext() const
Get the context in which this basic block lives.
static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V, SmallPtrSetImpl< const PHINode *> &LoadUsingPHIs, SmallPtrSetImpl< const PHINode *> &LoadUsingPHIsPerLoad)
Verify that all uses of V (a load, or a phi of a load) are simple enough to perform heap SRA on...
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
This global is stored to, but the only thing stored is the constant it was initialized with...
static int compareNames(Constant *const *A, Constant *const *B)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
const AliasListType & getAliasList() const
Get the Module's list of aliases (constant).
Value * getArgOperand(unsigned i) const
static DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
unsigned getAllocaAddrSpace() const
AnalysisUsage & addRequired()
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
#define INITIALIZE_PASS_DEPENDENCY(depName)
static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U, bool &RenameTarget)
static void makeAllConstantUsesInstructions(Constant *C)
C may have non-instruction users, and allNonInstructionUsersCanBeMadeInstructions has returned true...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static bool isColdCallSite(CallSite CS, BlockFrequencyInfo &CallerBFI)
Return true if the block containing the call site has a BlockFrequency of less than ColdCCRelFreq% of...
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV)
Return true if all uses of any loads from GV will trap if the loaded value is null.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This is the base class for all instructions that perform data casts.
TypeID getTypeID() const
Return the type id for the type.
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
static void changeCallSitesToColdCC(Function *F)
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
uint64_t getElementOffsetInBits(unsigned Idx) const
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
static bool optimizeGlobalsInModule(Module &M, const DataLayout &DL, TargetLibraryInfo *TLI, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, function_ref< DominatorTree &(Function &)> LookupDomTree)
UnnamedAddr getUnnamedAddr() const
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
This file contains the simple types necessary to represent the attributes associated with functions a...
Legacy analysis pass which computes BlockFrequencyInfo.
StoredType
Keep track of what stores to the global look like.
InstrTy * getInstruction() const
static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U)
uint64_t getNumElements() const
void setDLLStorageClass(DLLStorageClassTypes C)
void setArgument(unsigned ArgNo, Value *newVal)
static bool OptimizeFunctions(Module &M, TargetLibraryInfo *TLI, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, 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 hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U)
AtomicOrdering
Atomic ordering for LLVM's memory model.
INITIALIZE_PASS_BEGIN(GlobalOptLegacyPass, "globalopt", "Global Variable Optimizer", false, false) INITIALIZE_PASS_END(GlobalOptLegacyPass
global_iterator global_begin()
ValTy * getCalledValue() const
Return the pointer to function that is being called.
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
static cl::opt< int > ColdCCRelFreq("coldcc-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore, cl::desc("Maximum block frequency, expressed as a percentage of caller's " "entry frequency, for a call site to be considered cold for enabling" "coldcc"))
Fast - This calling convention attempts to make calls as fast as possible (e.g.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
A constant value that is initialized with an expression using other constant values.
Type * getType() const
All values are typed, get the type of this value.
static bool optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, AtomicOrdering Ordering, const DataLayout &DL, TargetLibraryInfo *TLI)
static void ChangeCalleesToFastCall(Function *F)
Walk all of the direct calls of the specified function, changing them to FastCC.
static Function * FindCXAAtExit(Module &M, TargetLibraryInfo *TLI)
static void setUsedInitializer(GlobalVariable &V, const SmallPtrSetImpl< GlobalValue *> &Init)
Class to represent array types.
bool has(LibFunc F) const
Tests whether a library function is available.
static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V, const GlobalVariable *GV, SmallPtrSetImpl< const PHINode *> &PHIs)
Scan the use-list of V checking to make sure that there are no complex uses of V. ...
This class represents a no-op cast from one type to another.
AttributeList getAttributes() const
Return the attribute list for this Function.
An instruction for storing to memory.
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
void takeName(Value *V)
Transfer the name from V to this value.
Type::subtype_iterator element_iterator
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Class to represent pointers.
This global is stored to, but only its initializer and one other value is ever stored to it...
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Value * getMallocArraySize(CallInst *CI, const DataLayout &DL, const TargetLibraryInfo *TLI, bool LookThroughSExt=false)
getMallocArraySize - Returns the array size of a malloc call.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
const BasicBlock & getEntryBlock() const
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
bool hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index=nullptr) const
Return true if the specified attribute is set for at least one parameter or for the return value...
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
void setCallingConv(CallingConv::ID CC)
initializer< Ty > init(const Ty &Val)
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
As we analyze each global, keep track of some information about it.
A set of analyses that are preserved following a run of a transformation pass.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
DLLStorageClassTypes getDLLStorageClass() const
VisibilityTypes getVisibility() const
alias_iterator alias_end()
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
const CallInst * extractMallocCall(const Value *I, const TargetLibraryInfo *TLI)
extractMallocCall - Returns the corresponding CallInst if the instruction is a malloc call...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() 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.
void setExternallyInitialized(bool Val)
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.
void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression *> &GVs) const
Fill the vector with all debug info attachements.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
element_iterator element_end() const
static void RemoveNestAttribute(Function *F)
A pair of DIGlobalVariable and DIExpression.
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit...
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
static bool cxxDtorIsEmpty(const Function &Fn, SmallPtrSet< const Function *, 8 > &CalledFunctions)
Returns whether the given function is an empty C++ destructor and can therefore be eliminated...
static Constant * get(StructType *T, ArrayRef< Constant *> V)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Base class for variables.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE int compare(StringRef RHS) const
compare - Compare two strings; the result is -1, 0, or 1 if this string is lexicographically less tha...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
ModulePass * createGlobalOptimizerPass()
createGlobalOptimizerPass - This function returns a new pass that optimizes non-address taken interna...
static bool isValidCandidateForColdCC(Function &F, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, const std::vector< Function *> &AllCallsCold)
static bool analyzeGlobal(const Value *V, GlobalStatus &GS)
Look at all uses of the global and fill in the GlobalStatus structure.
const Function * getFunction() const
Return the function this instruction belongs to.
void setConstant(bool Val)
static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V, const LLVMUsed &U)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Constant * stripPointerCasts() const
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
bool isSafeToDestroyConstant(const Constant *C)
It is safe to destroy a constant iff it is only used by constants itself.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
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...
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
static void ConstantPropUsersOf(Value *V, const DataLayout &DL, TargetLibraryInfo *TLI)
Walk the use list of V, constant folding all of the instructions that are foldable.
static void RewriteHeapSROALoadUser(Instruction *LoadUser, DenseMap< Value *, std::vector< Value *>> &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned >> &PHIsToRewrite)
Given a load instruction and a value derived from the load, rewrite the derived value to use the Heap...
void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool doesNotRecurse() const
Determine if the function is known not to recurse, directly or indirectly.
This class evaluates LLVM IR, producing the Constant representing each SSA instruction.
global_iterator global_end()
This is the superclass of the array and vector type classes.
static AttributeList StripNest(LLVMContext &C, AttributeList Attrs)
GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallPtrSetImpl< GlobalValue *> &Set, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Analysis pass which computes BlockFrequencyInfo.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
Global Variable Optimizer
This is the shared class of boolean and integer constants.
static void CommitValueTo(Constant *Val, Constant *Addr)
We have decided that Addr (which satisfies the predicate isSimpleEnoughPointerToCommit) should get Va...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
ValTy * getArgument(unsigned ArgNo) const
16: SIMD 'packed' format, or other vector type
X86_ThisCall - Similar to X86_StdCall.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
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.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_NODISCARD T pop_back_val()
uint64_t getSizeInBytes() const
alias_iterator alias_begin()
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
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)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
bool hasGlobalUnnamedAddr() const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static ConstantInt * getTrue(LLVMContext &Context)
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
void setLinkage(LinkageTypes LT)
BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, TargetLibraryInfo *TLI)
Evaluate static constructors in the function, if we can.
A range adaptor for a pair of iterators.
This file contains constants used for implementing Dwarf debug support.
const Comdat * getComdat() const
Target - Wrapper for Target specific information.
void push_back(pointer val)
Type * getMallocAllocatedType(const CallInst *CI, const TargetLibraryInfo *TLI)
getMallocAllocatedType - Returns the Type allocated by malloc call.
iterator_range< user_iterator > users()
static bool allNonInstructionUsersCanBeMadeInstructions(Constant *C)
C may have non-instruction users.
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
element_iterator element_begin() const
static Instruction * CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, Type *AllocTy, Value *AllocSize, Value *ArraySize=nullptr, Function *MallocF=nullptr, const Twine &Name="")
Generate the IR for a call to malloc:
const SmallPtrSetImpl< GlobalVariable * > & getInvariants() const
static void BatchCommitValueTo(const DenseMap< Constant *, Constant *> &Mem)
Given a map of address -> value, where addresses are expected to be some form of either a global or a...
const Comdat * getComdat() const
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Predicate getPredicate() const
Return the predicate for this instruction.
static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV, Instruction *StoredVal)
If all users of values loaded from GV are simple enough to perform HeapSRA, return true...
This class wraps the llvm.memcpy/memmove intrinsics.
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
FunTy * getCaller() const
Return the caller function for this call site.
static bool GlobalUsersSafeToSRA(GlobalValue *GV)
Look at all uses of the global and decide whether it is safe for us to perform this transformation...
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void setUnnamedAddr(UnnamedAddr Val)
uint64_t getElementOffset(unsigned Idx) const
static IntegerType * getInt32Ty(LLVMContext &C)
bool IsCompared
True if the global's address is used in a comparison.
uint64_t getSequentialNumElements() const
Value * getOperand() const
LLVM_NODISCARD bool empty() const
AtomicOrdering Ordering
Set to the strongest atomic ordering requirement.
unsigned greater or equal
static bool OptimizeGlobalAliases(Module &M, SmallPtrSetImpl< const Comdat *> &NotDiscardableComdats)
const Value * stripPointerCastsNoFollowAliases() const
Strip off pointer casts and all-zero GEPs.
StringRef getName() const
Return a constant reference to the value's name.
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
LLVM_NODISCARD AttributeList removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const
Remove the specified attribute at the specified index from this attribute list.
const Function * getParent() const
Return the enclosing method, or null if none.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
user_iterator_impl< User > user_iterator
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
static bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn)
static GlobalVariable * SRAGlobal(GlobalVariable *GV, const DataLayout &DL)
Perform scalar replacement of aggregates on the specified global variable.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
const DenseMap< Constant *, Constant * > & getMutatedMemory() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
Rename collisions when linking (static functions).
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static bool tryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, CallInst *CI, Type *AllocTy, AtomicOrdering Ordering, const DataLayout &DL, TargetLibraryInfo *TLI)
This function is called when we see a pointer global variable with a single value stored it that is a...
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Analysis pass providing the TargetLibraryInfo.
static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV, const DataLayout &DL, TargetLibraryInfo *TLI)
The specified global has only one non-null value stored into it.
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
static void transferSRADebugInfo(GlobalVariable *GV, GlobalVariable *NGV, uint64_t FragmentOffsetInBits, uint64_t FragmentSizeInBits, unsigned NumElements)
Copy over the debug info for a variable to its SRA replacements.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
static bool processGlobal(GlobalValue &GV, TargetLibraryInfo *TLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
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.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV)
bool hasInitializer() const
Definitions have initializers, declarations don't.
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
uint64_t getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
Type * getElementType() const
iterator_range< global_iterator > globals()
bool hasOneUse() const
Return true if there is exactly one user of this value.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
AttributeList getAttributes() const
Get the parameter attributes of the call.
static bool CleanupPointerRootUsers(GlobalVariable *GV, const TargetLibraryInfo *TLI)
This GV is a pointer root.
static bool isPointerValueDeadOnEntryToFunction(const Function *F, GlobalValue *GV, function_ref< DominatorTree &(Function &)> LookupDomTree)
bool optimizeGlobalCtorsList(Module &M, function_ref< bool(Function *)> ShouldRemove)
Call "ShouldRemove" for every entry in M's global_ctor list and remove the entries for which it retur...
static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load, DenseMap< Value *, std::vector< Value *>> &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned > > &PHIsToRewrite)
We are performing Heap SRoA on a global.
bool isExternallyInitialized() const
void setSection(StringRef S)
Change the section for this global.
void setCalledFunction(Value *V)
Set the callee to the specified value.
bool isDefTriviallyDead() const
isDefTriviallyDead - Return true if it is trivially safe to remove this function definition from the ...
static Constant * get(ArrayRef< Constant *> V)
static bool AllUsesOfValueWillTrapIfNull(const Value *V, SmallPtrSetImpl< const PHINode *> &PHIs)
Return true if all users of the specified value will trap if the value is dynamically null...
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
bool isArrayTy() const
True if this is an instance of ArrayType.
static 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...
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
gep_type_iterator gep_type_begin(const User *GEP)
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
const Constant * getAliasee() const