blob: dc8832c4f3638ec989c1e5003dd74010f7fc4a7b [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");
36 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner25db5802004-10-07 04:16:33 +000037 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
Chris Lattnere42eb312004-10-10 23:14:11 +000038 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
Chris Lattner25db5802004-10-07 04:16:33 +000039
40 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000041 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<TargetData>();
43 }
44
Chris Lattner25db5802004-10-07 04:16:33 +000045 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000046
47 private:
48 bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000049 };
50
51 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
52}
53
54ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
55
56/// GlobalStatus - As we analyze each global, keep track of some information
57/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000058/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000059struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000060 /// isLoaded - True if the global is ever loaded. If the global isn't ever
61 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000062 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000063
64 /// StoredType - Keep track of what stores to the global look like.
65 ///
Chris Lattner25db5802004-10-07 04:16:33 +000066 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000067 /// NotStored - There is no store to this global. It can thus be marked
68 /// constant.
69 NotStored,
70
71 /// isInitializerStored - This global is stored to, but the only thing
72 /// stored is the constant it was initialized with. This is only tracked
73 /// for scalar globals.
74 isInitializerStored,
75
76 /// isStoredOnce - This global is stored to, but only its initializer and
77 /// one other value is ever stored to it. If this global isStoredOnce, we
78 /// track the value stored to it in StoredOnceValue below. This is only
79 /// tracked for scalar globals.
80 isStoredOnce,
81
82 /// isStored - This global is stored to by multiple values or something else
83 /// that we cannot track.
84 isStored
Chris Lattner25db5802004-10-07 04:16:33 +000085 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +000086
87 /// StoredOnceValue - If only one value (besides the initializer constant) is
88 /// ever stored to this global, keep track of what value it is.
89 Value *StoredOnceValue;
90
91 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
92 /// the global exist. Such users include GEP instruction with variable
93 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +000094 bool isNotSuitableForSRA;
95
Chris Lattner617f1a32004-10-07 21:30:30 +000096 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Chris Lattner25db5802004-10-07 04:16:33 +000097 isNotSuitableForSRA(false) {}
98};
99
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000100
101
102/// ConstantIsDead - Return true if the specified constant is (transitively)
103/// dead. The constant may be used by other constants (e.g. constant arrays and
104/// constant exprs) as long as they are dead, but it cannot be used by anything
105/// else.
106static bool ConstantIsDead(Constant *C) {
107 if (isa<GlobalValue>(C)) return false;
108
109 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
110 if (Constant *CU = dyn_cast<Constant>(*UI)) {
111 if (!ConstantIsDead(CU)) return false;
112 } else
113 return false;
114 return true;
115}
116
117
Chris Lattner25db5802004-10-07 04:16:33 +0000118/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
119/// structure. If the global has its address taken, return true to indicate we
120/// can't do anything with it.
121///
122static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
123 std::set<PHINode*> &PHIUsers) {
124 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
125 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
126 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
127 if (CE->getOpcode() != Instruction::GetElementPtr)
128 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000129 else if (!GS.isNotSuitableForSRA) {
130 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
131 // don't like < 3 operand CE's, and we don't like non-constant integer
132 // indices.
133 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
134 GS.isNotSuitableForSRA = true;
135 else {
136 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
137 if (!isa<ConstantInt>(CE->getOperand(i))) {
138 GS.isNotSuitableForSRA = true;
139 break;
140 }
141 }
142 }
143
Chris Lattner25db5802004-10-07 04:16:33 +0000144 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
145 if (isa<LoadInst>(I)) {
146 GS.isLoaded = true;
147 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000148 // Don't allow a store OF the address, only stores TO the address.
149 if (SI->getOperand(0) == V) return true;
150
Chris Lattner617f1a32004-10-07 21:30:30 +0000151 // If this is a direct store to the global (i.e., the global is a scalar
152 // value, not an aggregate), keep more specific information about
153 // stores.
154 if (GS.StoredType != GlobalStatus::isStored)
155 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
156 if (SI->getOperand(0) == GV->getInitializer()) {
157 if (GS.StoredType < GlobalStatus::isInitializerStored)
158 GS.StoredType = GlobalStatus::isInitializerStored;
159 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
160 GS.StoredType = GlobalStatus::isStoredOnce;
161 GS.StoredOnceValue = SI->getOperand(0);
162 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
163 GS.StoredOnceValue == SI->getOperand(0)) {
164 // noop.
165 } else {
166 GS.StoredType = GlobalStatus::isStored;
167 }
168 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000169 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000170 }
Chris Lattner25db5802004-10-07 04:16:33 +0000171 } else if (I->getOpcode() == Instruction::GetElementPtr) {
172 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000173
174 // If the first two indices are constants, this can be SRA'd.
175 if (isa<GlobalVariable>(I->getOperand(0))) {
176 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
177 !cast<Constant>(I->getOperand(1))->isNullValue() ||
178 !isa<ConstantInt>(I->getOperand(2)))
179 GS.isNotSuitableForSRA = true;
180 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
181 if (CE->getOpcode() != Instruction::GetElementPtr ||
182 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
183 !isa<Constant>(I->getOperand(0)) ||
184 !cast<Constant>(I->getOperand(0))->isNullValue())
185 GS.isNotSuitableForSRA = true;
186 } else {
187 GS.isNotSuitableForSRA = true;
188 }
Chris Lattner25db5802004-10-07 04:16:33 +0000189 } else if (I->getOpcode() == Instruction::Select) {
190 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
191 GS.isNotSuitableForSRA = true;
192 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
193 // PHI nodes we can check just like select or GEP instructions, but we
194 // have to be careful about infinite recursion.
195 if (PHIUsers.insert(PN).second) // Not already visited.
196 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
197 GS.isNotSuitableForSRA = true;
198 } else if (isa<SetCondInst>(I)) {
199 GS.isNotSuitableForSRA = true;
200 } else {
201 return true; // Any other non-load instruction might take address!
202 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000203 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
204 // We might have a dead and dangling constant hanging off of here.
205 if (!ConstantIsDead(C))
206 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000207 } else {
208 // Otherwise must be a global or some other user.
209 return true;
210 }
211
212 return false;
213}
214
Chris Lattnerabab0712004-10-08 17:32:09 +0000215static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
216 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
217 if (!CI) return 0;
218 uint64_t IdxV = CI->getRawValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000219
Chris Lattnerabab0712004-10-08 17:32:09 +0000220 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
221 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
222 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
223 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
224 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
225 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
226 } else if (ConstantAggregateZero *CAZ =
227 dyn_cast<ConstantAggregateZero>(Agg)) {
228 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
229 if (IdxV < STy->getNumElements())
230 return Constant::getNullValue(STy->getElementType(IdxV));
231 } else if (const SequentialType *STy =
232 dyn_cast<SequentialType>(Agg->getType())) {
233 return Constant::getNullValue(STy->getElementType());
234 }
235 }
236 return 0;
237}
Chris Lattner25db5802004-10-07 04:16:33 +0000238
239static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
240 if (GEP->getNumOperands() == 1 ||
241 !isa<Constant>(GEP->getOperand(1)) ||
242 !cast<Constant>(GEP->getOperand(1))->isNullValue())
243 return 0;
244
245 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
246 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
247 if (!Idx) return 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000248 Init = getAggregateConstantElement(Init, Idx);
249 if (Init == 0) return 0;
Chris Lattner25db5802004-10-07 04:16:33 +0000250 }
251 return Init;
252}
253
254/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
255/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000256/// quick scan over the use list to clean up the easy and obvious cruft. This
257/// returns true if it made a change.
258static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
259 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000260 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
261 User *U = *UI++;
262
263 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
264 // Replace the load with the initializer.
265 LI->replaceAllUsesWith(Init);
266 LI->getParent()->getInstList().erase(LI);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000267 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000268 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
269 // Store must be unreachable or storing Init into the global.
270 SI->getParent()->getInstList().erase(SI);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000271 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000272 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
273 if (CE->getOpcode() == Instruction::GetElementPtr) {
274 if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
Chris Lattnercb9f1522004-10-10 16:43:46 +0000275 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
276 if (CE->use_empty()) {
277 CE->destroyConstant();
278 Changed = true;
279 }
Chris Lattner25db5802004-10-07 04:16:33 +0000280 }
281 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
282 if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
Chris Lattnercb9f1522004-10-10 16:43:46 +0000283 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000284 else {
285 // If this GEP has variable indexes, we should still be able to delete
286 // any stores through it.
287 for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end();
288 GUI != E;)
289 if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) {
290 SI->getParent()->getInstList().erase(SI);
291 Changed = true;
292 }
293 }
294
Chris Lattnercb9f1522004-10-10 16:43:46 +0000295 if (GEP->use_empty()) {
Chris Lattner25db5802004-10-07 04:16:33 +0000296 GEP->getParent()->getInstList().erase(GEP);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000297 Changed = true;
298 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000299 } else if (Constant *C = dyn_cast<Constant>(U)) {
300 // If we have a chain of dead constantexprs or other things dangling from
301 // us, and if they are all dead, nuke them without remorse.
302 if (ConstantIsDead(C)) {
303 C->destroyConstant();
304 // This could have incalidated UI, start over from scratch.x
305 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000306 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000307 }
Chris Lattner25db5802004-10-07 04:16:33 +0000308 }
309 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000310 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000311}
312
Chris Lattnerabab0712004-10-08 17:32:09 +0000313/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
314/// variable. This opens the door for other optimizations by exposing the
315/// behavior of the program in a more fine-grained way. We have determined that
316/// this transformation is safe already. We return the first global variable we
317/// insert so that the caller can reprocess it.
318static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
319 assert(GV->hasInternalLinkage() && !GV->isConstant());
320 Constant *Init = GV->getInitializer();
321 const Type *Ty = Init->getType();
322
323 std::vector<GlobalVariable*> NewGlobals;
324 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
325
326 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
327 NewGlobals.reserve(STy->getNumElements());
328 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
329 Constant *In = getAggregateConstantElement(Init,
330 ConstantUInt::get(Type::UIntTy, i));
331 assert(In && "Couldn't get element of initializer?");
332 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
333 GlobalVariable::InternalLinkage,
334 In, GV->getName()+"."+utostr(i));
335 Globals.insert(GV, NGV);
336 NewGlobals.push_back(NGV);
337 }
338 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
339 unsigned NumElements = 0;
340 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
341 NumElements = ATy->getNumElements();
342 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
343 NumElements = PTy->getNumElements();
344 else
345 assert(0 && "Unknown aggregate sequential type!");
346
Chris Lattner004e2502004-10-11 05:54:41 +0000347 if (NumElements > 16 && GV->use_size() > 16) return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000348 NewGlobals.reserve(NumElements);
349 for (unsigned i = 0, e = NumElements; i != e; ++i) {
350 Constant *In = getAggregateConstantElement(Init,
351 ConstantUInt::get(Type::UIntTy, i));
352 assert(In && "Couldn't get element of initializer?");
353
354 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
355 GlobalVariable::InternalLinkage,
356 In, GV->getName()+"."+utostr(i));
357 Globals.insert(GV, NGV);
358 NewGlobals.push_back(NGV);
359 }
360 }
361
362 if (NewGlobals.empty())
363 return 0;
364
Chris Lattner004e2502004-10-11 05:54:41 +0000365 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
366
Chris Lattnerabab0712004-10-08 17:32:09 +0000367 Constant *NullInt = Constant::getNullValue(Type::IntTy);
368
369 // Loop over all of the uses of the global, replacing the constantexpr geps,
370 // with smaller constantexpr geps or direct references.
371 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000372 User *GEP = GV->use_back();
373 assert(((isa<ConstantExpr>(GEP) &&
374 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
375 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
376
Chris Lattnerabab0712004-10-08 17:32:09 +0000377 // Ignore the 1th operand, which has to be zero or else the program is quite
378 // broken (undefined). Get the 2nd operand, which is the structure or array
379 // index.
Chris Lattner004e2502004-10-11 05:54:41 +0000380 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000381 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
382
Chris Lattner004e2502004-10-11 05:54:41 +0000383 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000384
385 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000386 if (GEP->getNumOperands() > 3)
387 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
388 std::vector<Constant*> Idxs;
389 Idxs.push_back(NullInt);
390 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
391 Idxs.push_back(CE->getOperand(i));
392 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
393 } else {
394 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
395 std::vector<Value*> Idxs;
396 Idxs.push_back(NullInt);
397 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
398 Idxs.push_back(GEPI->getOperand(i));
399 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
400 GEPI->getName()+"."+utostr(Val), GEPI);
401 }
402 GEP->replaceAllUsesWith(NewPtr);
403
404 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
405 GEPI->getParent()->getInstList().erase(GEPI);
406 else
407 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000408 }
409
Chris Lattner73ad73e2004-10-08 20:25:55 +0000410 // Delete the old global, now that it is dead.
411 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000412 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000413
414 // Loop over the new globals array deleting any globals that are obviously
415 // dead. This can arise due to scalarization of a structure or an array that
416 // has elements that are dead.
417 unsigned FirstGlobal = 0;
418 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
419 if (NewGlobals[i]->use_empty()) {
420 Globals.erase(NewGlobals[i]);
421 if (FirstGlobal == i) ++FirstGlobal;
422 }
423
424 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000425}
426
Chris Lattner09a52722004-10-09 21:48:45 +0000427/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
428/// value will trap if the value is dynamically null.
429static bool AllUsesOfValueWillTrapIfNull(Value *V) {
430 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
431 if (isa<LoadInst>(*UI)) {
432 // Will trap.
433 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
434 if (SI->getOperand(0) == V) {
435 //std::cerr << "NONTRAPPING USE: " << **UI;
436 return false; // Storing the value.
437 }
438 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
439 if (CI->getOperand(0) != V) {
440 //std::cerr << "NONTRAPPING USE: " << **UI;
441 return false; // Not calling the ptr
442 }
443 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
444 if (II->getOperand(0) != V) {
445 //std::cerr << "NONTRAPPING USE: " << **UI;
446 return false; // Not calling the ptr
447 }
448 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
449 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
450 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
451 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
452 } else {
453 //std::cerr << "NONTRAPPING USE: " << **UI;
454 return false;
455 }
456 return true;
457}
458
459/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
460/// from GV will trap if the loaded value is null.
461static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
462 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
463 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
464 if (!AllUsesOfValueWillTrapIfNull(LI))
465 return false;
466 } else if (isa<StoreInst>(*UI)) {
467 // Ignore stores to the global.
468 } else {
469 // We don't know or understand this user, bail out.
470 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
471 return false;
472 }
473
474 return true;
475}
476
Chris Lattnere42eb312004-10-10 23:14:11 +0000477static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
478 bool Changed = false;
479 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
480 Instruction *I = cast<Instruction>(*UI++);
481 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
482 LI->setOperand(0, NewV);
483 Changed = true;
484 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
485 if (SI->getOperand(1) == V) {
486 SI->setOperand(1, NewV);
487 Changed = true;
488 }
489 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
490 if (I->getOperand(0) == V) {
491 // Calling through the pointer! Turn into a direct call, but be careful
492 // that the pointer is not also being passed as an argument.
493 I->setOperand(0, NewV);
494 Changed = true;
495 bool PassedAsArg = false;
496 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
497 if (I->getOperand(i) == V) {
498 PassedAsArg = true;
499 I->setOperand(i, NewV);
500 }
501
502 if (PassedAsArg) {
503 // Being passed as an argument also. Be careful to not invalidate UI!
504 UI = V->use_begin();
505 }
506 }
507 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
508 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
509 ConstantExpr::getCast(NewV, CI->getType()));
510 if (CI->use_empty()) {
511 Changed = true;
512 CI->getParent()->getInstList().erase(CI);
513 }
514 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
515 // Should handle GEP here.
516 std::vector<Constant*> Indices;
517 Indices.reserve(GEPI->getNumOperands()-1);
518 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
519 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
520 Indices.push_back(C);
521 else
522 break;
523 if (Indices.size() == GEPI->getNumOperands()-1)
524 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
525 ConstantExpr::getGetElementPtr(NewV, Indices));
526 if (GEPI->use_empty()) {
527 Changed = true;
528 GEPI->getParent()->getInstList().erase(GEPI);
529 }
530 }
531 }
532
533 return Changed;
534}
535
536
537/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
538/// value stored into it. If there are uses of the loaded value that would trap
539/// if the loaded value is dynamically null, then we know that they cannot be
540/// reachable with a null optimize away the load.
541static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
542 std::vector<LoadInst*> Loads;
543 bool Changed = false;
544
545 // Replace all uses of loads with uses of uses of the stored value.
546 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
547 GUI != E; ++GUI)
548 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
549 Loads.push_back(LI);
550 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
551 } else {
552 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
553 }
554
555 if (Changed) {
556 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
557 ++NumGlobUses;
558 }
559
560 // Delete all of the loads we can, keeping track of whether we nuked them all!
561 bool AllLoadsGone = true;
562 while (!Loads.empty()) {
563 LoadInst *L = Loads.back();
564 if (L->use_empty()) {
565 L->getParent()->getInstList().erase(L);
566 Changed = true;
567 } else {
568 AllLoadsGone = false;
569 }
570 Loads.pop_back();
571 }
572
573 // If we nuked all of the loads, then none of the stores are needed either,
574 // nor is the global.
575 if (AllLoadsGone) {
576 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
577 CleanupConstantGlobalUsers(GV, 0);
578 if (GV->use_empty()) {
579 GV->getParent()->getGlobalList().erase(GV);
580 ++NumDeleted;
581 }
582 Changed = true;
583 }
584 return Changed;
585}
586
Chris Lattner004e2502004-10-11 05:54:41 +0000587/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
588/// instructions that are foldable.
589static void ConstantPropUsersOf(Value *V) {
590 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
591 if (Instruction *I = dyn_cast<Instruction>(*UI++))
592 if (Constant *NewC = ConstantFoldInstruction(I)) {
593 I->replaceAllUsesWith(NewC);
594
595 // Back up UI to avoid invalidating it!
596 bool AtBegin = false;
597 if (UI == V->use_begin())
598 AtBegin = true;
599 else
600 --UI;
601 I->getParent()->getInstList().erase(I);
602 if (AtBegin)
603 UI = V->use_begin();
604 else
605 ++UI;
606 }
607}
608
609/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
610/// variable, and transforms the program as if it always contained the result of
611/// the specified malloc. Because it is always the result of the specified
612/// malloc, there is no reason to actually DO the malloc. Instead, turn the
613/// malloc into a global, and any laods of GV as uses of the new global.
614static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
615 MallocInst *MI) {
616 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
617 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
618
619 if (NElements->getRawValue() != 1) {
620 // If we have an array allocation, transform it to a single element
621 // allocation to make the code below simpler.
622 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
623 NElements->getRawValue());
624 MallocInst *NewMI =
625 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
626 MI->getName(), MI);
627 std::vector<Value*> Indices;
628 Indices.push_back(Constant::getNullValue(Type::IntTy));
629 Indices.push_back(Indices[0]);
630 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
631 NewMI->getName()+".el0", MI);
632 MI->replaceAllUsesWith(NewGEP);
633 MI->getParent()->getInstList().erase(MI);
634 MI = NewMI;
635 }
636
637 // Create the new global variable.
638 Constant *Init = Constant::getNullValue(MI->getAllocatedType());
639 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
640 GlobalValue::InternalLinkage, Init,
641 GV->getName()+".body");
642 GV->getParent()->getGlobalList().insert(GV, NewGV);
643
644 // Anything that used the malloc now uses the global directly.
645 MI->replaceAllUsesWith(NewGV);
646 MI->getParent()->getInstList().erase(MI);
647
648 Constant *RepValue = NewGV;
649 if (NewGV->getType() != GV->getType()->getElementType())
650 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
651
652 // Loop over all uses of GV, processing them in turn.
653 while (!GV->use_empty())
654 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
655 LI->replaceAllUsesWith(RepValue);
656 LI->getParent()->getInstList().erase(LI);
657 } else {
658 StoreInst *SI = cast<StoreInst>(GV->use_back());
659 SI->getParent()->getInstList().erase(SI);
660 }
661
662 // Now the GV is dead, nuke it.
663 GV->getParent()->getGlobalList().erase(GV);
664
665 // To further other optimizations, loop over all users of NewGV and try to
666 // constant prop them. This will promote GEP instructions with constant
667 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
668 ConstantPropUsersOf(NewGV);
669 if (RepValue != NewGV)
670 ConstantPropUsersOf(RepValue);
671
672 return NewGV;
673}
Chris Lattnere42eb312004-10-10 23:14:11 +0000674
Chris Lattner09a52722004-10-09 21:48:45 +0000675// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
676// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000677static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
678 Module::giterator &GVI, TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +0000679 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
680 StoredOnceVal = CI->getOperand(0);
681 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +0000682 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +0000683 bool IsJustACast = true;
684 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
685 if (!isa<Constant>(GEPI->getOperand(i)) ||
686 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
687 IsJustACast = false;
688 break;
689 }
690 if (IsJustACast)
691 StoredOnceVal = GEPI->getOperand(0);
692 }
693
Chris Lattnere42eb312004-10-10 23:14:11 +0000694 // If we are dealing with a pointer global that is initialized to null and
695 // only has one (non-null) value stored into it, then we can optimize any
696 // users of the loaded value (often calls and loads) that would trap if the
697 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +0000698 if (isa<PointerType>(GV->getInitializer()->getType()) &&
699 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000700 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
701 if (GV->getInitializer()->getType() != SOVC->getType())
702 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
703
704 // Optimize away any trapping uses of the loaded value.
705 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +0000706 return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000707 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
708 // If we have a global that is only initialized with a fixed size malloc,
709 // and if all users of the malloc trap, and if the malloc'd address is not
710 // put anywhere else, transform the program to use global memory instead
711 // of malloc'd memory. This eliminates dynamic allocation (good) and
712 // exposes the resultant global to further GlobalOpt (even better). Note
713 // that we restrict this transformation to only working on small
714 // allocations (2048 bytes currently), as we don't want to introduce a 16M
715 // global or something.
716 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
717 if (MI->getAllocatedType()->isSized() &&
718 NElements->getRawValue()*
719 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
720 AllUsesOfLoadedValueWillTrapIfNull(GV)) {
721 // FIXME: do more correctness checking to make sure the result of the
722 // malloc isn't squirrelled away somewhere.
723 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
724 return true;
725 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000726 }
Chris Lattner09a52722004-10-09 21:48:45 +0000727 }
Chris Lattner004e2502004-10-11 05:54:41 +0000728
Chris Lattner09a52722004-10-09 21:48:45 +0000729 return false;
730}
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000731
732/// ProcessInternalGlobal - Analyze the specified global variable and optimize
733/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +0000734bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
735 Module::giterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000736 std::set<PHINode*> PHIUsers;
737 GlobalStatus GS;
738 PHIUsers.clear();
739 GV->removeDeadConstantUsers();
740
741 if (GV->use_empty()) {
742 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner1b8d2952004-10-08 22:05:31 +0000743 GV->getParent()->getGlobalList().erase(GV);
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000744 ++NumDeleted;
745 return true;
746 }
747
748 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
749 // If the global is never loaded (but may be stored to), it is dead.
750 // Delete it now.
751 if (!GS.isLoaded) {
752 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +0000753
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000754 // Delete any stores we can find to the global. We may not be able to
755 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +0000756 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +0000757
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000758 // If the global is dead now, delete it.
759 if (GV->use_empty()) {
760 GV->getParent()->getGlobalList().erase(GV);
761 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +0000762 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000763 }
Chris Lattnerf369b382004-10-09 03:32:52 +0000764 return Changed;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000765
766 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
767 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
768 GV->setConstant(true);
769
770 // Clean up any obviously simplifiable users now.
771 CleanupConstantGlobalUsers(GV, GV->getInitializer());
772
773 // If the global is dead now, just nuke it.
774 if (GV->use_empty()) {
775 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
776 "all users and delete global!\n");
777 GV->getParent()->getGlobalList().erase(GV);
778 ++NumDeleted;
779 }
780
781 ++NumMarked;
782 return true;
783 } else if (!GS.isNotSuitableForSRA &&
784 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000785 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
786 GVI = FirstNewGV; // Don't skip the newly produced globals!
787 return true;
788 }
Chris Lattner09a52722004-10-09 21:48:45 +0000789 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
790 // Try to optimize globals based on the knowledge that only one value
791 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000792 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
793 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +0000794 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000795 }
796 }
797 return false;
798}
799
800
Chris Lattner25db5802004-10-07 04:16:33 +0000801bool GlobalOpt::runOnModule(Module &M) {
802 bool Changed = false;
803
804 // As a prepass, delete functions that are trivially dead.
805 bool LocalChange = true;
806 while (LocalChange) {
807 LocalChange = false;
808 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
809 Function *F = FI++;
810 F->removeDeadConstantUsers();
811 if (F->use_empty() && (F->hasInternalLinkage() || F->hasWeakLinkage())) {
812 M.getFunctionList().erase(F);
813 LocalChange = true;
814 ++NumFnDeleted;
815 }
816 }
817 Changed |= LocalChange;
818 }
819
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000820 LocalChange = true;
821 while (LocalChange) {
822 LocalChange = false;
823 for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
824 GlobalVariable *GV = GVI++;
825 if (!GV->isConstant() && GV->hasInternalLinkage() &&
826 GV->hasInitializer())
827 LocalChange |= ProcessInternalGlobal(GV, GVI);
Chris Lattner25db5802004-10-07 04:16:33 +0000828 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000829 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +0000830 }
831 return Changed;
832}