blob: db2d0b3535a7cb0aa896efc945ace002afa4cfc1 [file] [log] [blame]
Chris Lattner25db5802004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "globalopt"
17#include "llvm/Transforms/IPO.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
22#include "llvm/Pass.h"
23#include "llvm/Support/Debug.h"
Chris Lattner004e2502004-10-11 05:54:41 +000024#include "llvm/Target/TargetData.h"
25#include "llvm/Transforms/Utils/Local.h"
Chris Lattner25db5802004-10-07 04:16:33 +000026#include "llvm/ADT/Statistic.h"
Chris Lattnerabab0712004-10-08 17:32:09 +000027#include "llvm/ADT/StringExtras.h"
Chris Lattner25db5802004-10-07 04:16:33 +000028#include <set>
29#include <algorithm>
30using namespace llvm;
31
32namespace {
Chris Lattnerabab0712004-10-08 17:32:09 +000033 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
34 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
35 "into scalars");
Chris Lattner8e71c6a2004-10-16 18:09:00 +000036 Statistic<> NumSubstitute("globalopt",
37 "Number of globals with initializers stored into them");
Chris Lattnerabab0712004-10-08 17:32:09 +000038 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner25db5802004-10-07 04:16:33 +000039 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
Chris Lattnere42eb312004-10-10 23:14:11 +000040 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
Chris Lattner25db5802004-10-07 04:16:33 +000041
42 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000043 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
44 AU.addRequired<TargetData>();
45 }
46
Chris Lattner25db5802004-10-07 04:16:33 +000047 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000048
49 private:
50 bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000051 };
52
53 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
54}
55
56ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
57
58/// GlobalStatus - As we analyze each global, keep track of some information
59/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000060/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000061struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000062 /// isLoaded - True if the global is ever loaded. If the global isn't ever
63 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000064 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000065
66 /// StoredType - Keep track of what stores to the global look like.
67 ///
Chris Lattner25db5802004-10-07 04:16:33 +000068 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000069 /// NotStored - There is no store to this global. It can thus be marked
70 /// constant.
71 NotStored,
72
73 /// isInitializerStored - This global is stored to, but the only thing
74 /// stored is the constant it was initialized with. This is only tracked
75 /// for scalar globals.
76 isInitializerStored,
77
78 /// isStoredOnce - This global is stored to, but only its initializer and
79 /// one other value is ever stored to it. If this global isStoredOnce, we
80 /// track the value stored to it in StoredOnceValue below. This is only
81 /// tracked for scalar globals.
82 isStoredOnce,
83
84 /// isStored - This global is stored to by multiple values or something else
85 /// that we cannot track.
86 isStored
Chris Lattner25db5802004-10-07 04:16:33 +000087 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +000088
89 /// StoredOnceValue - If only one value (besides the initializer constant) is
90 /// ever stored to this global, keep track of what value it is.
91 Value *StoredOnceValue;
92
93 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
94 /// the global exist. Such users include GEP instruction with variable
95 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +000096 bool isNotSuitableForSRA;
97
Chris Lattner617f1a32004-10-07 21:30:30 +000098 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Chris Lattner25db5802004-10-07 04:16:33 +000099 isNotSuitableForSRA(false) {}
100};
101
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000102
103
104/// ConstantIsDead - Return true if the specified constant is (transitively)
105/// dead. The constant may be used by other constants (e.g. constant arrays and
106/// constant exprs) as long as they are dead, but it cannot be used by anything
107/// else.
108static bool ConstantIsDead(Constant *C) {
109 if (isa<GlobalValue>(C)) return false;
110
111 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
112 if (Constant *CU = dyn_cast<Constant>(*UI)) {
113 if (!ConstantIsDead(CU)) return false;
114 } else
115 return false;
116 return true;
117}
118
119
Chris Lattner25db5802004-10-07 04:16:33 +0000120/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
121/// structure. If the global has its address taken, return true to indicate we
122/// can't do anything with it.
123///
124static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
125 std::set<PHINode*> &PHIUsers) {
126 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
127 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
128 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
129 if (CE->getOpcode() != Instruction::GetElementPtr)
130 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000131 else if (!GS.isNotSuitableForSRA) {
132 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
133 // don't like < 3 operand CE's, and we don't like non-constant integer
134 // indices.
135 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
136 GS.isNotSuitableForSRA = true;
137 else {
138 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
139 if (!isa<ConstantInt>(CE->getOperand(i))) {
140 GS.isNotSuitableForSRA = true;
141 break;
142 }
143 }
144 }
145
Chris Lattner25db5802004-10-07 04:16:33 +0000146 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
147 if (isa<LoadInst>(I)) {
148 GS.isLoaded = true;
149 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000150 // Don't allow a store OF the address, only stores TO the address.
151 if (SI->getOperand(0) == V) return true;
152
Chris Lattner617f1a32004-10-07 21:30:30 +0000153 // If this is a direct store to the global (i.e., the global is a scalar
154 // value, not an aggregate), keep more specific information about
155 // stores.
156 if (GS.StoredType != GlobalStatus::isStored)
157 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattner28eeb732004-11-14 20:50:30 +0000158 Value *StoredVal = SI->getOperand(0);
159 if (StoredVal == GV->getInitializer()) {
160 if (GS.StoredType < GlobalStatus::isInitializerStored)
161 GS.StoredType = GlobalStatus::isInitializerStored;
162 } else if (isa<LoadInst>(StoredVal) &&
163 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
164 // G = G
Chris Lattner617f1a32004-10-07 21:30:30 +0000165 if (GS.StoredType < GlobalStatus::isInitializerStored)
166 GS.StoredType = GlobalStatus::isInitializerStored;
167 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
168 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattner28eeb732004-11-14 20:50:30 +0000169 GS.StoredOnceValue = StoredVal;
Chris Lattner617f1a32004-10-07 21:30:30 +0000170 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattner28eeb732004-11-14 20:50:30 +0000171 GS.StoredOnceValue == StoredVal) {
Chris Lattner617f1a32004-10-07 21:30:30 +0000172 // noop.
173 } else {
174 GS.StoredType = GlobalStatus::isStored;
175 }
176 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000177 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000178 }
Chris Lattner25db5802004-10-07 04:16:33 +0000179 } else if (I->getOpcode() == Instruction::GetElementPtr) {
180 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000181
182 // If the first two indices are constants, this can be SRA'd.
183 if (isa<GlobalVariable>(I->getOperand(0))) {
184 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
185 !cast<Constant>(I->getOperand(1))->isNullValue() ||
186 !isa<ConstantInt>(I->getOperand(2)))
187 GS.isNotSuitableForSRA = true;
188 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
189 if (CE->getOpcode() != Instruction::GetElementPtr ||
190 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
191 !isa<Constant>(I->getOperand(0)) ||
192 !cast<Constant>(I->getOperand(0))->isNullValue())
193 GS.isNotSuitableForSRA = true;
194 } else {
195 GS.isNotSuitableForSRA = true;
196 }
Chris Lattner25db5802004-10-07 04:16:33 +0000197 } else if (I->getOpcode() == Instruction::Select) {
198 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
199 GS.isNotSuitableForSRA = true;
200 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
201 // PHI nodes we can check just like select or GEP instructions, but we
202 // have to be careful about infinite recursion.
203 if (PHIUsers.insert(PN).second) // Not already visited.
204 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
205 GS.isNotSuitableForSRA = true;
206 } else if (isa<SetCondInst>(I)) {
207 GS.isNotSuitableForSRA = true;
208 } else {
209 return true; // Any other non-load instruction might take address!
210 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000211 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
212 // We might have a dead and dangling constant hanging off of here.
213 if (!ConstantIsDead(C))
214 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000215 } else {
216 // Otherwise must be a global or some other user.
217 return true;
218 }
219
220 return false;
221}
222
Chris Lattnerabab0712004-10-08 17:32:09 +0000223static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
224 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
225 if (!CI) return 0;
226 uint64_t IdxV = CI->getRawValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000227
Chris Lattnerabab0712004-10-08 17:32:09 +0000228 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
229 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
230 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
231 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
232 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
233 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000234 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000235 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
236 if (IdxV < STy->getNumElements())
237 return Constant::getNullValue(STy->getElementType(IdxV));
238 } else if (const SequentialType *STy =
239 dyn_cast<SequentialType>(Agg->getType())) {
240 return Constant::getNullValue(STy->getElementType());
241 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000242 } else if (isa<UndefValue>(Agg)) {
243 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
244 if (IdxV < STy->getNumElements())
245 return UndefValue::get(STy->getElementType(IdxV));
246 } else if (const SequentialType *STy =
247 dyn_cast<SequentialType>(Agg->getType())) {
248 return UndefValue::get(STy->getElementType());
249 }
Chris Lattnerabab0712004-10-08 17:32:09 +0000250 }
251 return 0;
252}
Chris Lattner25db5802004-10-07 04:16:33 +0000253
254static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
255 if (GEP->getNumOperands() == 1 ||
256 !isa<Constant>(GEP->getOperand(1)) ||
257 !cast<Constant>(GEP->getOperand(1))->isNullValue())
258 return 0;
259
260 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
261 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
262 if (!Idx) return 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000263 Init = getAggregateConstantElement(Init, Idx);
264 if (Init == 0) return 0;
Chris Lattner25db5802004-10-07 04:16:33 +0000265 }
266 return Init;
267}
268
269/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
270/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000271/// quick scan over the use list to clean up the easy and obvious cruft. This
272/// returns true if it made a change.
273static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
274 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000275 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
276 User *U = *UI++;
277
278 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
279 // Replace the load with the initializer.
280 LI->replaceAllUsesWith(Init);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000281 LI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000282 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000283 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
284 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000285 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000286 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000287 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
288 if (CE->getOpcode() == Instruction::GetElementPtr) {
289 if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
Chris Lattnercb9f1522004-10-10 16:43:46 +0000290 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
291 if (CE->use_empty()) {
292 CE->destroyConstant();
293 Changed = true;
294 }
Chris Lattner25db5802004-10-07 04:16:33 +0000295 }
296 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
297 if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
Chris Lattnercb9f1522004-10-10 16:43:46 +0000298 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000299 else {
300 // If this GEP has variable indexes, we should still be able to delete
301 // any stores through it.
302 for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end();
303 GUI != E;)
304 if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000305 SI->eraseFromParent();
Chris Lattnera0e769c2004-10-10 16:47:33 +0000306 Changed = true;
307 }
308 }
309
Chris Lattnercb9f1522004-10-10 16:43:46 +0000310 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000311 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000312 Changed = true;
313 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000314 } else if (Constant *C = dyn_cast<Constant>(U)) {
315 // If we have a chain of dead constantexprs or other things dangling from
316 // us, and if they are all dead, nuke them without remorse.
317 if (ConstantIsDead(C)) {
318 C->destroyConstant();
319 // This could have incalidated UI, start over from scratch.x
320 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000321 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000322 }
Chris Lattner25db5802004-10-07 04:16:33 +0000323 }
324 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000325 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000326}
327
Chris Lattnerabab0712004-10-08 17:32:09 +0000328/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
329/// variable. This opens the door for other optimizations by exposing the
330/// behavior of the program in a more fine-grained way. We have determined that
331/// this transformation is safe already. We return the first global variable we
332/// insert so that the caller can reprocess it.
333static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
334 assert(GV->hasInternalLinkage() && !GV->isConstant());
335 Constant *Init = GV->getInitializer();
336 const Type *Ty = Init->getType();
337
338 std::vector<GlobalVariable*> NewGlobals;
339 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
340
341 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
342 NewGlobals.reserve(STy->getNumElements());
343 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
344 Constant *In = getAggregateConstantElement(Init,
345 ConstantUInt::get(Type::UIntTy, i));
346 assert(In && "Couldn't get element of initializer?");
347 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
348 GlobalVariable::InternalLinkage,
349 In, GV->getName()+"."+utostr(i));
350 Globals.insert(GV, NGV);
351 NewGlobals.push_back(NGV);
352 }
353 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
354 unsigned NumElements = 0;
355 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
356 NumElements = ATy->getNumElements();
357 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
358 NumElements = PTy->getNumElements();
359 else
360 assert(0 && "Unknown aggregate sequential type!");
361
Chris Lattner004e2502004-10-11 05:54:41 +0000362 if (NumElements > 16 && GV->use_size() > 16) return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000363 NewGlobals.reserve(NumElements);
364 for (unsigned i = 0, e = NumElements; i != e; ++i) {
365 Constant *In = getAggregateConstantElement(Init,
366 ConstantUInt::get(Type::UIntTy, i));
367 assert(In && "Couldn't get element of initializer?");
368
369 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
370 GlobalVariable::InternalLinkage,
371 In, GV->getName()+"."+utostr(i));
372 Globals.insert(GV, NGV);
373 NewGlobals.push_back(NGV);
374 }
375 }
376
377 if (NewGlobals.empty())
378 return 0;
379
Chris Lattner004e2502004-10-11 05:54:41 +0000380 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
381
Chris Lattnerabab0712004-10-08 17:32:09 +0000382 Constant *NullInt = Constant::getNullValue(Type::IntTy);
383
384 // Loop over all of the uses of the global, replacing the constantexpr geps,
385 // with smaller constantexpr geps or direct references.
386 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000387 User *GEP = GV->use_back();
388 assert(((isa<ConstantExpr>(GEP) &&
389 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
390 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
391
Chris Lattnerabab0712004-10-08 17:32:09 +0000392 // Ignore the 1th operand, which has to be zero or else the program is quite
393 // broken (undefined). Get the 2nd operand, which is the structure or array
394 // index.
Chris Lattner004e2502004-10-11 05:54:41 +0000395 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000396 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
397
Chris Lattner004e2502004-10-11 05:54:41 +0000398 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000399
400 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000401 if (GEP->getNumOperands() > 3)
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
403 std::vector<Constant*> Idxs;
404 Idxs.push_back(NullInt);
405 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
406 Idxs.push_back(CE->getOperand(i));
407 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
408 } else {
409 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
410 std::vector<Value*> Idxs;
411 Idxs.push_back(NullInt);
412 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
413 Idxs.push_back(GEPI->getOperand(i));
414 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
415 GEPI->getName()+"."+utostr(Val), GEPI);
416 }
417 GEP->replaceAllUsesWith(NewPtr);
418
419 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000420 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000421 else
422 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000423 }
424
Chris Lattner73ad73e2004-10-08 20:25:55 +0000425 // Delete the old global, now that it is dead.
426 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000427 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000428
429 // Loop over the new globals array deleting any globals that are obviously
430 // dead. This can arise due to scalarization of a structure or an array that
431 // has elements that are dead.
432 unsigned FirstGlobal = 0;
433 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
434 if (NewGlobals[i]->use_empty()) {
435 Globals.erase(NewGlobals[i]);
436 if (FirstGlobal == i) ++FirstGlobal;
437 }
438
439 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000440}
441
Chris Lattner09a52722004-10-09 21:48:45 +0000442/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
443/// value will trap if the value is dynamically null.
444static bool AllUsesOfValueWillTrapIfNull(Value *V) {
445 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
446 if (isa<LoadInst>(*UI)) {
447 // Will trap.
448 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
449 if (SI->getOperand(0) == V) {
450 //std::cerr << "NONTRAPPING USE: " << **UI;
451 return false; // Storing the value.
452 }
453 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
454 if (CI->getOperand(0) != V) {
455 //std::cerr << "NONTRAPPING USE: " << **UI;
456 return false; // Not calling the ptr
457 }
458 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
459 if (II->getOperand(0) != V) {
460 //std::cerr << "NONTRAPPING USE: " << **UI;
461 return false; // Not calling the ptr
462 }
463 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
464 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
465 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
466 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000467 } else if (isa<SetCondInst>(*UI) &&
468 isa<ConstantPointerNull>(UI->getOperand(1))) {
469 // Ignore setcc X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000470 } else {
471 //std::cerr << "NONTRAPPING USE: " << **UI;
472 return false;
473 }
474 return true;
475}
476
477/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000478/// from GV will trap if the loaded value is null. Note that this also permits
479/// comparisons of the loaded value against null, as a special case.
Chris Lattner09a52722004-10-09 21:48:45 +0000480static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
481 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
482 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
483 if (!AllUsesOfValueWillTrapIfNull(LI))
484 return false;
485 } else if (isa<StoreInst>(*UI)) {
486 // Ignore stores to the global.
487 } else {
488 // We don't know or understand this user, bail out.
489 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
490 return false;
491 }
492
493 return true;
494}
495
Chris Lattnere42eb312004-10-10 23:14:11 +0000496static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
497 bool Changed = false;
498 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
499 Instruction *I = cast<Instruction>(*UI++);
500 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
501 LI->setOperand(0, NewV);
502 Changed = true;
503 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
504 if (SI->getOperand(1) == V) {
505 SI->setOperand(1, NewV);
506 Changed = true;
507 }
508 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
509 if (I->getOperand(0) == V) {
510 // Calling through the pointer! Turn into a direct call, but be careful
511 // that the pointer is not also being passed as an argument.
512 I->setOperand(0, NewV);
513 Changed = true;
514 bool PassedAsArg = false;
515 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
516 if (I->getOperand(i) == V) {
517 PassedAsArg = true;
518 I->setOperand(i, NewV);
519 }
520
521 if (PassedAsArg) {
522 // Being passed as an argument also. Be careful to not invalidate UI!
523 UI = V->use_begin();
524 }
525 }
526 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
527 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
528 ConstantExpr::getCast(NewV, CI->getType()));
529 if (CI->use_empty()) {
530 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000531 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000532 }
533 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
534 // Should handle GEP here.
535 std::vector<Constant*> Indices;
536 Indices.reserve(GEPI->getNumOperands()-1);
537 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
538 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
539 Indices.push_back(C);
540 else
541 break;
542 if (Indices.size() == GEPI->getNumOperands()-1)
543 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
544 ConstantExpr::getGetElementPtr(NewV, Indices));
545 if (GEPI->use_empty()) {
546 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000547 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000548 }
549 }
550 }
551
552 return Changed;
553}
554
555
556/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
557/// value stored into it. If there are uses of the loaded value that would trap
558/// if the loaded value is dynamically null, then we know that they cannot be
559/// reachable with a null optimize away the load.
560static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
561 std::vector<LoadInst*> Loads;
562 bool Changed = false;
563
564 // Replace all uses of loads with uses of uses of the stored value.
565 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
566 GUI != E; ++GUI)
567 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
568 Loads.push_back(LI);
569 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
570 } else {
571 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
572 }
573
574 if (Changed) {
575 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
576 ++NumGlobUses;
577 }
578
579 // Delete all of the loads we can, keeping track of whether we nuked them all!
580 bool AllLoadsGone = true;
581 while (!Loads.empty()) {
582 LoadInst *L = Loads.back();
583 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000584 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000585 Changed = true;
586 } else {
587 AllLoadsGone = false;
588 }
589 Loads.pop_back();
590 }
591
592 // If we nuked all of the loads, then none of the stores are needed either,
593 // nor is the global.
594 if (AllLoadsGone) {
595 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
596 CleanupConstantGlobalUsers(GV, 0);
597 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000598 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000599 ++NumDeleted;
600 }
601 Changed = true;
602 }
603 return Changed;
604}
605
Chris Lattner004e2502004-10-11 05:54:41 +0000606/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
607/// instructions that are foldable.
608static void ConstantPropUsersOf(Value *V) {
609 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
610 if (Instruction *I = dyn_cast<Instruction>(*UI++))
611 if (Constant *NewC = ConstantFoldInstruction(I)) {
612 I->replaceAllUsesWith(NewC);
613
614 // Back up UI to avoid invalidating it!
615 bool AtBegin = false;
616 if (UI == V->use_begin())
617 AtBegin = true;
618 else
619 --UI;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000620 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000621 if (AtBegin)
622 UI = V->use_begin();
623 else
624 ++UI;
625 }
626}
627
628/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
629/// variable, and transforms the program as if it always contained the result of
630/// the specified malloc. Because it is always the result of the specified
631/// malloc, there is no reason to actually DO the malloc. Instead, turn the
632/// malloc into a global, and any laods of GV as uses of the new global.
633static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
634 MallocInst *MI) {
635 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
636 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
637
638 if (NElements->getRawValue() != 1) {
639 // If we have an array allocation, transform it to a single element
640 // allocation to make the code below simpler.
641 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
642 NElements->getRawValue());
643 MallocInst *NewMI =
644 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
645 MI->getName(), MI);
646 std::vector<Value*> Indices;
647 Indices.push_back(Constant::getNullValue(Type::IntTy));
648 Indices.push_back(Indices[0]);
649 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
650 NewMI->getName()+".el0", MI);
651 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000652 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000653 MI = NewMI;
654 }
655
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000656 // Create the new global variable. The contents of the malloc'd memory is
657 // undefined, so initialize with an undef value.
658 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000659 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
660 GlobalValue::InternalLinkage, Init,
661 GV->getName()+".body");
662 GV->getParent()->getGlobalList().insert(GV, NewGV);
663
664 // Anything that used the malloc now uses the global directly.
665 MI->replaceAllUsesWith(NewGV);
Chris Lattner004e2502004-10-11 05:54:41 +0000666
667 Constant *RepValue = NewGV;
668 if (NewGV->getType() != GV->getType()->getElementType())
669 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
670
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000671 // If there is a comparison against null, we will insert a global bool to
672 // keep track of whether the global was initialized yet or not.
Chris Lattner3b181392004-12-02 06:25:58 +0000673 GlobalVariable *InitBool =
674 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
675 ConstantBool::False, GV->getName()+".init");
676 bool InitBoolUsed = false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000677
Chris Lattner004e2502004-10-11 05:54:41 +0000678 // Loop over all uses of GV, processing them in turn.
Chris Lattner3b181392004-12-02 06:25:58 +0000679 std::vector<StoreInst*> Stores;
Chris Lattner004e2502004-10-11 05:54:41 +0000680 while (!GV->use_empty())
681 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000682 while (!LI->use_empty()) {
683 // FIXME: the iterator should expose a getUse() method.
684 Use &LoadUse = *(const iplist<Use>::iterator&)LI->use_begin();
685 if (!isa<SetCondInst>(LoadUse.getUser()))
686 LoadUse = RepValue;
687 else {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000688 // Replace the setcc X, 0 with a use of the bool value.
689 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
690 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattner3b181392004-12-02 06:25:58 +0000691 InitBoolUsed = true;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000692 switch (SCI->getOpcode()) {
693 default: assert(0 && "Unknown opcode!");
694 case Instruction::SetLT:
695 LV = ConstantBool::False; // X < null -> always false
696 break;
697 case Instruction::SetEQ:
698 case Instruction::SetLE:
699 LV = BinaryOperator::createNot(LV, "notinit", SCI);
700 break;
701 case Instruction::SetNE:
702 case Instruction::SetGE:
703 case Instruction::SetGT:
704 break; // no change.
705 }
706 SCI->replaceAllUsesWith(LV);
707 SCI->eraseFromParent();
708 }
709 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000710 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000711 } else {
712 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner3b181392004-12-02 06:25:58 +0000713 // The global is initialized when the store to it occurs.
714 new StoreInst(ConstantBool::True, InitBool, SI);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000715 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000716 }
717
Chris Lattner3b181392004-12-02 06:25:58 +0000718 // If the initialization boolean was used, insert it, otherwise delete it.
719 if (!InitBoolUsed) {
720 while (!InitBool->use_empty()) // Delete initializations
721 cast<Instruction>(InitBool->use_back())->eraseFromParent();
722 delete InitBool;
723 } else
724 GV->getParent()->getGlobalList().insert(GV, InitBool);
725
726
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000727 // Now the GV is dead, nuke it and the malloc.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000728 GV->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000729 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000730
731 // To further other optimizations, loop over all users of NewGV and try to
732 // constant prop them. This will promote GEP instructions with constant
733 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
734 ConstantPropUsersOf(NewGV);
735 if (RepValue != NewGV)
736 ConstantPropUsersOf(RepValue);
737
738 return NewGV;
739}
Chris Lattnere42eb312004-10-10 23:14:11 +0000740
Chris Lattner09a52722004-10-09 21:48:45 +0000741// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
742// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000743static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
744 Module::giterator &GVI, TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +0000745 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
746 StoredOnceVal = CI->getOperand(0);
747 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +0000748 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +0000749 bool IsJustACast = true;
750 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
751 if (!isa<Constant>(GEPI->getOperand(i)) ||
752 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
753 IsJustACast = false;
754 break;
755 }
756 if (IsJustACast)
757 StoredOnceVal = GEPI->getOperand(0);
758 }
759
Chris Lattnere42eb312004-10-10 23:14:11 +0000760 // If we are dealing with a pointer global that is initialized to null and
761 // only has one (non-null) value stored into it, then we can optimize any
762 // users of the loaded value (often calls and loads) that would trap if the
763 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +0000764 if (isa<PointerType>(GV->getInitializer()->getType()) &&
765 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000766 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
767 if (GV->getInitializer()->getType() != SOVC->getType())
768 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
769
770 // Optimize away any trapping uses of the loaded value.
771 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +0000772 return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000773 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
774 // If we have a global that is only initialized with a fixed size malloc,
775 // and if all users of the malloc trap, and if the malloc'd address is not
776 // put anywhere else, transform the program to use global memory instead
777 // of malloc'd memory. This eliminates dynamic allocation (good) and
778 // exposes the resultant global to further GlobalOpt (even better). Note
779 // that we restrict this transformation to only working on small
780 // allocations (2048 bytes currently), as we don't want to introduce a 16M
781 // global or something.
782 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
783 if (MI->getAllocatedType()->isSized() &&
784 NElements->getRawValue()*
785 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
786 AllUsesOfLoadedValueWillTrapIfNull(GV)) {
787 // FIXME: do more correctness checking to make sure the result of the
788 // malloc isn't squirrelled away somewhere.
789 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
790 return true;
791 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000792 }
Chris Lattner09a52722004-10-09 21:48:45 +0000793 }
Chris Lattner004e2502004-10-11 05:54:41 +0000794
Chris Lattner09a52722004-10-09 21:48:45 +0000795 return false;
796}
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000797
798/// ProcessInternalGlobal - Analyze the specified global variable and optimize
799/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +0000800bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
801 Module::giterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000802 std::set<PHINode*> PHIUsers;
803 GlobalStatus GS;
804 PHIUsers.clear();
805 GV->removeDeadConstantUsers();
806
807 if (GV->use_empty()) {
808 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000809 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000810 ++NumDeleted;
811 return true;
812 }
813
814 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
815 // If the global is never loaded (but may be stored to), it is dead.
816 // Delete it now.
817 if (!GS.isLoaded) {
818 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +0000819
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000820 // Delete any stores we can find to the global. We may not be able to
821 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +0000822 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +0000823
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000824 // If the global is dead now, delete it.
825 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000826 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000827 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +0000828 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000829 }
Chris Lattnerf369b382004-10-09 03:32:52 +0000830 return Changed;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000831
832 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
833 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
834 GV->setConstant(true);
835
836 // Clean up any obviously simplifiable users now.
837 CleanupConstantGlobalUsers(GV, GV->getInitializer());
838
839 // If the global is dead now, just nuke it.
840 if (GV->use_empty()) {
841 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
842 "all users and delete global!\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000843 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000844 ++NumDeleted;
845 }
846
847 ++NumMarked;
848 return true;
849 } else if (!GS.isNotSuitableForSRA &&
850 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000851 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
852 GVI = FirstNewGV; // Don't skip the newly produced globals!
853 return true;
854 }
Chris Lattner09a52722004-10-09 21:48:45 +0000855 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000856 // If the initial value for the global was an undef value, and if only one
857 // other value was stored into it, we can just change the initializer to
858 // be an undef value, then delete all stores to the global. This allows
859 // us to mark it constant.
860 if (isa<UndefValue>(GV->getInitializer()) &&
861 isa<Constant>(GS.StoredOnceValue)) {
862 // Change the initial value here.
863 GV->setInitializer(cast<Constant>(GS.StoredOnceValue));
864
865 // Clean up any obviously simplifiable users now.
866 CleanupConstantGlobalUsers(GV, GV->getInitializer());
867
868 if (GV->use_empty()) {
869 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
870 "simplify all users and delete global!\n");
871 GV->eraseFromParent();
872 ++NumDeleted;
873 } else {
874 GVI = GV;
875 }
876 ++NumSubstitute;
877 return true;
878 }
879
Chris Lattner09a52722004-10-09 21:48:45 +0000880 // Try to optimize globals based on the knowledge that only one value
881 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000882 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
883 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +0000884 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000885 }
886 }
887 return false;
888}
889
890
Chris Lattner25db5802004-10-07 04:16:33 +0000891bool GlobalOpt::runOnModule(Module &M) {
892 bool Changed = false;
893
894 // As a prepass, delete functions that are trivially dead.
895 bool LocalChange = true;
896 while (LocalChange) {
897 LocalChange = false;
898 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
899 Function *F = FI++;
900 F->removeDeadConstantUsers();
Chris Lattner5d33e8e2004-10-14 19:53:50 +0000901 if (F->use_empty() && (F->hasInternalLinkage() ||
902 F->hasLinkOnceLinkage())) {
Chris Lattner25db5802004-10-07 04:16:33 +0000903 M.getFunctionList().erase(F);
904 LocalChange = true;
905 ++NumFnDeleted;
906 }
907 }
908 Changed |= LocalChange;
909 }
910
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000911 LocalChange = true;
912 while (LocalChange) {
913 LocalChange = false;
914 for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
915 GlobalVariable *GV = GVI++;
916 if (!GV->isConstant() && GV->hasInternalLinkage() &&
917 GV->hasInitializer())
918 LocalChange |= ProcessInternalGlobal(GV, GVI);
Chris Lattner25db5802004-10-07 04:16:33 +0000919 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000920 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +0000921 }
922 return Changed;
923}