16 #define DEBUG_TYPE "globalopt"
46 STATISTIC(NumMarked ,
"Number of globals marked constant");
47 STATISTIC(NumUnnamed ,
"Number of globals marked unnamed_addr");
48 STATISTIC(NumSRA ,
"Number of aggregate globals broken into scalars");
49 STATISTIC(NumHeapSRA ,
"Number of heap objects SRA'd");
50 STATISTIC(NumSubstitute,
"Number of globals with initializers stored into them");
51 STATISTIC(NumDeleted ,
"Number of globals deleted");
52 STATISTIC(NumFnDeleted ,
"Number of functions deleted");
53 STATISTIC(NumGlobUses ,
"Number of global uses devirtualized");
54 STATISTIC(NumLocalized ,
"Number of globals localized");
55 STATISTIC(NumShrunkToBool ,
"Number of global vars shrunk to booleans");
56 STATISTIC(NumFastCallFns ,
"Number of functions converted to fastcc");
57 STATISTIC(NumCtorsEvaluated,
"Number of static ctors evaluated");
58 STATISTIC(NumNestRemoved ,
"Number of nest attributes removed");
59 STATISTIC(NumAliasesResolved,
"Number of global aliases resolved");
60 STATISTIC(NumAliasesRemoved,
"Number of global aliases eliminated");
61 STATISTIC(NumCXXDtorsRemoved,
"Number of global C++ destructors removed");
73 bool runOnModule(
Module &M);
77 bool OptimizeFunctions(
Module &M);
78 bool OptimizeGlobalVars(
Module &M);
79 bool OptimizeGlobalAliases(
Module &M);
84 bool OptimizeEmptyGlobalCXXDtors(
Function *CXAAtExitFn);
93 "Global Variable Optimizer",
false,
false)
135 if (isa<PointerType>(InnerTy))
return true;
136 if (isa<CompositeType>(InnerTy))
142 if (--Limit == 0)
return true;
143 }
while (!Types.
empty());
152 if (isa<Constant>(V))
156 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
166 if (!GEP->hasAllConstantIndices())
191 bool Changed =
false;
201 if (
StoreInst *SI = dyn_cast<StoreInst>(U)) {
202 Value *V = SI->getValueOperand();
203 if (isa<Constant>(V)) {
205 SI->eraseFromParent();
210 }
else if (
MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
211 if (isa<Constant>(MSI->getValue())) {
213 MSI->eraseFromParent();
214 }
else if (
Instruction *
I = dyn_cast<Instruction>(MSI->getValue())) {
222 MTI->eraseFromParent();
223 }
else if (
Instruction *
I = dyn_cast<Instruction>(MemSrc)) {
227 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
228 if (CE->use_empty()) {
229 CE->destroyConstant();
232 }
else if (
Constant *
C = dyn_cast<Constant>(U)) {
234 C->destroyConstant();
243 for (
int i = 0, e = Dead.
size(); i != e; ++i) {
245 Dead[i].second->eraseFromParent();
269 bool Changed =
false;
271 while (!WorkList.empty()) {
272 User *U = WorkList.pop_back_val();
277 LI->replaceAllUsesWith(Init);
278 LI->eraseFromParent();
281 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(U)) {
283 SI->eraseFromParent();
285 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
286 if (CE->getOpcode() == Instruction::GetElementPtr) {
291 }
else if (CE->getOpcode() == Instruction::BitCast &&
292 CE->getType()->isPointerTy()) {
297 if (CE->use_empty()) {
298 CE->destroyConstant();
306 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
309 if (Init && CE && CE->
getOpcode() == Instruction::GetElementPtr)
315 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
320 if (GEP->use_empty()) {
321 GEP->eraseFromParent();
325 if (
MI->getRawDest() == V) {
326 MI->eraseFromParent();
330 }
else if (
Constant *
C = dyn_cast<Constant>(U)) {
334 C->destroyConstant();
351 if (!I)
return false;
354 if (isa<LoadInst>(I))
return true;
357 if (
StoreInst *SI = dyn_cast<StoreInst>(I))
362 if (GEPI == 0)
return false;
365 !cast<Constant>(GEPI->
getOperand(1))->isNullValue())
381 if (!isa<GetElementPtrInst>(U) &&
382 (!isa<ConstantExpr>(U) ||
383 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
391 !cast<Constant>(U->
getOperand(1))->isNullValue() ||
399 if (
ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
400 uint64_t NumElements = AT->getNumElements();
419 uint64_t NumElements;
420 if (
ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
421 NumElements = SubArrayTy->getNumElements();
422 else if (
VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
423 NumElements = SubVectorTy->getNumElements();
425 assert((*GEPI)->isStructTy() &&
426 "Indexed GEP type is not array, vector, or struct!");
467 Type *Ty = Init->getType();
469 std::vector<GlobalVariable*> NewGlobals;
474 if (StartAlignment == 0)
477 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
478 NewGlobals.reserve(STy->getNumElements());
480 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
482 assert(In &&
"Couldn't get element of initializer?");
489 NewGlobals.push_back(NGV);
500 unsigned NumElements = 0;
501 if (
ArrayType *ATy = dyn_cast<ArrayType>(STy))
502 NumElements = ATy->getNumElements();
504 NumElements = cast<VectorType>(STy)->getNumElements();
508 NewGlobals.reserve(NumElements);
512 for (
unsigned i = 0, e = NumElements; i != e; ++i) {
514 assert(In &&
"Couldn't get element of initializer?");
522 NewGlobals.push_back(NGV);
528 if (NewAlign > EltAlign)
533 if (NewGlobals.empty())
536 DEBUG(
dbgs() <<
"PERFORMING GLOBAL SRA ON: " << *GV);
544 assert(((isa<ConstantExpr>(GEP) &&
545 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
546 isa<GetElementPtrInst>(GEP)) &&
"NonGEP CE's are not SRAable!");
551 unsigned Val = cast<ConstantInt>(GEP->
getOperand(2))->getZExtValue();
552 if (Val >= NewGlobals.size()) Val = 0;
554 Value *NewPtr = NewGlobals[Val];
561 for (
unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
577 GEPI->eraseFromParent();
579 cast<ConstantExpr>(GEP)->destroyConstant();
589 unsigned FirstGlobal = 0;
590 for (
unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
591 if (NewGlobals[i]->use_empty()) {
592 Globals.
erase(NewGlobals[i]);
593 if (FirstGlobal == i) ++FirstGlobal;
596 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
608 if (isa<LoadInst>(U)) {
610 }
else if (
const StoreInst *SI = dyn_cast<StoreInst>(U)) {
611 if (SI->getOperand(0) == V) {
615 }
else if (
const CallInst *CI = dyn_cast<CallInst>(U)) {
616 if (CI->getCalledValue() != V) {
620 }
else if (
const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
621 if (II->getCalledValue() != V) {
625 }
else if (
const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
629 }
else if (
const PHINode *PN = dyn_cast<PHINode>(U)) {
634 }
else if (isa<ICmpInst>(U) &&
635 isa<ConstantPointerNull>(UI->getOperand(1))) {
653 if (
const LoadInst *
LI = dyn_cast<LoadInst>(U)) {
657 }
else if (isa<StoreInst>(U)) {
669 bool Changed =
false;
673 LI->setOperand(0, NewV);
675 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
676 if (SI->getOperand(1) == V) {
677 SI->setOperand(1, NewV);
680 }
else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
687 bool PassedAsArg =
false;
688 for (
unsigned i = 0, e = CS.
arg_size(); i != e; ++i)
699 }
else if (
CastInst *CI = dyn_cast<CastInst>(I)) {
703 if (CI->use_empty()) {
705 CI->eraseFromParent();
710 Idxs.
reserve(GEPI->getNumOperands()-1);
713 if (
Constant *
C = dyn_cast<Constant>(*i))
717 if (Idxs.
size() == GEPI->getNumOperands()-1)
720 if (GEPI->use_empty()) {
722 GEPI->eraseFromParent();
738 bool Changed =
false;
742 bool AllNonStoreUsesGone =
true;
746 User *GlobalUser = *GUI++;
747 if (
LoadInst *
LI = dyn_cast<LoadInst>(GlobalUser)) {
750 if (
LI->use_empty()) {
751 LI->eraseFromParent();
754 AllNonStoreUsesGone =
false;
756 }
else if (isa<StoreInst>(GlobalUser)) {
759 "Must be storing *to* the global");
761 AllNonStoreUsesGone =
false;
765 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
766 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
767 isa<BitCastInst>(GlobalUser) ||
768 isa<GetElementPtrInst>(GlobalUser)) &&
769 "Only expect load and stores!");
774 DEBUG(
dbgs() <<
"OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
780 if (AllNonStoreUsesGone) {
788 DEBUG(
dbgs() <<
" *** GLOBAL NOW DEAD!\n");
804 I->replaceAllUsesWith(NewC);
808 while (UI != E && *UI ==
I)
810 I->eraseFromParent();
825 DEBUG(
errs() <<
"PROMOTING GLOBAL: " << *GV <<
" CALL = " << *CI <<
'\n');
829 GlobalType = AllocTy;
850 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
851 if (BCI->getType() == NewGV->getType()) {
853 BCI->eraseFromParent();
855 BCI->setOperand(0, NewGV);
873 GlobalValue::InternalLinkage,
876 bool InitBoolUsed =
false;
883 SI->getOrdering(), SI->getSynchScope(), SI);
891 if (!isa<ICmpInst>(LoadUse.
getUser())) {
930 cast<StoreInst>(InitBool->
use_back())->eraseFromParent();
943 if (RepValue != NewGV)
960 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
964 if (
const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
965 if (SI->getOperand(0) == V && SI->
getOperand(1) != GV)
971 if (isa<GetElementPtrInst>(Inst) && Inst->
getNumOperands() >= 3) {
977 if (
const PHINode *PN = dyn_cast<PHINode>(Inst)) {
986 if (
const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
1007 if (
StoreInst *SI = dyn_cast<StoreInst>(U)) {
1009 if (SI->getOperand(1) == GV) {
1013 }
else if (
PHINode *PN = dyn_cast<PHINode>(U)) {
1016 InsertPt = PN->getIncomingBlock(Alloc->
use_begin())->getTerminator();
1017 }
else if (isa<BitCastInst>(U)) {
1025 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1026 if (
StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1027 if (SI->getOperand(1) == GV) {
1031 GEPI->eraseFromParent();
1055 if (
const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1056 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1064 if (GEPI->getNumOperands() < 3)
1071 if (
const PHINode *PN = dyn_cast<PHINode>(User)) {
1072 if (!LoadUsingPHIsPerLoad.
insert(PN))
1076 if (!LoadUsingPHIs.
insert(PN))
1082 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1104 if (
const LoadInst *
LI = dyn_cast<LoadInst>(*UI)) {
1106 LoadUsingPHIsPerLoad))
1108 LoadUsingPHIsPerLoad.
clear();
1117 , E = LoadUsingPHIs.
end();
I != E; ++
I) {
1123 if (InVal == StoredVal)
continue;
1125 if (
const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1127 if (LoadUsingPHIs.
count(InPN))
1133 if (
const LoadInst *
LI = dyn_cast<LoadInst>(InVal))
1134 if (
LI->getOperand(0) == GV)
1148 DenseMap<
Value*, std::vector<Value*> > &InsertedScalarizedValues,
1149 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1150 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1152 if (FieldNo >= FieldVals.size())
1153 FieldVals.resize(FieldNo+1);
1157 if (
Value *FieldVal = FieldVals[FieldNo])
1166 InsertedScalarizedValues,
1169 }
else if (
PHINode *PN = dyn_cast<PHINode>(V)) {
1172 StructType *
ST = cast<StructType>(PN->getType()->getPointerElementType());
1176 PN->getNumIncomingValues(),
1177 PN->getName()+
".f"+
Twine(FieldNo), PN);
1179 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1184 return FieldVals[FieldNo] = Result;
1190 DenseMap<
Value*, std::vector<Value*> > &InsertedScalarizedValues,
1191 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1193 if (
ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1194 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1198 InsertedScalarizedValues, PHIsToRewrite);
1204 SCI->eraseFromParent();
1210 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1211 &&
"Unexpected GEPI!");
1214 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1216 InsertedScalarizedValues, PHIsToRewrite);
1221 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1226 GEPI->eraseFromParent();
1236 PHINode *PN = cast<PHINode>(LoadUser);
1237 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1238 std::vector<Value*>())).second)
1254 DenseMap<
Value*, std::vector<Value*> > &InsertedScalarizedValues,
1255 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1264 InsertedScalarizedValues.erase(Load);
1273 DEBUG(
dbgs() <<
"SROA HEAP ALLOC: " << *GV <<
" MALLOC = " << *CI <<
'\n');
1285 std::vector<Value*> FieldGlobals;
1286 std::vector<Value*> FieldMallocs;
1288 for (
unsigned FieldNo = 0, e = STy->
getNumElements(); FieldNo != e;++FieldNo){
1298 FieldGlobals.push_back(NGV);
1308 FieldMallocs.push_back(NMI);
1327 ConstantZero,
"isneg");
1328 for (
unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1332 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond,
"tmp", CI);
1352 for (
unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1353 Value *GVVal =
new LoadInst(FieldGlobals[i],
"tmp", NullPtrBlock);
1369 NullPtrBlock = NextBlock;
1381 InsertedScalarizedValues[GV] = FieldGlobals;
1383 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1391 if (
LoadInst *
LI = dyn_cast<LoadInst>(User)) {
1398 assert(isa<ConstantPointerNull>(SI->
getOperand(0)) &&
1399 "Unexpected heap-sra user!");
1402 for (
unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1403 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1405 new StoreInst(Null, FieldGlobals[i], SI);
1412 while (!PHIsToRewrite.empty()) {
1413 PHINode *PN = PHIsToRewrite.back().first;
1414 unsigned FieldNo = PHIsToRewrite.back().second;
1415 PHIsToRewrite.pop_back();
1416 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1430 I = InsertedScalarizedValues.
begin(), E = InsertedScalarizedValues.
end();
1432 if (
PHINode *PN = dyn_cast<PHINode>(
I->first))
1433 PN->dropAllReferences();
1434 else if (
LoadInst *
LI = dyn_cast<LoadInst>(
I->first))
1435 LI->dropAllReferences();
1440 I = InsertedScalarizedValues.
begin(), E = InsertedScalarizedValues.
end();
1442 if (
PHINode *PN = dyn_cast<PHINode>(
I->first))
1443 PN->eraseFromParent();
1444 else if (
LoadInst *
LI = dyn_cast<LoadInst>(
I->first))
1445 LI->eraseFromParent();
1452 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();
1538 AllocSize, NumElements,
1543 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1544 CI = cast<CallInst>(BCI->getOperand(0));
1546 CI = cast<CallInst>(Malloc);
1572 if (
Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1612 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1616 DEBUG(
dbgs() <<
" *** SHRINKING TO BOOL: " << *GV);
1630 "No reason to shrink to bool!");
1634 bool IsOneZero =
false;
1635 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1636 IsOneZero = InitVal->
isNullValue() && CI->isOne();
1640 if (
StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1642 bool StoringOther = SI->
getOperand(0) == OtherVal;
1645 if (StoringOther || SI->getOperand(0) == InitVal) {
1652 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1657 if (
LoadInst *
LI = dyn_cast<LoadInst>(StoredVal)) {
1658 assert(
LI->getOperand(0) == GV &&
"Not a copy!");
1660 StoreVal =
new LoadInst(NewGV,
LI->getName()+
".b",
false, 0,
1661 LI->getOrdering(),
LI->getSynchScope(),
LI);
1663 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1664 "This is not a form that we understand!");
1666 assert(isa<LoadInst>(StoreVal) &&
"Not a load of NewGV!");
1669 new StoreInst(StoreVal, NewGV,
false, 0,
1670 SI->getOrdering(), SI->getSynchScope(), SI);
1706 DEBUG(
dbgs() <<
"GLOBAL DEAD: " << *GV);
1728 return ProcessInternalGlobal(GV, GVI, GS);
1750 DEBUG(
dbgs() <<
"LOCALIZING GLOBAL: " << *GV);
1768 DEBUG(
dbgs() <<
"GLOBAL NEVER LOADED: " << *GV);
1789 DEBUG(
dbgs() <<
"MARKING CONSTANT: " << *GV <<
"\n");
1797 DEBUG(
dbgs() <<
" *** Marking constant allowed us to simplify "
1798 <<
"all users and delete global!\n");
1806 if (
DataLayout *
TD = getAnalysisIfAvailable<DataLayout>())
1825 DEBUG(
dbgs() <<
" *** Substituting initializer allowed us to "
1826 <<
"simplify all users and delete global!\n");
1861 if (isa<BlockAddress>(*UI))
1869 for (
unsigned i = 0, e = Attrs.
getNumSlots(); i != e; ++i) {
1884 if (isa<BlockAddress>(*UI))
1891 bool GlobalOpt::OptimizeFunctions(
Module &M) {
1892 bool Changed =
false;
1929 bool GlobalOpt::OptimizeGlobalVars(
Module &M) {
1930 bool Changed =
false;
1941 if (New && New != CE)
1945 Changed |= ProcessGlobal(GV, GVI);
1954 if (GV == 0)
return 0;
1965 if (isa<ConstantAggregateZero>(*i))
1968 if (isa<ConstantPointerNull>(CS->
getOperand(1)))
1988 return std::vector<Function*>();
1990 std::vector<Function*> Result;
1994 Result.push_back(dyn_cast<Function>(CS->
getOperand(1)));
2002 const std::vector<Function*> &Ctors) {
2012 std::vector<Constant*> CAList;
2013 for (
unsigned i = 0, e = Ctors.size(); i != e; ++i) {
2015 CSVals[1] = Ctors[i];
2029 CAList.size()), CAList);
2080 isa<GlobalValue>(C))
2084 if (isa<ConstantArray>(C) || isa<ConstantStruct>(
C) ||
2085 isa<ConstantVector>(C)) {
2099 case Instruction::BitCast:
2103 case Instruction::IntToPtr:
2104 case Instruction::PtrToInt:
2113 case Instruction::GetElementPtr:
2119 case Instruction::Add:
2133 if (!SimpleConstants.
insert(C))
return true;
2147 if (!cast<PointerType>(C->
getType())->getElementType()->isSingleValueType())
2157 if (CE->getOpcode() == Instruction::GetElementPtr &&
2158 isa<GlobalVariable>(CE->getOperand(0)) &&
2159 cast<GEPOperator>(CE)->isInBounds()) {
2168 if (!CI || !CI->
isZero())
return false;
2172 if (!CE->isGEPWithNoNotionalOverIndexing())
2180 }
else if (CE->getOpcode() == Instruction::BitCast &&
2181 isa<GlobalVariable>(CE->getOperand(0))) {
2184 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
2205 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2211 assert(Idx < STy->getNumElements() &&
"Struct index out of range!");
2222 if (
ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2223 NumElts = ATy->getNumElements();
2228 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2263 : TD(TD), TLI(TLI) {
2269 while (!AllocaTmps.empty()) {
2271 AllocaTmps.pop_back();
2294 if (
Constant *CV = dyn_cast<Constant>(V))
return CV;
2295 Constant *R = ValueStack.back()->lookup(V);
2296 assert(R &&
"Reference to an uncomputed value!");
2301 ValueStack.back()->operator[](V) = C;
2305 return MutatedMemory;
2356 if (I != MutatedMemory.
end())
return I->second;
2367 if (CE->getOpcode() == Instruction::GetElementPtr &&
2368 isa<GlobalVariable>(CE->getOperand(0))) {
2386 DEBUG(
dbgs() <<
"Evaluating Instruction: " << *CurInst <<
"\n");
2388 if (
StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2389 if (!SI->isSimple()) {
2390 DEBUG(
dbgs() <<
"Store is not simple! Can not evaluate.\n");
2393 Constant *Ptr = getVal(SI->getOperand(1));
2395 DEBUG(
dbgs() <<
"Folding constant ptr expression: " << *Ptr);
2397 DEBUG(
dbgs() <<
"; To: " << *Ptr <<
"\n");
2401 DEBUG(
dbgs() <<
"Pointer is too complex for us to evaluate store.");
2405 Constant *Val = getVal(SI->getOperand(0));
2410 DEBUG(
dbgs() <<
"Store value is too complex to evaluate store. " << *Val
2416 if (CE->getOpcode() == Instruction::BitCast) {
2417 DEBUG(
dbgs() <<
"Attempting to resolve bitcast on constant ptr.\n");
2423 Type *NewTy = cast<PointerType>(Ptr->
getType())->getElementType();
2432 if (
StructType *STy = dyn_cast<StructType>(NewTy)) {
2433 NewTy = STy->getTypeAtIndex(0U);
2437 Constant *
const IdxList[] = {IdxZero, IdxZero};
2446 DEBUG(
dbgs() <<
"Failed to bitcast constant ptr, can not "
2456 DEBUG(
dbgs() <<
"Evaluated bitcast: " << *Val <<
"\n");
2460 MutatedMemory[Ptr] = Val;
2461 }
else if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2463 getVal(BO->getOperand(0)),
2464 getVal(BO->getOperand(1)));
2465 DEBUG(
dbgs() <<
"Found a BinaryOperator! Simplifying: " << *InstResult
2467 }
else if (
CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2471 DEBUG(
dbgs() <<
"Found a CmpInst! Simplifying: " << *InstResult
2473 }
else if (
CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2477 DEBUG(
dbgs() <<
"Found a Cast! Simplifying: " << *InstResult
2479 }
else if (
SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2481 getVal(SI->getOperand(1)),
2482 getVal(SI->getOperand(2)));
2483 DEBUG(
dbgs() <<
"Found a Select! Simplifying: " << *InstResult
2486 Constant *P = getVal(GEP->getOperand(0));
2493 cast<GEPOperator>(GEP)->isInBounds());
2494 DEBUG(
dbgs() <<
"Found a GEP! Simplifying: " << *InstResult
2496 }
else if (
LoadInst *
LI = dyn_cast<LoadInst>(CurInst)) {
2498 if (!
LI->isSimple()) {
2499 DEBUG(
dbgs() <<
"Found a Load! Not a simple load, can not evaluate.\n");
2506 DEBUG(
dbgs() <<
"Found a constant pointer expression, constant "
2507 "folding: " << *Ptr <<
"\n");
2509 InstResult = ComputeLoadResult(Ptr);
2510 if (InstResult == 0) {
2511 DEBUG(
dbgs() <<
"Failed to compute load result. Can not evaluate load."
2516 DEBUG(
dbgs() <<
"Evaluated load: " << *InstResult <<
"\n");
2517 }
else if (
AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2518 if (AI->isArrayAllocation()) {
2519 DEBUG(
dbgs() <<
"Found an array alloca. Can not evaluate.\n");
2522 Type *Ty = AI->getType()->getElementType();
2527 InstResult = AllocaTmps.back();
2528 DEBUG(
dbgs() <<
"Found an alloca. Result: " << *InstResult <<
"\n");
2529 }
else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2533 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
2534 DEBUG(
dbgs() <<
"Ignoring debug info.\n");
2540 if (isa<InlineAsm>(CS.getCalledValue())) {
2541 DEBUG(
dbgs() <<
"Found inline asm, can not evaluate.\n");
2545 if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2546 if (
MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2547 if (MSI->isVolatile()) {
2548 DEBUG(
dbgs() <<
"Can not optimize a volatile memset " <<
2552 Constant *Ptr = getVal(MSI->getDest());
2553 Constant *Val = getVal(MSI->getValue());
2554 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
2555 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2557 DEBUG(
dbgs() <<
"Ignoring no-op memset.\n");
2565 DEBUG(
dbgs() <<
"Ignoring lifetime intrinsic.\n");
2573 if (!II->use_empty()) {
2574 DEBUG(
dbgs() <<
"Found unused invariant_start. Cant evaluate.\n");
2577 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
2578 Value *PtrArg = getVal(II->getArgOperand(1));
2581 Type *ElemTy = cast<PointerType>(GV->
getType())->getElementType();
2585 Invariants.insert(GV);
2586 DEBUG(
dbgs() <<
"Found a global var that is an invariant: " << *GV
2589 DEBUG(
dbgs() <<
"Found a global var, but can not treat it as an "
2598 DEBUG(
dbgs() <<
"Unknown intrinsic. Can not evaluate.\n");
2605 DEBUG(
dbgs() <<
"Can not resolve function pointer.\n");
2617 DEBUG(
dbgs() <<
"Constant folded function call. Result: " <<
2618 *InstResult <<
"\n");
2620 DEBUG(
dbgs() <<
"Can not constant fold function call.\n");
2625 DEBUG(
dbgs() <<
"Can not constant fold vararg function call.\n");
2632 if (!EvaluateFunction(Callee, RetVal, Formals)) {
2633 DEBUG(
dbgs() <<
"Failed to evaluate function.\n");
2636 delete ValueStack.pop_back_val();
2637 InstResult = RetVal;
2639 if (InstResult != NULL) {
2640 DEBUG(
dbgs() <<
"Successfully evaluated function. Result: " <<
2641 InstResult <<
"\n\n");
2643 DEBUG(
dbgs() <<
"Successfully evaluated function. Result: 0\n\n");
2646 }
else if (isa<TerminatorInst>(CurInst)) {
2647 DEBUG(
dbgs() <<
"Found a terminator instruction.\n");
2649 if (
BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2650 if (BI->isUnconditional()) {
2651 NextBB = BI->getSuccessor(0);
2655 if (!Cond)
return false;
2659 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2662 if (!Val)
return false;
2663 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
2664 }
else if (
IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2665 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
2667 NextBB = BA->getBasicBlock();
2670 }
else if (isa<ReturnInst>(CurInst)) {
2674 DEBUG(
dbgs() <<
"Can not handle terminator.");
2679 DEBUG(
dbgs() <<
"Successfully evaluated block.\n");
2683 DEBUG(
dbgs() <<
"Failed to evaluate block due to unhandled instruction."
2688 if (!CurInst->use_empty()) {
2689 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2692 setVal(CurInst, InstResult);
2696 if (
InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2697 NextBB = II->getNormalDest();
2698 DEBUG(
dbgs() <<
"Found an invoke instruction. Finished Block.\n\n");
2714 if (std::find(CallStack.begin(), CallStack.end(),
F) != CallStack.end())
2717 CallStack.push_back(F);
2723 setVal(AI, ActualArgs[ArgNo]);
2737 DEBUG(
dbgs() <<
"Trying to evaluate BB: " << *CurBB <<
"\n");
2739 if (!EvaluateBlock(CurInst, NextBB))
2748 CallStack.pop_back();
2755 if (!ExecutedBlocks.
insert(NextBB))
2762 for (CurInst = NextBB->
begin();
2778 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2783 DEBUG(
dbgs() <<
"FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2784 << F->
getName() <<
"' to " << Eval.getMutatedMemory().size()
2787 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
2791 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2793 (*I)->setConstant(
true);
2803 bool MadeChange =
false;
2804 if (Ctors.empty())
return false;
2807 for (
unsigned i = 0; i != Ctors.size(); ++i) {
2812 if (i != Ctors.size()-1) {
2818 DEBUG(
dbgs() <<
"Optimizing Global Constructor: " << *F <<
"\n");
2821 if (F->
empty())
continue;
2825 Ctors.erase(Ctors.begin()+i);
2828 ++NumCtorsEvaluated;
2833 if (!MadeChange)
return false;
2840 return (*A)->getName().compare((*B)->getName());
2886 iterator usedBegin() {
return Used.begin(); }
2887 iterator usedEnd() {
return Used.end(); }
2888 iterator compilerUsedBegin() {
return CompilerUsed.begin(); }
2889 iterator compilerUsedEnd() {
return CompilerUsed.end(); }
2890 bool usedCount(
GlobalValue *GV)
const {
return Used.count(GV); }
2892 return CompilerUsed.count(GV);
2894 bool usedErase(
GlobalValue *GV) {
return Used.erase(GV); }
2895 bool compilerUsedErase(
GlobalValue *GV) {
return CompilerUsed.erase(GV); }
2896 bool usedInsert(
GlobalValue *GV) {
return Used.insert(GV); }
2897 bool compilerUsedInsert(
GlobalValue *GV) {
return CompilerUsed.insert(GV); }
2899 void syncVariablesAndSets() {
2912 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2913 "We should have removed the duplicated "
2914 "element from llvm.compiler.used");
2921 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
2925 const LLVMUsed &U) {
2927 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2928 "We should have removed the duplicated "
2929 "element from llvm.compiler.used");
2930 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2939 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2943 RenameTarget =
false;
2969 RenameTarget =
true;
2973 bool GlobalOpt::OptimizeGlobalAliases(
Module &M) {
2974 bool Changed =
false;
2980 Used.compilerUsedErase(*I);
2986 if (!J->hasName() && !J->isDeclaration())
2989 if (J->mayBeOverridden())
2992 Constant *Aliasee = J->getAliasee();
3001 J->replaceAllUsesWith(Aliasee);
3002 ++NumAliasesResolved;
3009 Target->GlobalValue::copyAttributesFrom(J);
3011 if (Used.usedErase(J))
3012 Used.usedInsert(Target);
3014 if (Used.compilerUsedErase(J))
3015 Used.compilerUsedInsert(Target);
3021 ++NumAliasesRemoved;
3025 Used.syncVariablesAndSets();
3072 if (
const CallInst *CI = dyn_cast<CallInst>(I)) {
3074 if (isa<DbgInfoIntrinsic>(CI))
3077 const Function *CalledFn = CI->getCalledFunction();
3085 if (!NewCalledFunctions.
insert(CalledFn))
3090 }
else if (isa<ReturnInst>(*I))
3092 else if (I->mayHaveSideEffects())
3099 bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(
Function *CXAAtExitFn) {
3114 bool Changed =
false;
3117 E = CXAAtExitFn->
use_end(); I != E;) {
3138 ++NumCXXDtorsRemoved;
3146 bool GlobalOpt::runOnModule(
Module &M) {
3147 bool Changed =
false;
3149 TD = getAnalysisIfAvailable<DataLayout>();
3150 TLI = &getAnalysis<TargetLibraryInfo>();
3155 bool LocalChange =
true;
3156 while (LocalChange) {
3157 LocalChange =
false;
3160 LocalChange |= OptimizeFunctions(M);
3164 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
3167 LocalChange |= OptimizeGlobalVars(M);
3170 LocalChange |= OptimizeGlobalAliases(M);
3176 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3178 Changed |= LocalChange;
static GlobalVariable * OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy, ConstantInt *NElements, DataLayout *TD, TargetLibraryInfo *TLI)
bool isDefTriviallyDead() const
void DeleteContainerPointers(Container &C)
void push_back(const T &Elt)
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...
LinkageTypes getLinkage() const
static ConstantInt * getFalse(LLVMContext &Context)
IntegerType * getType() const
Abstract base class of comparison instructions.
static bool isLeakCheckerRoot(GlobalVariable *GV)
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
Special purpose, only applies to global arrays.
static PassRegistry * getPassRegistry()
LLVMContext & getContext() const
const Function * AccessingFunction
const AttributeSet & getAttributes() const
ThreadLocalMode getThreadLocalMode() const
static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI)
Constant * ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE)
The main container class for the LLVM Intermediate Representation.
unsigned getNumParams() const
unsigned getAlignment() const
static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, CallInst *CI, Type *AllocTy, AtomicOrdering Ordering, Module::global_iterator &GVI, DataLayout *TD, TargetLibraryInfo *TLI)
INITIALIZE_PASS_BEGIN(GlobalOpt,"globalopt","Global Variable Optimizer", false, false) INITIALIZE_PASS_END(GlobalOpt
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=0)
static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, GlobalVariable *GV)
unsigned arg_size() const
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
This class represents zero extension of integer types.
const GlobalListType & getGlobalList() const
Get the Module's list of global variables (constant).
unsigned getNumOperands() const
Nested function static chain.
static Constant * getGetElementPtr(Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false)
static bool isSafeSROAElementUse(Value *V)
void setCalledFunction(Value *V)
static std::vector< Function * > ParseGlobalCtors(GlobalVariable *GV)
gep_type_iterator gep_type_end(const User *GEP)
bool mayHaveSideEffects() const
static Constant * EvaluateStoreInto(Constant *Init, Constant *Val, ConstantExpr *Addr, unsigned OpNo)
bool HasMultipleAccessingFunctions
void setArgument(unsigned ArgNo, Value *newVal)
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
void setSection(StringRef S)
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
static Instruction * CreateFree(Value *Source, Instruction *InsertBefore)
CreateFree - Generate the IR for a call to the builtin free function.
const Constant * getInitializer() const
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
const AliasListType & getAliasList() const
Get the Module's list of aliases (constant).
const Constant * getAliasee() const
unsigned getOpcode() const
getOpcode - Return the opcode at the root of this constant expression
const GlobalVariable * getGlobalVariable(StringRef Name, bool AllowInternal=false) const
LoopInfoBase< BlockT, LoopT > * LI
ValTy * getArgument(unsigned ArgNo) const
CallingConv::ID getCallingConv() const
static int compareNames(Constant *const *A, Constant *const *B)
static Constant * getNullValue(Type *Ty)
StringRef getName() const
bool isSingleValueType() const
element_iterator element_end() const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
AttributeSet removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Attr) const
Remove the specified attribute at the specified index from this attribute list. Since attribute lists...
static void ConstantPropUsersOf(Value *V, DataLayout *TD, TargetLibraryInfo *TLI)
static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV)
Type::subtype_iterator element_iterator
const StructLayout * getStructLayout(StructType *Ty) const
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0)
Base class of casting instructions.
const APInt & getValue() const
Return the constant's value.
void setInitializer(Constant *InitVal)
bool has(LibFunc::Func F) const
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
#define llvm_unreachable(msg)
Type * getArrayElementType() const
void initializeGlobalOptPass(PassRegistry &)
static bool AllUsesOfValueWillTrapIfNull(const Value *V, SmallPtrSet< const PHINode *, 8 > &PHIs)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
bool canLosslesslyBitCastTo(Type *Ty) const
Determine if this type could be losslessly bitcast to Ty.
static Constant * get(ArrayRef< Constant * > V)
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=0)
static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV, DataLayout *TD, TargetLibraryInfo *TLI)
StoredType
Keep track of what stores to the global look like.
element_iterator element_begin() const
bool HasNonInstructionUser
bool hasUniqueInitializer() const
ID
LLVM Calling Convention Representation.
static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U)
int __cxa_atexit(void (*f)(void *), void *p, void *d);
static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal)
static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U)
bool hasPrivateLinkage() const
SynchronizationScope getSynchScope() const
uint64_t getZExtValue() const
Return the zero extended value.
global_iterator global_begin()
LLVMContext & getContext() const
getContext - Return the LLVMContext in which this type was uniqued.
bool count(PtrType Ptr) const
count - Return true if the specified pointer is in the set.
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
static GlobalVariable * PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI, Value *NElems, DataLayout *TD, const TargetLibraryInfo *TLI)
static void ChangeCalleesToFastCall(Function *F)
static Function * FindCXAAtExit(Module &M, TargetLibraryInfo *TLI)
static void RewriteHeapSROALoadUser(Instruction *LoadUser, DenseMap< Value *, std::vector< Value * > > &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned > > &PHIsToRewrite)
Constant * ConstantFoldConstantExpression(const ConstantExpr *CE, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0)
This class represents a no-op cast from one type to another.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0)
bool isFloatingPointTy() const
ValTy * getCalledValue() const
bool hasDefinitiveInitializer() const
void replaceAllUsesWith(Value *V)
aa Exhaustive Alias Analysis Precision Evaluator
Type * getElementType() const
unsigned getNumIncomingValues() const
bool hasAddressTaken(const User **=0) const
void replaceUsesOfWith(Value *From, Value *To)
static bool isSimpleEnoughValueToCommitHelper(Constant *C, SmallPtrSet< Constant *, 8 > &SimpleConstants, const DataLayout *TD)
Function * getFunction(StringRef Name) const
Constant * ConstantFoldCall(Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=0)
uint64_t getElementOffset(unsigned Idx) const
void setCallingConv(CallingConv::ID CC)
unsigned getNumSlots() const
Return the number of slots used in this attribute list. This is the number of arguments that have an ...
Type * getParamType(unsigned i) const
Parameter type accessors.
void array_pod_sort(IteratorTy Start, IteratorTy End)
* if(!EatIfPresent(lltok::kw_thread_local)) return false
alias_iterator alias_end()
value_use_iterator< User > use_iterator
LLVM Basic Block Representation.
static bool mayBeOverridden(LinkageTypes Linkage)
AttributeSet getSlotAttributes(unsigned Slot) const
Return the attributes at the given slot.
Type * getElementType(unsigned N) const
const CallInst * extractMallocCall(const Value *I, const TargetLibraryInfo *TLI)
LLVM Constant Representation.
static Value * GetHeapSROAValue(Value *V, unsigned FieldNo, DenseMap< Value *, std::vector< Value * > > &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned > > &PHIsToRewrite)
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static bool isSimpleEnoughPointerToCommit(Constant *C)
virtual void eraseFromParent()
static void RemoveNestAttribute(Function *F)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=0)
static Type * getVoidTy(LLVMContext &C)
BasicBlock * getIncomingBlock(unsigned i) const
ItTy next(ItTy it, Dist n)
Represent an integer comparison operator.
iterator insert(iterator where, NodeTy *New)
static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD, const TargetLibraryInfo *TLI)
static bool isDiscardableIfUnused(LinkageTypes Linkage)
static bool cxxDtorIsEmpty(const Function &Fn, SmallPtrSet< const Function *, 8 > &CalledFunctions)
Value * getOperand(unsigned i) const
Integer representation type.
ModulePass * createGlobalOptimizerPass()
Predicate getPredicate() const
Return the predicate for this instruction.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
static bool analyzeGlobal(const Value *V, GlobalStatus &GS)
Constant * getAggregateElement(unsigned Elt) const
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV)
void setConstant(bool Val)
static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V, const LLVMUsed &U)
static UndefValue * get(Type *T)
bool isSafeToDestroyConstant(const Constant *C)
LLVMContext & getContext() const
All values hold a context through their type.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
virtual void removeFromParent()
iterator erase(iterator where)
global_iterator global_end()
static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget)
SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
unsigned getABITypeAlignment(Type *Ty) const
bool hasExternalLinkage() const
static IntegerType * get(LLVMContext &C, unsigned NumBits)
Get or create an IntegerType instance.
static Constant * getBitCast(Constant *C, Type *Ty)
Global Variable Optimizer
static bool CleanupConstantGlobalUsers(Value *V, Constant *Init, DataLayout *TD, TargetLibraryInfo *TLI)
static PointerType * getUnqual(Type *ElementType)
Class for constant integers.
static void CommitValueTo(Constant *Val, Constant *Addr)
Value * getIncomingValue(unsigned i) const
15: SIMD 'packed' format, or other vector type
uint64_t getTypeAllocSize(Type *Ty) const
unsigned getVectorNumElements() const
void setAlignment(unsigned Align)
void setUnnamedAddr(bool Val)
static void setUsedInitializer(GlobalVariable &V, SmallPtrSet< GlobalValue *, 8 > Init)
uint64_t getSizeInBytes() const
alias_iterator alias_begin()
Value * stripPointerCasts()
Strips off any unneeded pointer casts, all-zero GEPs and aliases from the specified value...
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs)
AtomicOrdering getOrdering() const
Returns the ordering effect of this fence.
static GetElementPtrInst * Create(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=0)
const BasicBlock & getEntryBlock() const
static ConstantInt * getTrue(LLVMContext &Context)
void setLinkage(LinkageTypes LT)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
bool isAllOnesValue() const
AttributeSet getAttributes() const
Return the attribute list for this Function.
Value * getArgOperand(unsigned i) const
static bool isSimpleEnoughValueToCommit(Constant *C, SmallPtrSet< Constant *, 8 > &SimpleConstants, const DataLayout *TD)
bool hasInitializer() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Type * getMallocAllocatedType(const CallInst *CI, const TargetLibraryInfo *TLI)
Value * getMallocArraySize(CallInst *CI, const DataLayout *DL, const TargetLibraryInfo *TLI, bool LookThroughSExt=false)
void setCallingConv(CallingConv::ID CC)
Value * getOperand() const
uint64_t MinAlign(uint64_t A, uint64_t B)
static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV, Instruction *StoredVal)
PointerType * getType() const
getType - Global values are always pointers.
static bool GlobalUsersSafeToSRA(GlobalValue *GV)
static GlobalVariable * SRAGlobal(GlobalVariable *GV, const DataLayout &TD)
StringRef getName(LibFunc::Func F) const
static IntegerType * getInt32Ty(LLVMContext &C)
bool IsCompared
True if the global's address is used in a comparison.
bool isDeclaration() const
static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V, SmallPtrSet< const PHINode *, 32 > &LoadUsingPHIs, SmallPtrSet< const PHINode *, 32 > &LoadUsingPHIsPerLoad)
bool hasAttrSomewhere(Attribute::AttrKind Attr) const
Return true if the specified attribute is set for at least one parameter or for the return value...
unsigned getSlotIndex(unsigned Slot) const
Return the index for the given slot.
AtomicOrdering Ordering
Set to the strongest atomic ordering requirement.
unsigned greater or equal
void setAttributes(const AttributeSet &PAL)
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
FunctionType * getFunctionType() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=0, BasicBlock *InsertBefore=0)
Creates a new BasicBlock.
GraphT::NodeType * Eval(DominatorTreeBase< typename GraphT::NodeType > &DT, typename GraphT::NodeType *VIn, unsigned LastLinked)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
Rename collisions when linking (static functions).
virtual void eraseFromParent()
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
uint64_t getTypeStoreSize(Type *Ty) const
void setAttributes(AttributeSet attrs)
Set the attribute list for this Function.
bool hasNUsesOrMore(unsigned N) const
static GlobalVariable * InstallGlobalCtors(GlobalVariable *GCL, const std::vector< Function * > &Ctors)
bool hasLocalLinkage() const
static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load, DenseMap< Value *, std::vector< Value * > > &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned > > &PHIsToRewrite)
Type * getReturnType() const
STATISTIC(NumMarked,"Number of globals marked constant")
LLVMContext & getContext() const
Get the context in which this basic block lives.
void removeDeadConstantUsers() const
static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, AtomicOrdering Ordering, Module::global_iterator &GVI, DataLayout *TD, TargetLibraryInfo *TLI)
LLVM Value Representation.
bool hasUnnamedAddr() const
static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV)
uint64_t getTypeSizeInBits(Type *Ty) const
static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V, const GlobalVariable *GV, SmallPtrSet< const PHINode *, 8 > &PHIs)
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2)
Return an ICmp or FCmp comparison operator constant expression.
static bool CleanupPointerRootUsers(GlobalVariable *GV, const TargetLibraryInfo *TLI)
GlobalVariable * collectUsedGlobalVariables(Module &M, SmallPtrSet< GlobalValue *, 8 > &Set, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
unsigned getNumElements() const
Random access to the elements.
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=0)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty)
const BasicBlock * getParent() const
INITIALIZE_PASS(GlobalMerge,"global-merge","Global Merge", false, false) bool GlobalMerge const DataLayout * TD
static Instruction * CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, Type *AllocTy, Value *AllocSize, Value *ArraySize=0, Function *MallocF=0, const Twine &Name="")
gep_type_iterator gep_type_begin(const User *GEP)