blob: 0c00798f99ff8b682da2a7e2363d747a27c01db0 [file] [log] [blame]
Chris Lattner25db5802004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner25db5802004-10-07 04:16:33 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner25db5802004-10-07 04:16:33 +00008//===----------------------------------------------------------------------===//
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"
Chris Lattnera4c80222005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner25db5802004-10-07 04:16:33 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Instructions.h"
Chris Lattner7561ca12005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner25db5802004-10-07 04:16:33 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/Debug.h"
Chris Lattner004e2502004-10-11 05:54:41 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Transforms/Utils/Local.h"
Chris Lattner25db5802004-10-07 04:16:33 +000028#include "llvm/ADT/Statistic.h"
Chris Lattnerabab0712004-10-08 17:32:09 +000029#include "llvm/ADT/StringExtras.h"
Chris Lattner25db5802004-10-07 04:16:33 +000030#include <set>
31#include <algorithm>
32using namespace llvm;
33
34namespace {
Chris Lattnerabab0712004-10-08 17:32:09 +000035 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
36 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
37 "into scalars");
Chris Lattner8e71c6a2004-10-16 18:09:00 +000038 Statistic<> NumSubstitute("globalopt",
39 "Number of globals with initializers stored into them");
Chris Lattnerabab0712004-10-08 17:32:09 +000040 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner25db5802004-10-07 04:16:33 +000041 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
Chris Lattnere42eb312004-10-10 23:14:11 +000042 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +000043 Statistic<> NumLocalized("globalopt", "Number of globals localized");
Chris Lattner40e4cec2004-12-12 05:53:50 +000044 Statistic<> NumShrunkToBool("globalopt",
45 "Number of global vars shrunk to booleans");
Chris Lattnera4c80222005-05-08 22:18:06 +000046 Statistic<> NumFastCallFns("globalopt",
47 "Number of functions converted to fastcc");
Chris Lattner25db5802004-10-07 04:16:33 +000048
49 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000050 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addRequired<TargetData>();
52 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000053
Chris Lattner25db5802004-10-07 04:16:33 +000054 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000055
56 private:
Chris Lattner531f9e92005-03-15 04:54:21 +000057 bool ProcessInternalGlobal(GlobalVariable *GV, Module::global_iterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000058 };
59
60 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
61}
62
63ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
64
65/// GlobalStatus - As we analyze each global, keep track of some information
66/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000067/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000068struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000069 /// isLoaded - True if the global is ever loaded. If the global isn't ever
70 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000071 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000072
73 /// StoredType - Keep track of what stores to the global look like.
74 ///
Chris Lattner25db5802004-10-07 04:16:33 +000075 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000076 /// NotStored - There is no store to this global. It can thus be marked
77 /// constant.
78 NotStored,
79
80 /// isInitializerStored - This global is stored to, but the only thing
81 /// stored is the constant it was initialized with. This is only tracked
82 /// for scalar globals.
83 isInitializerStored,
84
85 /// isStoredOnce - This global is stored to, but only its initializer and
86 /// one other value is ever stored to it. If this global isStoredOnce, we
87 /// track the value stored to it in StoredOnceValue below. This is only
88 /// tracked for scalar globals.
89 isStoredOnce,
90
91 /// isStored - This global is stored to by multiple values or something else
92 /// that we cannot track.
93 isStored
Chris Lattner25db5802004-10-07 04:16:33 +000094 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +000095
96 /// StoredOnceValue - If only one value (besides the initializer constant) is
97 /// ever stored to this global, keep track of what value it is.
98 Value *StoredOnceValue;
99
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000100 // AccessingFunction/HasMultipleAccessingFunctions - These start out
101 // null/false. When the first accessing function is noticed, it is recorded.
102 // When a second different accessing function is noticed,
103 // HasMultipleAccessingFunctions is set to true.
104 Function *AccessingFunction;
105 bool HasMultipleAccessingFunctions;
106
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000107 // HasNonInstructionUser - Set to true if this global has a user that is not
108 // an instruction (e.g. a constant expr or GV initializer).
109 bool HasNonInstructionUser;
110
Chris Lattner617f1a32004-10-07 21:30:30 +0000111 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
112 /// the global exist. Such users include GEP instruction with variable
113 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +0000114 bool isNotSuitableForSRA;
115
Chris Lattner617f1a32004-10-07 21:30:30 +0000116 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000117 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000118 HasNonInstructionUser(false), isNotSuitableForSRA(false) {}
Chris Lattner25db5802004-10-07 04:16:33 +0000119};
120
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000121
122
123/// ConstantIsDead - Return true if the specified constant is (transitively)
124/// dead. The constant may be used by other constants (e.g. constant arrays and
125/// constant exprs) as long as they are dead, but it cannot be used by anything
126/// else.
127static bool ConstantIsDead(Constant *C) {
128 if (isa<GlobalValue>(C)) return false;
129
130 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
131 if (Constant *CU = dyn_cast<Constant>(*UI)) {
132 if (!ConstantIsDead(CU)) return false;
133 } else
134 return false;
135 return true;
136}
137
138
Chris Lattner25db5802004-10-07 04:16:33 +0000139/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
140/// structure. If the global has its address taken, return true to indicate we
141/// can't do anything with it.
142///
143static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
144 std::set<PHINode*> &PHIUsers) {
145 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
146 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000147 GS.HasNonInstructionUser = true;
148
Chris Lattner25db5802004-10-07 04:16:33 +0000149 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
150 if (CE->getOpcode() != Instruction::GetElementPtr)
151 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000152 else if (!GS.isNotSuitableForSRA) {
153 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
154 // don't like < 3 operand CE's, and we don't like non-constant integer
155 // indices.
156 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
157 GS.isNotSuitableForSRA = true;
158 else {
159 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
160 if (!isa<ConstantInt>(CE->getOperand(i))) {
161 GS.isNotSuitableForSRA = true;
162 break;
163 }
164 }
165 }
166
Chris Lattner25db5802004-10-07 04:16:33 +0000167 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000168 if (!GS.HasMultipleAccessingFunctions) {
169 Function *F = I->getParent()->getParent();
170 if (GS.AccessingFunction == 0)
171 GS.AccessingFunction = F;
172 else if (GS.AccessingFunction != F)
173 GS.HasMultipleAccessingFunctions = true;
174 }
Chris Lattner25db5802004-10-07 04:16:33 +0000175 if (isa<LoadInst>(I)) {
176 GS.isLoaded = true;
177 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000178 // Don't allow a store OF the address, only stores TO the address.
179 if (SI->getOperand(0) == V) return true;
180
Chris Lattner617f1a32004-10-07 21:30:30 +0000181 // If this is a direct store to the global (i.e., the global is a scalar
182 // value, not an aggregate), keep more specific information about
183 // stores.
184 if (GS.StoredType != GlobalStatus::isStored)
185 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattner28eeb732004-11-14 20:50:30 +0000186 Value *StoredVal = SI->getOperand(0);
187 if (StoredVal == GV->getInitializer()) {
188 if (GS.StoredType < GlobalStatus::isInitializerStored)
189 GS.StoredType = GlobalStatus::isInitializerStored;
190 } else if (isa<LoadInst>(StoredVal) &&
191 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
192 // G = G
Chris Lattner617f1a32004-10-07 21:30:30 +0000193 if (GS.StoredType < GlobalStatus::isInitializerStored)
194 GS.StoredType = GlobalStatus::isInitializerStored;
195 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
196 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattner28eeb732004-11-14 20:50:30 +0000197 GS.StoredOnceValue = StoredVal;
Chris Lattner617f1a32004-10-07 21:30:30 +0000198 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattner28eeb732004-11-14 20:50:30 +0000199 GS.StoredOnceValue == StoredVal) {
Chris Lattner617f1a32004-10-07 21:30:30 +0000200 // noop.
201 } else {
202 GS.StoredType = GlobalStatus::isStored;
203 }
204 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000205 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000206 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000207 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000208 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000209
210 // If the first two indices are constants, this can be SRA'd.
211 if (isa<GlobalVariable>(I->getOperand(0))) {
212 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
Misha Brukmanb1c93172005-04-21 23:48:37 +0000213 !cast<Constant>(I->getOperand(1))->isNullValue() ||
Chris Lattner004e2502004-10-11 05:54:41 +0000214 !isa<ConstantInt>(I->getOperand(2)))
215 GS.isNotSuitableForSRA = true;
216 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
217 if (CE->getOpcode() != Instruction::GetElementPtr ||
218 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
219 !isa<Constant>(I->getOperand(0)) ||
220 !cast<Constant>(I->getOperand(0))->isNullValue())
221 GS.isNotSuitableForSRA = true;
222 } else {
223 GS.isNotSuitableForSRA = true;
224 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000225 } else if (isa<SelectInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000226 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
227 GS.isNotSuitableForSRA = true;
228 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
229 // PHI nodes we can check just like select or GEP instructions, but we
230 // have to be careful about infinite recursion.
231 if (PHIUsers.insert(PN).second) // Not already visited.
232 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
233 GS.isNotSuitableForSRA = true;
234 } else if (isa<SetCondInst>(I)) {
235 GS.isNotSuitableForSRA = true;
Chris Lattner7561ca12005-02-27 18:58:52 +0000236 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
237 if (I->getOperand(1) == V)
238 GS.StoredType = GlobalStatus::isStored;
239 if (I->getOperand(2) == V)
240 GS.isLoaded = true;
241 GS.isNotSuitableForSRA = true;
242 } else if (isa<MemSetInst>(I)) {
243 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
244 GS.StoredType = GlobalStatus::isStored;
245 GS.isNotSuitableForSRA = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000246 } else {
247 return true; // Any other non-load instruction might take address!
248 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000249 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000250 GS.HasNonInstructionUser = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000251 // We might have a dead and dangling constant hanging off of here.
252 if (!ConstantIsDead(C))
253 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000254 } else {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000255 GS.HasNonInstructionUser = true;
256 // Otherwise must be some other user.
Chris Lattner25db5802004-10-07 04:16:33 +0000257 return true;
258 }
259
260 return false;
261}
262
Chris Lattnerabab0712004-10-08 17:32:09 +0000263static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
264 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
265 if (!CI) return 0;
Chris Lattner46fa04b2005-01-08 19:45:31 +0000266 unsigned IdxV = (unsigned)CI->getRawValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000267
Chris Lattnerabab0712004-10-08 17:32:09 +0000268 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
269 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
270 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
271 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
272 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
273 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000274 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000275 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
276 if (IdxV < STy->getNumElements())
277 return Constant::getNullValue(STy->getElementType(IdxV));
278 } else if (const SequentialType *STy =
279 dyn_cast<SequentialType>(Agg->getType())) {
280 return Constant::getNullValue(STy->getElementType());
281 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000282 } else if (isa<UndefValue>(Agg)) {
283 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
284 if (IdxV < STy->getNumElements())
285 return UndefValue::get(STy->getElementType(IdxV));
286 } else if (const SequentialType *STy =
287 dyn_cast<SequentialType>(Agg->getType())) {
288 return UndefValue::get(STy->getElementType());
289 }
Chris Lattnerabab0712004-10-08 17:32:09 +0000290 }
291 return 0;
292}
Chris Lattner25db5802004-10-07 04:16:33 +0000293
294static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000295 if (Init == 0) return 0;
Chris Lattner25db5802004-10-07 04:16:33 +0000296 if (GEP->getNumOperands() == 1 ||
297 !isa<Constant>(GEP->getOperand(1)) ||
298 !cast<Constant>(GEP->getOperand(1))->isNullValue())
299 return 0;
300
301 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
302 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
303 if (!Idx) return 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000304 Init = getAggregateConstantElement(Init, Idx);
305 if (Init == 0) return 0;
Chris Lattner25db5802004-10-07 04:16:33 +0000306 }
307 return Init;
308}
309
310/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
311/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000312/// quick scan over the use list to clean up the easy and obvious cruft. This
313/// returns true if it made a change.
314static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
315 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000316 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
317 User *U = *UI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000318
Chris Lattner25db5802004-10-07 04:16:33 +0000319 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000320 if (Init) {
321 // Replace the load with the initializer.
322 LI->replaceAllUsesWith(Init);
323 LI->eraseFromParent();
324 Changed = true;
325 }
Chris Lattner25db5802004-10-07 04:16:33 +0000326 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
327 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000328 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000329 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000330 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
331 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000332 Constant *SubInit = TraverseGEPInitializer(CE, Init);
333 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
334 } else if (CE->getOpcode() == Instruction::Cast &&
335 isa<PointerType>(CE->getType())) {
336 // Pointer cast, delete any stores and memsets to the global.
337 Changed |= CleanupConstantGlobalUsers(CE, 0);
338 }
339
340 if (CE->use_empty()) {
341 CE->destroyConstant();
342 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000343 }
344 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000345 Constant *SubInit = TraverseGEPInitializer(GEP, Init);
346 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000347
Chris Lattnercb9f1522004-10-10 16:43:46 +0000348 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000349 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000350 Changed = true;
351 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000352 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
353 if (MI->getRawDest() == V) {
354 MI->eraseFromParent();
355 Changed = true;
356 }
357
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000358 } else if (Constant *C = dyn_cast<Constant>(U)) {
359 // If we have a chain of dead constantexprs or other things dangling from
360 // us, and if they are all dead, nuke them without remorse.
361 if (ConstantIsDead(C)) {
362 C->destroyConstant();
Chris Lattner7561ca12005-02-27 18:58:52 +0000363 // This could have invalidated UI, start over from scratch.
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000364 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000365 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000366 }
Chris Lattner25db5802004-10-07 04:16:33 +0000367 }
368 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000369 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000370}
371
Chris Lattnerabab0712004-10-08 17:32:09 +0000372/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
373/// variable. This opens the door for other optimizations by exposing the
374/// behavior of the program in a more fine-grained way. We have determined that
375/// this transformation is safe already. We return the first global variable we
376/// insert so that the caller can reprocess it.
377static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
378 assert(GV->hasInternalLinkage() && !GV->isConstant());
379 Constant *Init = GV->getInitializer();
380 const Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000381
Chris Lattnerabab0712004-10-08 17:32:09 +0000382 std::vector<GlobalVariable*> NewGlobals;
383 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
384
385 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
386 NewGlobals.reserve(STy->getNumElements());
387 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
388 Constant *In = getAggregateConstantElement(Init,
389 ConstantUInt::get(Type::UIntTy, i));
390 assert(In && "Couldn't get element of initializer?");
391 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
392 GlobalVariable::InternalLinkage,
393 In, GV->getName()+"."+utostr(i));
394 Globals.insert(GV, NGV);
395 NewGlobals.push_back(NGV);
396 }
397 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
398 unsigned NumElements = 0;
399 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
400 NumElements = ATy->getNumElements();
401 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
402 NumElements = PTy->getNumElements();
403 else
404 assert(0 && "Unknown aggregate sequential type!");
405
Chris Lattner25169ca2005-02-23 16:53:04 +0000406 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000407 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000408 NewGlobals.reserve(NumElements);
409 for (unsigned i = 0, e = NumElements; i != e; ++i) {
410 Constant *In = getAggregateConstantElement(Init,
411 ConstantUInt::get(Type::UIntTy, i));
412 assert(In && "Couldn't get element of initializer?");
413
414 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
415 GlobalVariable::InternalLinkage,
416 In, GV->getName()+"."+utostr(i));
417 Globals.insert(GV, NGV);
418 NewGlobals.push_back(NGV);
419 }
420 }
421
422 if (NewGlobals.empty())
423 return 0;
424
Chris Lattner004e2502004-10-11 05:54:41 +0000425 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
426
Chris Lattnerabab0712004-10-08 17:32:09 +0000427 Constant *NullInt = Constant::getNullValue(Type::IntTy);
428
429 // Loop over all of the uses of the global, replacing the constantexpr geps,
430 // with smaller constantexpr geps or direct references.
431 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000432 User *GEP = GV->use_back();
433 assert(((isa<ConstantExpr>(GEP) &&
434 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
435 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000436
Chris Lattnerabab0712004-10-08 17:32:09 +0000437 // Ignore the 1th operand, which has to be zero or else the program is quite
438 // broken (undefined). Get the 2nd operand, which is the structure or array
439 // index.
Chris Lattner46fa04b2005-01-08 19:45:31 +0000440 unsigned Val =
441 (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000442 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
443
Chris Lattner004e2502004-10-11 05:54:41 +0000444 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000445
446 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000447 if (GEP->getNumOperands() > 3)
448 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
449 std::vector<Constant*> Idxs;
450 Idxs.push_back(NullInt);
451 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
452 Idxs.push_back(CE->getOperand(i));
453 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
454 } else {
455 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
456 std::vector<Value*> Idxs;
457 Idxs.push_back(NullInt);
458 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
459 Idxs.push_back(GEPI->getOperand(i));
460 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
461 GEPI->getName()+"."+utostr(Val), GEPI);
462 }
463 GEP->replaceAllUsesWith(NewPtr);
464
465 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000466 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000467 else
468 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000469 }
470
Chris Lattner73ad73e2004-10-08 20:25:55 +0000471 // Delete the old global, now that it is dead.
472 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000473 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000474
475 // Loop over the new globals array deleting any globals that are obviously
476 // dead. This can arise due to scalarization of a structure or an array that
477 // has elements that are dead.
478 unsigned FirstGlobal = 0;
479 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
480 if (NewGlobals[i]->use_empty()) {
481 Globals.erase(NewGlobals[i]);
482 if (FirstGlobal == i) ++FirstGlobal;
483 }
484
485 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000486}
487
Chris Lattner09a52722004-10-09 21:48:45 +0000488/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
489/// value will trap if the value is dynamically null.
490static bool AllUsesOfValueWillTrapIfNull(Value *V) {
491 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
492 if (isa<LoadInst>(*UI)) {
493 // Will trap.
494 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
495 if (SI->getOperand(0) == V) {
496 //std::cerr << "NONTRAPPING USE: " << **UI;
497 return false; // Storing the value.
498 }
499 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
500 if (CI->getOperand(0) != V) {
501 //std::cerr << "NONTRAPPING USE: " << **UI;
502 return false; // Not calling the ptr
503 }
504 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
505 if (II->getOperand(0) != V) {
506 //std::cerr << "NONTRAPPING USE: " << **UI;
507 return false; // Not calling the ptr
508 }
509 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
510 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
511 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
512 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000513 } else if (isa<SetCondInst>(*UI) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000514 isa<ConstantPointerNull>(UI->getOperand(1))) {
515 // Ignore setcc X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000516 } else {
517 //std::cerr << "NONTRAPPING USE: " << **UI;
518 return false;
519 }
520 return true;
521}
522
523/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000524/// from GV will trap if the loaded value is null. Note that this also permits
525/// comparisons of the loaded value against null, as a special case.
Chris Lattner09a52722004-10-09 21:48:45 +0000526static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
527 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
528 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
529 if (!AllUsesOfValueWillTrapIfNull(LI))
530 return false;
531 } else if (isa<StoreInst>(*UI)) {
532 // Ignore stores to the global.
533 } else {
534 // We don't know or understand this user, bail out.
535 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
536 return false;
537 }
538
539 return true;
540}
541
Chris Lattnere42eb312004-10-10 23:14:11 +0000542static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
543 bool Changed = false;
544 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
545 Instruction *I = cast<Instruction>(*UI++);
546 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
547 LI->setOperand(0, NewV);
548 Changed = true;
549 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
550 if (SI->getOperand(1) == V) {
551 SI->setOperand(1, NewV);
552 Changed = true;
553 }
554 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
555 if (I->getOperand(0) == V) {
556 // Calling through the pointer! Turn into a direct call, but be careful
557 // that the pointer is not also being passed as an argument.
558 I->setOperand(0, NewV);
559 Changed = true;
560 bool PassedAsArg = false;
561 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
562 if (I->getOperand(i) == V) {
563 PassedAsArg = true;
564 I->setOperand(i, NewV);
565 }
566
567 if (PassedAsArg) {
568 // Being passed as an argument also. Be careful to not invalidate UI!
569 UI = V->use_begin();
570 }
571 }
572 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
573 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
574 ConstantExpr::getCast(NewV, CI->getType()));
575 if (CI->use_empty()) {
576 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000577 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000578 }
579 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
580 // Should handle GEP here.
581 std::vector<Constant*> Indices;
582 Indices.reserve(GEPI->getNumOperands()-1);
583 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
584 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
585 Indices.push_back(C);
586 else
587 break;
588 if (Indices.size() == GEPI->getNumOperands()-1)
589 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
590 ConstantExpr::getGetElementPtr(NewV, Indices));
591 if (GEPI->use_empty()) {
592 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000593 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000594 }
595 }
596 }
597
598 return Changed;
599}
600
601
602/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
603/// value stored into it. If there are uses of the loaded value that would trap
604/// if the loaded value is dynamically null, then we know that they cannot be
605/// reachable with a null optimize away the load.
606static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
607 std::vector<LoadInst*> Loads;
608 bool Changed = false;
609
610 // Replace all uses of loads with uses of uses of the stored value.
611 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
612 GUI != E; ++GUI)
613 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
614 Loads.push_back(LI);
615 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
616 } else {
617 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
618 }
619
620 if (Changed) {
621 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
622 ++NumGlobUses;
623 }
624
625 // Delete all of the loads we can, keeping track of whether we nuked them all!
626 bool AllLoadsGone = true;
627 while (!Loads.empty()) {
628 LoadInst *L = Loads.back();
629 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000630 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000631 Changed = true;
632 } else {
633 AllLoadsGone = false;
634 }
635 Loads.pop_back();
636 }
637
638 // If we nuked all of the loads, then none of the stores are needed either,
639 // nor is the global.
640 if (AllLoadsGone) {
641 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
642 CleanupConstantGlobalUsers(GV, 0);
643 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000644 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000645 ++NumDeleted;
646 }
647 Changed = true;
648 }
649 return Changed;
650}
651
Chris Lattner004e2502004-10-11 05:54:41 +0000652/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
653/// instructions that are foldable.
654static void ConstantPropUsersOf(Value *V) {
655 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
656 if (Instruction *I = dyn_cast<Instruction>(*UI++))
657 if (Constant *NewC = ConstantFoldInstruction(I)) {
658 I->replaceAllUsesWith(NewC);
659
Chris Lattnerd6a44922005-02-01 01:23:31 +0000660 // Advance UI to the next non-I use to avoid invalidating it!
661 // Instructions could multiply use V.
662 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000663 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000664 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000665 }
666}
667
668/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
669/// variable, and transforms the program as if it always contained the result of
670/// the specified malloc. Because it is always the result of the specified
671/// malloc, there is no reason to actually DO the malloc. Instead, turn the
672/// malloc into a global, and any laods of GV as uses of the new global.
673static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
674 MallocInst *MI) {
675 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
676 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
677
678 if (NElements->getRawValue() != 1) {
679 // If we have an array allocation, transform it to a single element
680 // allocation to make the code below simpler.
681 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Chris Lattner46fa04b2005-01-08 19:45:31 +0000682 (unsigned)NElements->getRawValue());
Chris Lattner004e2502004-10-11 05:54:41 +0000683 MallocInst *NewMI =
684 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
685 MI->getName(), MI);
686 std::vector<Value*> Indices;
687 Indices.push_back(Constant::getNullValue(Type::IntTy));
688 Indices.push_back(Indices[0]);
689 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
690 NewMI->getName()+".el0", MI);
691 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000692 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000693 MI = NewMI;
694 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000695
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000696 // Create the new global variable. The contents of the malloc'd memory is
697 // undefined, so initialize with an undef value.
698 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000699 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
700 GlobalValue::InternalLinkage, Init,
701 GV->getName()+".body");
702 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000703
Chris Lattner004e2502004-10-11 05:54:41 +0000704 // Anything that used the malloc now uses the global directly.
705 MI->replaceAllUsesWith(NewGV);
Chris Lattner004e2502004-10-11 05:54:41 +0000706
707 Constant *RepValue = NewGV;
708 if (NewGV->getType() != GV->getType()->getElementType())
709 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
710
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000711 // If there is a comparison against null, we will insert a global bool to
712 // keep track of whether the global was initialized yet or not.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000713 GlobalVariable *InitBool =
714 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
Chris Lattner3b181392004-12-02 06:25:58 +0000715 ConstantBool::False, GV->getName()+".init");
716 bool InitBoolUsed = false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000717
Chris Lattner004e2502004-10-11 05:54:41 +0000718 // Loop over all uses of GV, processing them in turn.
Chris Lattner3b181392004-12-02 06:25:58 +0000719 std::vector<StoreInst*> Stores;
Chris Lattner004e2502004-10-11 05:54:41 +0000720 while (!GV->use_empty())
721 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000722 while (!LI->use_empty()) {
Chris Lattnerd6a44922005-02-01 01:23:31 +0000723 Use &LoadUse = LI->use_begin().getUse();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000724 if (!isa<SetCondInst>(LoadUse.getUser()))
725 LoadUse = RepValue;
726 else {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000727 // Replace the setcc X, 0 with a use of the bool value.
728 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
729 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattner3b181392004-12-02 06:25:58 +0000730 InitBoolUsed = true;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000731 switch (SCI->getOpcode()) {
732 default: assert(0 && "Unknown opcode!");
733 case Instruction::SetLT:
734 LV = ConstantBool::False; // X < null -> always false
735 break;
736 case Instruction::SetEQ:
737 case Instruction::SetLE:
738 LV = BinaryOperator::createNot(LV, "notinit", SCI);
739 break;
740 case Instruction::SetNE:
741 case Instruction::SetGE:
742 case Instruction::SetGT:
743 break; // no change.
744 }
745 SCI->replaceAllUsesWith(LV);
746 SCI->eraseFromParent();
747 }
748 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000749 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000750 } else {
751 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner3b181392004-12-02 06:25:58 +0000752 // The global is initialized when the store to it occurs.
753 new StoreInst(ConstantBool::True, InitBool, SI);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000754 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000755 }
756
Chris Lattner3b181392004-12-02 06:25:58 +0000757 // If the initialization boolean was used, insert it, otherwise delete it.
758 if (!InitBoolUsed) {
759 while (!InitBool->use_empty()) // Delete initializations
760 cast<Instruction>(InitBool->use_back())->eraseFromParent();
761 delete InitBool;
762 } else
763 GV->getParent()->getGlobalList().insert(GV, InitBool);
764
765
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000766 // Now the GV is dead, nuke it and the malloc.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000767 GV->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000768 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000769
770 // To further other optimizations, loop over all users of NewGV and try to
771 // constant prop them. This will promote GEP instructions with constant
772 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
773 ConstantPropUsersOf(NewGV);
774 if (RepValue != NewGV)
775 ConstantPropUsersOf(RepValue);
776
777 return NewGV;
778}
Chris Lattnere42eb312004-10-10 23:14:11 +0000779
Chris Lattnerc0677c02004-12-02 07:11:07 +0000780/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
781/// to make sure that there are no complex uses of V. We permit simple things
782/// like dereferencing the pointer, but not storing through the address, unless
783/// it is to the specified global.
784static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
785 GlobalVariable *GV) {
786 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
787 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
788 // Fine, ignore.
789 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
790 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
791 return false; // Storing the pointer itself... bad.
792 // Otherwise, storing through it, or storing into GV... fine.
793 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
794 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
795 return false;
796 } else {
797 return false;
798 }
799 return true;
800
801}
802
Chris Lattner09a52722004-10-09 21:48:45 +0000803// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
804// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +0000805static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner531f9e92005-03-15 04:54:21 +0000806 Module::global_iterator &GVI, TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +0000807 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
808 StoredOnceVal = CI->getOperand(0);
809 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +0000810 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +0000811 bool IsJustACast = true;
812 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
813 if (!isa<Constant>(GEPI->getOperand(i)) ||
814 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
815 IsJustACast = false;
816 break;
817 }
818 if (IsJustACast)
819 StoredOnceVal = GEPI->getOperand(0);
820 }
821
Chris Lattnere42eb312004-10-10 23:14:11 +0000822 // If we are dealing with a pointer global that is initialized to null and
823 // only has one (non-null) value stored into it, then we can optimize any
824 // users of the loaded value (often calls and loads) that would trap if the
825 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +0000826 if (isa<PointerType>(GV->getInitializer()->getType()) &&
827 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000828 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
829 if (GV->getInitializer()->getType() != SOVC->getType())
830 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000831
Chris Lattnere42eb312004-10-10 23:14:11 +0000832 // Optimize away any trapping uses of the loaded value.
833 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +0000834 return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000835 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
836 // If we have a global that is only initialized with a fixed size malloc,
837 // and if all users of the malloc trap, and if the malloc'd address is not
838 // put anywhere else, transform the program to use global memory instead
839 // of malloc'd memory. This eliminates dynamic allocation (good) and
840 // exposes the resultant global to further GlobalOpt (even better). Note
841 // that we restrict this transformation to only working on small
842 // allocations (2048 bytes currently), as we don't want to introduce a 16M
843 // global or something.
844 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
845 if (MI->getAllocatedType()->isSized() &&
846 NElements->getRawValue()*
847 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
Chris Lattnerc0677c02004-12-02 07:11:07 +0000848 AllUsesOfLoadedValueWillTrapIfNull(GV) &&
849 ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000850 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
851 return true;
852 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000853 }
Chris Lattner09a52722004-10-09 21:48:45 +0000854 }
Chris Lattner004e2502004-10-11 05:54:41 +0000855
Chris Lattner09a52722004-10-09 21:48:45 +0000856 return false;
857}
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000858
Chris Lattner40e4cec2004-12-12 05:53:50 +0000859/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
Misha Brukmanb1c93172005-04-21 23:48:37 +0000860/// values ever stored into GV are its initializer and OtherVal.
Chris Lattner40e4cec2004-12-12 05:53:50 +0000861static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
862 // Create the new global, initializing it to false.
863 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
864 GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b");
865 GV->getParent()->getGlobalList().insert(GV, NewGV);
866
867 Constant *InitVal = GV->getInitializer();
868 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
869
870 // If initialized to zero and storing one into the global, we can use a cast
871 // instead of a select to synthesize the desired value.
872 bool IsOneZero = false;
873 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
874 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
875
876 while (!GV->use_empty()) {
877 Instruction *UI = cast<Instruction>(GV->use_back());
878 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
879 // Change the store into a boolean store.
880 bool StoringOther = SI->getOperand(0) == OtherVal;
881 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +0000882 Value *StoreVal;
Chris Lattner40e4cec2004-12-12 05:53:50 +0000883 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner745196a2004-12-12 19:34:41 +0000884 StoreVal = ConstantBool::get(StoringOther);
885 else {
886 // Otherwise, we are storing a previously loaded copy. To do this,
887 // change the copy from copying the original value to just copying the
888 // bool.
889 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
890
891 // If we're already replaced the input, StoredVal will be a cast or
892 // select instruction. If not, it will be a load of the original
893 // global.
894 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
895 assert(LI->getOperand(0) == GV && "Not a copy!");
896 // Insert a new load, to preserve the saved value.
897 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
898 } else {
899 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
900 "This is not a form that we understand!");
901 StoreVal = StoredVal->getOperand(0);
902 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
903 }
904 }
905 new StoreInst(StoreVal, NewGV, SI);
906 } else if (!UI->use_empty()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +0000907 // Change the load into a load of bool then a select.
908 LoadInst *LI = cast<LoadInst>(UI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000909
Chris Lattner40e4cec2004-12-12 05:53:50 +0000910 std::string Name = LI->getName(); LI->setName("");
911 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
912 Value *NSI;
913 if (IsOneZero)
914 NSI = new CastInst(NLI, LI->getType(), Name, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000915 else
Chris Lattner40e4cec2004-12-12 05:53:50 +0000916 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
917 LI->replaceAllUsesWith(NSI);
918 }
919 UI->eraseFromParent();
920 }
921
922 GV->eraseFromParent();
923}
924
925
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000926/// ProcessInternalGlobal - Analyze the specified global variable and optimize
927/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +0000928bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattner531f9e92005-03-15 04:54:21 +0000929 Module::global_iterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000930 std::set<PHINode*> PHIUsers;
931 GlobalStatus GS;
932 PHIUsers.clear();
933 GV->removeDeadConstantUsers();
934
935 if (GV->use_empty()) {
936 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000937 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000938 ++NumDeleted;
939 return true;
940 }
941
942 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000943 // If this is a first class global and has only one accessing function
944 // and this function is main (which we know is not recursive we can make
945 // this global a local variable) we replace the global with a local alloca
946 // in this function.
947 //
948 // NOTE: It doesn't make sense to promote non first class types since we
949 // are just replacing static memory to stack memory.
950 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000951 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000952 GV->getType()->getElementType()->isFirstClassType() &&
953 GS.AccessingFunction->getName() == "main" &&
954 GS.AccessingFunction->hasExternalLinkage()) {
955 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
956 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
957 const Type* ElemTy = GV->getType()->getElementType();
958 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
959 if (!isa<UndefValue>(GV->getInitializer()))
960 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000961
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000962 GV->replaceAllUsesWith(Alloca);
963 GV->eraseFromParent();
964 ++NumLocalized;
965 return true;
966 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000967 // If the global is never loaded (but may be stored to), it is dead.
968 // Delete it now.
969 if (!GS.isLoaded) {
970 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +0000971
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000972 // Delete any stores we can find to the global. We may not be able to
973 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +0000974 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +0000975
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000976 // If the global is dead now, delete it.
977 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000978 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000979 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +0000980 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000981 }
Chris Lattnerf369b382004-10-09 03:32:52 +0000982 return Changed;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000983
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000984 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
985 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
986 GV->setConstant(true);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000987
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000988 // Clean up any obviously simplifiable users now.
989 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000990
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000991 // If the global is dead now, just nuke it.
992 if (GV->use_empty()) {
993 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
994 "all users and delete global!\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000995 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000996 ++NumDeleted;
997 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000998
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000999 ++NumMarked;
1000 return true;
1001 } else if (!GS.isNotSuitableForSRA &&
1002 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001003 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1004 GVI = FirstNewGV; // Don't skip the newly produced globals!
1005 return true;
1006 }
Chris Lattner09a52722004-10-09 21:48:45 +00001007 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001008 // If the initial value for the global was an undef value, and if only
1009 // one other value was stored into it, we can just change the
1010 // initializer to be an undef value, then delete all stores to the
1011 // global. This allows us to mark it constant.
1012 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1013 if (isa<UndefValue>(GV->getInitializer())) {
1014 // Change the initial value here.
1015 GV->setInitializer(SOVConstant);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001016
Chris Lattner40e4cec2004-12-12 05:53:50 +00001017 // Clean up any obviously simplifiable users now.
1018 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001019
Chris Lattner40e4cec2004-12-12 05:53:50 +00001020 if (GV->use_empty()) {
1021 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
1022 "simplify all users and delete global!\n");
1023 GV->eraseFromParent();
1024 ++NumDeleted;
1025 } else {
1026 GVI = GV;
1027 }
1028 ++NumSubstitute;
1029 return true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001030 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001031
Chris Lattner09a52722004-10-09 21:48:45 +00001032 // Try to optimize globals based on the knowledge that only one value
1033 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001034 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1035 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +00001036 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001037
1038 // Otherwise, if the global was not a boolean, we can shrink it to be a
1039 // boolean.
1040 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner1cbd5be2004-12-12 06:03:06 +00001041 if (GV->getType()->getElementType() != Type::BoolTy &&
1042 !GV->getType()->getElementType()->isFloatingPoint()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001043 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
1044 ShrinkGlobalToBoolean(GV, SOVConstant);
1045 ++NumShrunkToBool;
1046 return true;
1047 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001048 }
1049 }
1050 return false;
1051}
1052
Chris Lattnera4c80222005-05-08 22:18:06 +00001053/// OnlyCalledDirectly - Return true if the specified function is only called
1054/// directly. In other words, its address is never taken.
1055static bool OnlyCalledDirectly(Function *F) {
1056 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1057 Instruction *User = dyn_cast<Instruction>(*UI);
1058 if (!User) return false;
1059 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1060
1061 // See if the function address is passed as an argument.
1062 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1063 if (User->getOperand(i) == F) return false;
1064 }
1065 return true;
1066}
1067
1068/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1069/// function, changing them to FastCC.
1070static void ChangeCalleesToFastCall(Function *F) {
1071 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1072 Instruction *User = cast<Instruction>(*UI);
1073 if (CallInst *CI = dyn_cast<CallInst>(User))
1074 CI->setCallingConv(CallingConv::Fast);
1075 else
1076 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1077 }
1078}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001079
Chris Lattner25db5802004-10-07 04:16:33 +00001080bool GlobalOpt::runOnModule(Module &M) {
1081 bool Changed = false;
1082
1083 // As a prepass, delete functions that are trivially dead.
1084 bool LocalChange = true;
1085 while (LocalChange) {
1086 LocalChange = false;
1087 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1088 Function *F = FI++;
1089 F->removeDeadConstantUsers();
Chris Lattner5d33e8e2004-10-14 19:53:50 +00001090 if (F->use_empty() && (F->hasInternalLinkage() ||
1091 F->hasLinkOnceLinkage())) {
Chris Lattner25db5802004-10-07 04:16:33 +00001092 M.getFunctionList().erase(F);
1093 LocalChange = true;
1094 ++NumFnDeleted;
Chris Lattnera4c80222005-05-08 22:18:06 +00001095 } else if (F->hasInternalLinkage() &&
1096 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1097 OnlyCalledDirectly(F)) {
1098 // If this function has C calling conventions, is not a varargs
1099 // function, and is only called directly, promote it to use the Fast
1100 // calling convention.
1101 F->setCallingConv(CallingConv::Fast);
1102 ChangeCalleesToFastCall(F);
1103 ++NumFastCallFns;
1104 LocalChange = true;
Chris Lattner25db5802004-10-07 04:16:33 +00001105 }
1106 }
1107 Changed |= LocalChange;
1108 }
1109
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001110 LocalChange = true;
1111 while (LocalChange) {
1112 LocalChange = false;
Chris Lattnera4c80222005-05-08 22:18:06 +00001113 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1114 GVI != E; ) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001115 GlobalVariable *GV = GVI++;
1116 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1117 GV->hasInitializer())
1118 LocalChange |= ProcessInternalGlobal(GV, GVI);
Chris Lattner25db5802004-10-07 04:16:33 +00001119 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001120 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +00001121 }
1122 return Changed;
1123}