blob: 6cdd530a11d4e93644e0e6d089e0fbec0e9c8eb8 [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 <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000031#include <iostream>
32#include <set>
Chris Lattner25db5802004-10-07 04:16:33 +000033using namespace llvm;
34
35namespace {
Chris Lattnerabab0712004-10-08 17:32:09 +000036 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
37 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
38 "into scalars");
Chris Lattner24d3d422006-09-30 23:32:09 +000039 Statistic<> NumHeapSRA ("globalopt", "Number of heap objects SRA'd");
Chris Lattner8e71c6a2004-10-16 18:09:00 +000040 Statistic<> NumSubstitute("globalopt",
41 "Number of globals with initializers stored into them");
Chris Lattnerabab0712004-10-08 17:32:09 +000042 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner25db5802004-10-07 04:16:33 +000043 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
Chris Lattnere42eb312004-10-10 23:14:11 +000044 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +000045 Statistic<> NumLocalized("globalopt", "Number of globals localized");
Chris Lattner40e4cec2004-12-12 05:53:50 +000046 Statistic<> NumShrunkToBool("globalopt",
47 "Number of global vars shrunk to booleans");
Chris Lattnera4c80222005-05-08 22:18:06 +000048 Statistic<> NumFastCallFns("globalopt",
49 "Number of functions converted to fastcc");
Chris Lattner99e23fa2005-09-26 04:44:35 +000050 Statistic<> NumCtorsEvaluated("globalopt","Number of static ctors evaluated");
Chris Lattner25db5802004-10-07 04:16:33 +000051
52 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000053 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 AU.addRequired<TargetData>();
55 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000056
Chris Lattner25db5802004-10-07 04:16:33 +000057 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000058
59 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000060 GlobalVariable *FindGlobalCtors(Module &M);
61 bool OptimizeFunctions(Module &M);
62 bool OptimizeGlobalVars(Module &M);
63 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattnerc2d3d312006-08-27 22:42:52 +000064 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000065 };
66
Chris Lattnerc2d3d312006-08-27 22:42:52 +000067 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
Chris Lattner25db5802004-10-07 04:16:33 +000068}
69
70ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
71
72/// GlobalStatus - As we analyze each global, keep track of some information
73/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000074/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000075struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000076 /// isLoaded - True if the global is ever loaded. If the global isn't ever
77 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000078 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000079
80 /// StoredType - Keep track of what stores to the global look like.
81 ///
Chris Lattner25db5802004-10-07 04:16:33 +000082 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000083 /// NotStored - There is no store to this global. It can thus be marked
84 /// constant.
85 NotStored,
86
87 /// isInitializerStored - This global is stored to, but the only thing
88 /// stored is the constant it was initialized with. This is only tracked
89 /// for scalar globals.
90 isInitializerStored,
91
92 /// isStoredOnce - This global is stored to, but only its initializer and
93 /// one other value is ever stored to it. If this global isStoredOnce, we
94 /// track the value stored to it in StoredOnceValue below. This is only
95 /// tracked for scalar globals.
96 isStoredOnce,
97
98 /// isStored - This global is stored to by multiple values or something else
99 /// that we cannot track.
100 isStored
Chris Lattner25db5802004-10-07 04:16:33 +0000101 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +0000102
103 /// StoredOnceValue - If only one value (besides the initializer constant) is
104 /// ever stored to this global, keep track of what value it is.
105 Value *StoredOnceValue;
106
Chris Lattner5a0bd612006-11-01 18:03:33 +0000107 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
108 /// null/false. When the first accessing function is noticed, it is recorded.
109 /// When a second different accessing function is noticed,
110 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000111 Function *AccessingFunction;
112 bool HasMultipleAccessingFunctions;
113
Chris Lattner5a0bd612006-11-01 18:03:33 +0000114 /// HasNonInstructionUser - Set to true if this global has a user that is not
115 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000116 bool HasNonInstructionUser;
117
Chris Lattner5a0bd612006-11-01 18:03:33 +0000118 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
119 bool HasPHIUser;
120
Chris Lattner617f1a32004-10-07 21:30:30 +0000121 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
122 /// the global exist. Such users include GEP instruction with variable
123 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +0000124 bool isNotSuitableForSRA;
125
Chris Lattner617f1a32004-10-07 21:30:30 +0000126 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000127 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner5a0bd612006-11-01 18:03:33 +0000128 HasNonInstructionUser(false), HasPHIUser(false),
129 isNotSuitableForSRA(false) {}
Chris Lattner25db5802004-10-07 04:16:33 +0000130};
131
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000132
133
134/// ConstantIsDead - Return true if the specified constant is (transitively)
135/// dead. The constant may be used by other constants (e.g. constant arrays and
136/// constant exprs) as long as they are dead, but it cannot be used by anything
137/// else.
138static bool ConstantIsDead(Constant *C) {
139 if (isa<GlobalValue>(C)) return false;
140
141 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
142 if (Constant *CU = dyn_cast<Constant>(*UI)) {
143 if (!ConstantIsDead(CU)) return false;
144 } else
145 return false;
146 return true;
147}
148
149
Chris Lattner25db5802004-10-07 04:16:33 +0000150/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
151/// structure. If the global has its address taken, return true to indicate we
152/// can't do anything with it.
153///
154static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
155 std::set<PHINode*> &PHIUsers) {
156 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
157 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000158 GS.HasNonInstructionUser = true;
159
Chris Lattner25db5802004-10-07 04:16:33 +0000160 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
161 if (CE->getOpcode() != Instruction::GetElementPtr)
162 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000163 else if (!GS.isNotSuitableForSRA) {
164 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
165 // don't like < 3 operand CE's, and we don't like non-constant integer
166 // indices.
167 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
168 GS.isNotSuitableForSRA = true;
169 else {
170 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
171 if (!isa<ConstantInt>(CE->getOperand(i))) {
172 GS.isNotSuitableForSRA = true;
173 break;
174 }
175 }
176 }
177
Chris Lattner25db5802004-10-07 04:16:33 +0000178 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000179 if (!GS.HasMultipleAccessingFunctions) {
180 Function *F = I->getParent()->getParent();
181 if (GS.AccessingFunction == 0)
182 GS.AccessingFunction = F;
183 else if (GS.AccessingFunction != F)
184 GS.HasMultipleAccessingFunctions = true;
185 }
Chris Lattner25db5802004-10-07 04:16:33 +0000186 if (isa<LoadInst>(I)) {
187 GS.isLoaded = true;
188 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000189 // Don't allow a store OF the address, only stores TO the address.
190 if (SI->getOperand(0) == V) return true;
191
Chris Lattner617f1a32004-10-07 21:30:30 +0000192 // If this is a direct store to the global (i.e., the global is a scalar
193 // value, not an aggregate), keep more specific information about
194 // stores.
195 if (GS.StoredType != GlobalStatus::isStored)
196 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattner28eeb732004-11-14 20:50:30 +0000197 Value *StoredVal = SI->getOperand(0);
198 if (StoredVal == GV->getInitializer()) {
199 if (GS.StoredType < GlobalStatus::isInitializerStored)
200 GS.StoredType = GlobalStatus::isInitializerStored;
201 } else if (isa<LoadInst>(StoredVal) &&
202 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
203 // G = G
Chris Lattner617f1a32004-10-07 21:30:30 +0000204 if (GS.StoredType < GlobalStatus::isInitializerStored)
205 GS.StoredType = GlobalStatus::isInitializerStored;
206 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
207 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattner28eeb732004-11-14 20:50:30 +0000208 GS.StoredOnceValue = StoredVal;
Chris Lattner617f1a32004-10-07 21:30:30 +0000209 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattner28eeb732004-11-14 20:50:30 +0000210 GS.StoredOnceValue == StoredVal) {
Chris Lattner617f1a32004-10-07 21:30:30 +0000211 // noop.
212 } else {
213 GS.StoredType = GlobalStatus::isStored;
214 }
215 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000216 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000217 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000218 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000219 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000220
221 // If the first two indices are constants, this can be SRA'd.
222 if (isa<GlobalVariable>(I->getOperand(0))) {
223 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
Misha Brukmanb1c93172005-04-21 23:48:37 +0000224 !cast<Constant>(I->getOperand(1))->isNullValue() ||
Chris Lattner004e2502004-10-11 05:54:41 +0000225 !isa<ConstantInt>(I->getOperand(2)))
226 GS.isNotSuitableForSRA = true;
227 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
228 if (CE->getOpcode() != Instruction::GetElementPtr ||
229 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
230 !isa<Constant>(I->getOperand(0)) ||
231 !cast<Constant>(I->getOperand(0))->isNullValue())
232 GS.isNotSuitableForSRA = true;
233 } else {
234 GS.isNotSuitableForSRA = true;
235 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000236 } else if (isa<SelectInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000237 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
238 GS.isNotSuitableForSRA = true;
239 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
240 // PHI nodes we can check just like select or GEP instructions, but we
241 // have to be careful about infinite recursion.
242 if (PHIUsers.insert(PN).second) // Not already visited.
243 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
244 GS.isNotSuitableForSRA = true;
Chris Lattner5a0bd612006-11-01 18:03:33 +0000245 GS.HasPHIUser = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000246 } else if (isa<SetCondInst>(I)) {
247 GS.isNotSuitableForSRA = true;
Chris Lattner7561ca12005-02-27 18:58:52 +0000248 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
249 if (I->getOperand(1) == V)
250 GS.StoredType = GlobalStatus::isStored;
251 if (I->getOperand(2) == V)
252 GS.isLoaded = true;
253 GS.isNotSuitableForSRA = true;
254 } else if (isa<MemSetInst>(I)) {
255 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
256 GS.StoredType = GlobalStatus::isStored;
257 GS.isNotSuitableForSRA = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000258 } else {
259 return true; // Any other non-load instruction might take address!
260 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000261 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000262 GS.HasNonInstructionUser = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000263 // We might have a dead and dangling constant hanging off of here.
264 if (!ConstantIsDead(C))
265 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000266 } else {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000267 GS.HasNonInstructionUser = true;
268 // Otherwise must be some other user.
Chris Lattner25db5802004-10-07 04:16:33 +0000269 return true;
270 }
271
272 return false;
273}
274
Chris Lattnerabab0712004-10-08 17:32:09 +0000275static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
276 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
277 if (!CI) return 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000278 unsigned IdxV = CI->getZExtValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000279
Chris Lattnerabab0712004-10-08 17:32:09 +0000280 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
281 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
282 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
283 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
284 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
285 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000286 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000287 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
288 if (IdxV < STy->getNumElements())
289 return Constant::getNullValue(STy->getElementType(IdxV));
290 } else if (const SequentialType *STy =
291 dyn_cast<SequentialType>(Agg->getType())) {
292 return Constant::getNullValue(STy->getElementType());
293 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000294 } else if (isa<UndefValue>(Agg)) {
295 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
296 if (IdxV < STy->getNumElements())
297 return UndefValue::get(STy->getElementType(IdxV));
298 } else if (const SequentialType *STy =
299 dyn_cast<SequentialType>(Agg->getType())) {
300 return UndefValue::get(STy->getElementType());
301 }
Chris Lattnerabab0712004-10-08 17:32:09 +0000302 }
303 return 0;
304}
Chris Lattner25db5802004-10-07 04:16:33 +0000305
Chris Lattner25db5802004-10-07 04:16:33 +0000306
307/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
308/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000309/// quick scan over the use list to clean up the easy and obvious cruft. This
310/// returns true if it made a change.
311static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
312 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000313 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
314 User *U = *UI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000315
Chris Lattner25db5802004-10-07 04:16:33 +0000316 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000317 if (Init) {
318 // Replace the load with the initializer.
319 LI->replaceAllUsesWith(Init);
320 LI->eraseFromParent();
321 Changed = true;
322 }
Chris Lattner25db5802004-10-07 04:16:33 +0000323 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
324 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000325 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000326 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000327 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
328 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner46d9ff082005-09-26 07:34:35 +0000329 Constant *SubInit = 0;
330 if (Init)
331 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000332 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
333 } else if (CE->getOpcode() == Instruction::Cast &&
334 isa<PointerType>(CE->getType())) {
335 // Pointer cast, delete any stores and memsets to the global.
336 Changed |= CleanupConstantGlobalUsers(CE, 0);
337 }
338
339 if (CE->use_empty()) {
340 CE->destroyConstant();
341 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000342 }
343 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner61ff32c2005-09-26 05:34:07 +0000344 Constant *SubInit = 0;
Chris Lattner46af55e2005-09-26 06:52:44 +0000345 ConstantExpr *CE =
346 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattnereb953f02005-09-27 22:28:11 +0000347 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner61ff32c2005-09-26 05:34:07 +0000348 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000349 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000350
Chris Lattnercb9f1522004-10-10 16:43:46 +0000351 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000352 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000353 Changed = true;
354 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000355 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
356 if (MI->getRawDest() == V) {
357 MI->eraseFromParent();
358 Changed = true;
359 }
360
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000361 } else if (Constant *C = dyn_cast<Constant>(U)) {
362 // If we have a chain of dead constantexprs or other things dangling from
363 // us, and if they are all dead, nuke them without remorse.
364 if (ConstantIsDead(C)) {
365 C->destroyConstant();
Chris Lattner7561ca12005-02-27 18:58:52 +0000366 // This could have invalidated UI, start over from scratch.
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000367 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000368 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000369 }
Chris Lattner25db5802004-10-07 04:16:33 +0000370 }
371 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000372 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000373}
374
Chris Lattnerabab0712004-10-08 17:32:09 +0000375/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
376/// variable. This opens the door for other optimizations by exposing the
377/// behavior of the program in a more fine-grained way. We have determined that
378/// this transformation is safe already. We return the first global variable we
379/// insert so that the caller can reprocess it.
380static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
381 assert(GV->hasInternalLinkage() && !GV->isConstant());
382 Constant *Init = GV->getInitializer();
383 const Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000384
Chris Lattnerabab0712004-10-08 17:32:09 +0000385 std::vector<GlobalVariable*> NewGlobals;
386 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
387
388 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
389 NewGlobals.reserve(STy->getNumElements());
390 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
391 Constant *In = getAggregateConstantElement(Init,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000392 ConstantInt::get(Type::UIntTy, i));
Chris Lattnerabab0712004-10-08 17:32:09 +0000393 assert(In && "Couldn't get element of initializer?");
394 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
395 GlobalVariable::InternalLinkage,
396 In, GV->getName()+"."+utostr(i));
397 Globals.insert(GV, NGV);
398 NewGlobals.push_back(NGV);
399 }
400 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
401 unsigned NumElements = 0;
402 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
403 NumElements = ATy->getNumElements();
404 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
405 NumElements = PTy->getNumElements();
406 else
407 assert(0 && "Unknown aggregate sequential type!");
408
Chris Lattner25169ca2005-02-23 16:53:04 +0000409 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000410 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000411 NewGlobals.reserve(NumElements);
412 for (unsigned i = 0, e = NumElements; i != e; ++i) {
413 Constant *In = getAggregateConstantElement(Init,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000414 ConstantInt::get(Type::UIntTy, i));
Chris Lattnerabab0712004-10-08 17:32:09 +0000415 assert(In && "Couldn't get element of initializer?");
416
417 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
418 GlobalVariable::InternalLinkage,
419 In, GV->getName()+"."+utostr(i));
420 Globals.insert(GV, NGV);
421 NewGlobals.push_back(NGV);
422 }
423 }
424
425 if (NewGlobals.empty())
426 return 0;
427
Chris Lattner004e2502004-10-11 05:54:41 +0000428 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
429
Chris Lattnerabab0712004-10-08 17:32:09 +0000430 Constant *NullInt = Constant::getNullValue(Type::IntTy);
431
432 // Loop over all of the uses of the global, replacing the constantexpr geps,
433 // with smaller constantexpr geps or direct references.
434 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000435 User *GEP = GV->use_back();
436 assert(((isa<ConstantExpr>(GEP) &&
437 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
438 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000439
Chris Lattnerabab0712004-10-08 17:32:09 +0000440 // Ignore the 1th operand, which has to be zero or else the program is quite
441 // broken (undefined). Get the 2nd operand, which is the structure or array
442 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000443 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000444 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
445
Chris Lattner004e2502004-10-11 05:54:41 +0000446 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000447
448 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000449 if (GEP->getNumOperands() > 3)
450 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
451 std::vector<Constant*> Idxs;
452 Idxs.push_back(NullInt);
453 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
454 Idxs.push_back(CE->getOperand(i));
455 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
456 } else {
457 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
458 std::vector<Value*> Idxs;
459 Idxs.push_back(NullInt);
460 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
461 Idxs.push_back(GEPI->getOperand(i));
462 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
463 GEPI->getName()+"."+utostr(Val), GEPI);
464 }
465 GEP->replaceAllUsesWith(NewPtr);
466
467 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000468 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000469 else
470 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000471 }
472
Chris Lattner73ad73e2004-10-08 20:25:55 +0000473 // Delete the old global, now that it is dead.
474 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000475 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000476
477 // Loop over the new globals array deleting any globals that are obviously
478 // dead. This can arise due to scalarization of a structure or an array that
479 // has elements that are dead.
480 unsigned FirstGlobal = 0;
481 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
482 if (NewGlobals[i]->use_empty()) {
483 Globals.erase(NewGlobals[i]);
484 if (FirstGlobal == i) ++FirstGlobal;
485 }
486
487 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000488}
489
Chris Lattner09a52722004-10-09 21:48:45 +0000490/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
491/// value will trap if the value is dynamically null.
492static bool AllUsesOfValueWillTrapIfNull(Value *V) {
493 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
494 if (isa<LoadInst>(*UI)) {
495 // Will trap.
496 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
497 if (SI->getOperand(0) == V) {
498 //std::cerr << "NONTRAPPING USE: " << **UI;
499 return false; // Storing the value.
500 }
501 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
502 if (CI->getOperand(0) != V) {
503 //std::cerr << "NONTRAPPING USE: " << **UI;
504 return false; // Not calling the ptr
505 }
506 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
507 if (II->getOperand(0) != V) {
508 //std::cerr << "NONTRAPPING USE: " << **UI;
509 return false; // Not calling the ptr
510 }
511 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
512 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
513 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
514 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000515 } else if (isa<SetCondInst>(*UI) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000516 isa<ConstantPointerNull>(UI->getOperand(1))) {
517 // Ignore setcc X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000518 } else {
519 //std::cerr << "NONTRAPPING USE: " << **UI;
520 return false;
521 }
522 return true;
523}
524
525/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000526/// from GV will trap if the loaded value is null. Note that this also permits
527/// comparisons of the loaded value against null, as a special case.
Chris Lattner09a52722004-10-09 21:48:45 +0000528static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
529 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
530 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
531 if (!AllUsesOfValueWillTrapIfNull(LI))
532 return false;
533 } else if (isa<StoreInst>(*UI)) {
534 // Ignore stores to the global.
535 } else {
536 // We don't know or understand this user, bail out.
537 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
538 return false;
539 }
540
541 return true;
542}
543
Chris Lattnere42eb312004-10-10 23:14:11 +0000544static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
545 bool Changed = false;
546 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
547 Instruction *I = cast<Instruction>(*UI++);
548 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
549 LI->setOperand(0, NewV);
550 Changed = true;
551 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
552 if (SI->getOperand(1) == V) {
553 SI->setOperand(1, NewV);
554 Changed = true;
555 }
556 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
557 if (I->getOperand(0) == V) {
558 // Calling through the pointer! Turn into a direct call, but be careful
559 // that the pointer is not also being passed as an argument.
560 I->setOperand(0, NewV);
561 Changed = true;
562 bool PassedAsArg = false;
563 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
564 if (I->getOperand(i) == V) {
565 PassedAsArg = true;
566 I->setOperand(i, NewV);
567 }
568
569 if (PassedAsArg) {
570 // Being passed as an argument also. Be careful to not invalidate UI!
571 UI = V->use_begin();
572 }
573 }
574 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
575 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
576 ConstantExpr::getCast(NewV, CI->getType()));
577 if (CI->use_empty()) {
578 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000579 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000580 }
581 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
582 // Should handle GEP here.
583 std::vector<Constant*> Indices;
584 Indices.reserve(GEPI->getNumOperands()-1);
585 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
586 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
587 Indices.push_back(C);
588 else
589 break;
590 if (Indices.size() == GEPI->getNumOperands()-1)
591 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
592 ConstantExpr::getGetElementPtr(NewV, Indices));
593 if (GEPI->use_empty()) {
594 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000595 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000596 }
597 }
598 }
599
600 return Changed;
601}
602
603
604/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
605/// value stored into it. If there are uses of the loaded value that would trap
606/// if the loaded value is dynamically null, then we know that they cannot be
607/// reachable with a null optimize away the load.
608static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
609 std::vector<LoadInst*> Loads;
610 bool Changed = false;
611
612 // Replace all uses of loads with uses of uses of the stored value.
613 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
614 GUI != E; ++GUI)
615 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
616 Loads.push_back(LI);
617 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
618 } else {
619 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
620 }
621
622 if (Changed) {
623 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
624 ++NumGlobUses;
625 }
626
627 // Delete all of the loads we can, keeping track of whether we nuked them all!
628 bool AllLoadsGone = true;
629 while (!Loads.empty()) {
630 LoadInst *L = Loads.back();
631 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000632 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000633 Changed = true;
634 } else {
635 AllLoadsGone = false;
636 }
637 Loads.pop_back();
638 }
639
640 // If we nuked all of the loads, then none of the stores are needed either,
641 // nor is the global.
642 if (AllLoadsGone) {
643 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
644 CleanupConstantGlobalUsers(GV, 0);
645 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000646 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000647 ++NumDeleted;
648 }
649 Changed = true;
650 }
651 return Changed;
652}
653
Chris Lattner004e2502004-10-11 05:54:41 +0000654/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
655/// instructions that are foldable.
656static void ConstantPropUsersOf(Value *V) {
657 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
658 if (Instruction *I = dyn_cast<Instruction>(*UI++))
659 if (Constant *NewC = ConstantFoldInstruction(I)) {
660 I->replaceAllUsesWith(NewC);
661
Chris Lattnerd6a44922005-02-01 01:23:31 +0000662 // Advance UI to the next non-I use to avoid invalidating it!
663 // Instructions could multiply use V.
664 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000665 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000666 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000667 }
668}
669
670/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
671/// variable, and transforms the program as if it always contained the result of
672/// the specified malloc. Because it is always the result of the specified
673/// malloc, there is no reason to actually DO the malloc. Instead, turn the
674/// malloc into a global, and any laods of GV as uses of the new global.
675static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
676 MallocInst *MI) {
677 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
678 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
679
Reid Spencere0fc4df2006-10-20 07:07:24 +0000680 if (NElements->getZExtValue() != 1) {
Chris Lattner004e2502004-10-11 05:54:41 +0000681 // If we have an array allocation, transform it to a single element
682 // allocation to make the code below simpler.
683 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencere0fc4df2006-10-20 07:07:24 +0000684 NElements->getZExtValue());
Chris Lattner004e2502004-10-11 05:54:41 +0000685 MallocInst *NewMI =
686 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
Nate Begeman848622f2005-11-05 09:21:28 +0000687 MI->getAlignment(), MI->getName(), MI);
Chris Lattner004e2502004-10-11 05:54:41 +0000688 std::vector<Value*> Indices;
689 Indices.push_back(Constant::getNullValue(Type::IntTy));
690 Indices.push_back(Indices[0]);
691 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
692 NewMI->getName()+".el0", MI);
693 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000694 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000695 MI = NewMI;
696 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000697
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000698 // Create the new global variable. The contents of the malloc'd memory is
699 // undefined, so initialize with an undef value.
700 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000701 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
702 GlobalValue::InternalLinkage, Init,
703 GV->getName()+".body");
704 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000705
Chris Lattner004e2502004-10-11 05:54:41 +0000706 // Anything that used the malloc now uses the global directly.
707 MI->replaceAllUsesWith(NewGV);
Chris Lattner004e2502004-10-11 05:54:41 +0000708
709 Constant *RepValue = NewGV;
710 if (NewGV->getType() != GV->getType()->getElementType())
711 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
712
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000713 // If there is a comparison against null, we will insert a global bool to
714 // keep track of whether the global was initialized yet or not.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000715 GlobalVariable *InitBool =
716 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
Chris Lattner6ab03f62006-09-28 23:35:22 +0000717 ConstantBool::getFalse(), GV->getName()+".init");
Chris Lattner3b181392004-12-02 06:25:58 +0000718 bool InitBoolUsed = false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000719
Chris Lattner004e2502004-10-11 05:54:41 +0000720 // Loop over all uses of GV, processing them in turn.
Chris Lattner3b181392004-12-02 06:25:58 +0000721 std::vector<StoreInst*> Stores;
Chris Lattner004e2502004-10-11 05:54:41 +0000722 while (!GV->use_empty())
723 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000724 while (!LI->use_empty()) {
Chris Lattnerd6a44922005-02-01 01:23:31 +0000725 Use &LoadUse = LI->use_begin().getUse();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000726 if (!isa<SetCondInst>(LoadUse.getUser()))
727 LoadUse = RepValue;
728 else {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000729 // Replace the setcc X, 0 with a use of the bool value.
730 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
731 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattner3b181392004-12-02 06:25:58 +0000732 InitBoolUsed = true;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000733 switch (SCI->getOpcode()) {
734 default: assert(0 && "Unknown opcode!");
735 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +0000736 LV = ConstantBool::getFalse(); // X < null -> always false
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000737 break;
738 case Instruction::SetEQ:
739 case Instruction::SetLE:
740 LV = BinaryOperator::createNot(LV, "notinit", SCI);
741 break;
742 case Instruction::SetNE:
743 case Instruction::SetGE:
744 case Instruction::SetGT:
745 break; // no change.
746 }
747 SCI->replaceAllUsesWith(LV);
748 SCI->eraseFromParent();
749 }
750 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000751 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000752 } else {
753 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner3b181392004-12-02 06:25:58 +0000754 // The global is initialized when the store to it occurs.
Chris Lattner6ab03f62006-09-28 23:35:22 +0000755 new StoreInst(ConstantBool::getTrue(), InitBool, SI);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000756 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000757 }
758
Chris Lattner3b181392004-12-02 06:25:58 +0000759 // If the initialization boolean was used, insert it, otherwise delete it.
760 if (!InitBoolUsed) {
761 while (!InitBool->use_empty()) // Delete initializations
762 cast<Instruction>(InitBool->use_back())->eraseFromParent();
763 delete InitBool;
764 } else
765 GV->getParent()->getGlobalList().insert(GV, InitBool);
766
767
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000768 // Now the GV is dead, nuke it and the malloc.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000769 GV->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000770 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000771
772 // To further other optimizations, loop over all users of NewGV and try to
773 // constant prop them. This will promote GEP instructions with constant
774 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
775 ConstantPropUsersOf(NewGV);
776 if (RepValue != NewGV)
777 ConstantPropUsersOf(RepValue);
778
779 return NewGV;
780}
Chris Lattnere42eb312004-10-10 23:14:11 +0000781
Chris Lattnerc0677c02004-12-02 07:11:07 +0000782/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
783/// to make sure that there are no complex uses of V. We permit simple things
784/// like dereferencing the pointer, but not storing through the address, unless
785/// it is to the specified global.
786static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
787 GlobalVariable *GV) {
788 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
789 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
790 // Fine, ignore.
791 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
792 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
793 return false; // Storing the pointer itself... bad.
794 // Otherwise, storing through it, or storing into GV... fine.
795 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
796 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
797 return false;
798 } else {
799 return false;
800 }
801 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000802}
803
Chris Lattner24d3d422006-09-30 23:32:09 +0000804/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
805/// somewhere. Transform all uses of the allocation into loads from the
806/// global and uses of the resultant pointer. Further, delete the store into
807/// GV. This assumes that these value pass the
808/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
809static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
810 GlobalVariable *GV) {
811 while (!Alloc->use_empty()) {
812 Instruction *U = Alloc->use_back();
813 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
814 // If this is the store of the allocation into the global, remove it.
815 if (SI->getOperand(1) == GV) {
816 SI->eraseFromParent();
817 continue;
818 }
819 }
820
821 // Insert a load from the global, and use it instead of the malloc.
822 Value *NL = new LoadInst(GV, GV->getName()+".val", U);
823 U->replaceUsesOfWith(Alloc, NL);
824 }
825}
826
827/// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
828/// GV are simple enough to perform HeapSRA, return true.
829static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
830 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
831 ++UI)
832 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
833 // We permit two users of the load: setcc comparing against the null
834 // pointer, and a getelementptr of a specific form.
835 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
836 ++UI) {
837 // Comparison against null is ok.
838 if (SetCondInst *SCI = dyn_cast<SetCondInst>(*UI)) {
839 if (!isa<ConstantPointerNull>(SCI->getOperand(1)))
840 return false;
841 continue;
842 }
843
844 // getelementptr is also ok, but only a simple form.
845 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
846 if (!GEPI) return false;
847
848 // Must index into the array and into the struct.
849 if (GEPI->getNumOperands() < 3)
850 return false;
851
852 // Otherwise the GEP is ok.
853 continue;
854 }
855 }
856 return true;
857}
858
859/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
860/// is a value loaded from the global. Eliminate all uses of Ptr, making them
861/// use FieldGlobals instead. All uses of loaded values satisfy
862/// GlobalLoadUsesSimpleEnoughForHeapSRA.
863static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr,
864 const std::vector<GlobalVariable*> &FieldGlobals) {
865 std::vector<Value *> InsertedLoadsForPtr;
866 //InsertedLoadsForPtr.resize(FieldGlobals.size());
867 while (!Ptr->use_empty()) {
868 Instruction *User = Ptr->use_back();
869
870 // If this is a comparison against null, handle it.
871 if (SetCondInst *SCI = dyn_cast<SetCondInst>(User)) {
872 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
873 // If we have a setcc of the loaded pointer, we can use a setcc of any
874 // field.
875 Value *NPtr;
876 if (InsertedLoadsForPtr.empty()) {
877 NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
878 InsertedLoadsForPtr.push_back(Ptr);
879 } else {
880 NPtr = InsertedLoadsForPtr.back();
881 }
882
883 Value *New = new SetCondInst(SCI->getOpcode(), NPtr,
884 Constant::getNullValue(NPtr->getType()),
885 SCI->getName(), SCI);
886 SCI->replaceAllUsesWith(New);
887 SCI->eraseFromParent();
888 continue;
889 }
890
891 // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
892 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000893 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
894 && GEPI->getOperand(2)->getType()->isUnsigned()
Chris Lattner24d3d422006-09-30 23:32:09 +0000895 && "Unexpected GEPI!");
896
897 // Load the pointer for this field.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000898 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner24d3d422006-09-30 23:32:09 +0000899 if (InsertedLoadsForPtr.size() <= FieldNo)
900 InsertedLoadsForPtr.resize(FieldNo+1);
901 if (InsertedLoadsForPtr[FieldNo] == 0)
902 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
903 Ptr->getName()+".f" +
904 utostr(FieldNo), Ptr);
905 Value *NewPtr = InsertedLoadsForPtr[FieldNo];
906
907 // Create the new GEP idx vector.
908 std::vector<Value*> GEPIdx;
909 GEPIdx.push_back(GEPI->getOperand(1));
910 GEPIdx.insert(GEPIdx.end(), GEPI->op_begin()+3, GEPI->op_end());
911
912 Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx, GEPI->getName(), GEPI);
913 GEPI->replaceAllUsesWith(NGEPI);
914 GEPI->eraseFromParent();
915 }
916}
917
918/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
919/// it up into multiple allocations of arrays of the fields.
920static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Chris Lattner4797c892006-09-30 23:32:50 +0000921 DEBUG(std::cerr << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI);
Chris Lattner24d3d422006-09-30 23:32:09 +0000922 const StructType *STy = cast<StructType>(MI->getAllocatedType());
923
924 // There is guaranteed to be at least one use of the malloc (storing
925 // it into GV). If there are other uses, change them to be uses of
926 // the global to simplify later code. This also deletes the store
927 // into GV.
928 ReplaceUsesOfMallocWithGlobal(MI, GV);
929
930 // Okay, at this point, there are no users of the malloc. Insert N
931 // new mallocs at the same place as MI, and N globals.
932 std::vector<GlobalVariable*> FieldGlobals;
933 std::vector<MallocInst*> FieldMallocs;
934
935 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
936 const Type *FieldTy = STy->getElementType(FieldNo);
937 const Type *PFieldTy = PointerType::get(FieldTy);
938
939 GlobalVariable *NGV =
940 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
941 Constant::getNullValue(PFieldTy),
942 GV->getName() + ".f" + utostr(FieldNo), GV);
943 FieldGlobals.push_back(NGV);
944
945 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
946 MI->getName() + ".f" + utostr(FieldNo),MI);
947 FieldMallocs.push_back(NMI);
948 new StoreInst(NMI, NGV, MI);
949 }
950
951 // The tricky aspect of this transformation is handling the case when malloc
952 // fails. In the original code, malloc failing would set the result pointer
953 // of malloc to null. In this case, some mallocs could succeed and others
954 // could fail. As such, we emit code that looks like this:
955 // F0 = malloc(field0)
956 // F1 = malloc(field1)
957 // F2 = malloc(field2)
958 // if (F0 == 0 || F1 == 0 || F2 == 0) {
959 // if (F0) { free(F0); F0 = 0; }
960 // if (F1) { free(F1); F1 = 0; }
961 // if (F2) { free(F2); F2 = 0; }
962 // }
963 Value *RunningOr = 0;
964 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
965 Value *Cond = new SetCondInst(Instruction::SetEQ, FieldMallocs[i],
966 Constant::getNullValue(FieldMallocs[i]->getType()),
967 "isnull", MI);
968 if (!RunningOr)
969 RunningOr = Cond; // First seteq
970 else
971 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
972 }
973
974 // Split the basic block at the old malloc.
975 BasicBlock *OrigBB = MI->getParent();
976 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
977
978 // Create the block to check the first condition. Put all these blocks at the
979 // end of the function as they are unlikely to be executed.
980 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
981 OrigBB->getParent());
982
983 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
984 // branch on RunningOr.
985 OrigBB->getTerminator()->eraseFromParent();
986 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
987
988 // Within the NullPtrBlock, we need to emit a comparison and branch for each
989 // pointer, because some may be null while others are not.
990 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
991 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
992 Value *Cmp = new SetCondInst(Instruction::SetNE, GVVal,
993 Constant::getNullValue(GVVal->getType()),
994 "tmp", NullPtrBlock);
995 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
996 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
997 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
998
999 // Fill in FreeBlock.
1000 new FreeInst(GVVal, FreeBlock);
1001 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1002 FreeBlock);
1003 new BranchInst(NextBlock, FreeBlock);
1004
1005 NullPtrBlock = NextBlock;
1006 }
1007
1008 new BranchInst(ContBB, NullPtrBlock);
1009
1010
1011 // MI is no longer needed, remove it.
1012 MI->eraseFromParent();
1013
1014
1015 // Okay, the malloc site is completely handled. All of the uses of GV are now
1016 // loads, and all uses of those loads are simple. Rewrite them to use loads
1017 // of the per-field globals instead.
1018 while (!GV->use_empty()) {
1019 LoadInst *LI = cast<LoadInst>(GV->use_back());
1020 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1021 LI->eraseFromParent();
1022 }
1023
1024 // The old global is now dead, remove it.
1025 GV->eraseFromParent();
1026
1027 ++NumHeapSRA;
1028 return FieldGlobals[0];
1029}
1030
1031
Chris Lattner09a52722004-10-09 21:48:45 +00001032// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1033// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001034static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001035 Module::global_iterator &GVI,
1036 TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +00001037 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1038 StoredOnceVal = CI->getOperand(0);
1039 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +00001040 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +00001041 bool IsJustACast = true;
1042 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1043 if (!isa<Constant>(GEPI->getOperand(i)) ||
1044 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1045 IsJustACast = false;
1046 break;
1047 }
1048 if (IsJustACast)
1049 StoredOnceVal = GEPI->getOperand(0);
1050 }
1051
Chris Lattnere42eb312004-10-10 23:14:11 +00001052 // If we are dealing with a pointer global that is initialized to null and
1053 // only has one (non-null) value stored into it, then we can optimize any
1054 // users of the loaded value (often calls and loads) that would trap if the
1055 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +00001056 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1057 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001058 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1059 if (GV->getInitializer()->getType() != SOVC->getType())
1060 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001061
Chris Lattnere42eb312004-10-10 23:14:11 +00001062 // Optimize away any trapping uses of the loaded value.
1063 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001064 return true;
Chris Lattner004e2502004-10-11 05:54:41 +00001065 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattner80a01ef2006-09-30 19:40:30 +00001066 // If this is a malloc of an abstract type, don't touch it.
1067 if (!MI->getAllocatedType()->isSized())
1068 return false;
1069
Chris Lattner24d3d422006-09-30 23:32:09 +00001070 // We can't optimize this global unless all uses of it are *known* to be
1071 // of the malloc value, not of the null initializer value (consider a use
1072 // that compares the global's value against zero to see if the malloc has
1073 // been reached). To do this, we check to see if all uses of the global
1074 // would trap if the global were null: this proves that they must all
1075 // happen after the malloc.
1076 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1077 return false;
1078
1079 // We can't optimize this if the malloc itself is used in a complex way,
1080 // for example, being stored into multiple globals. This allows the
1081 // malloc to be stored into the specified global, loaded setcc'd, and
1082 // GEP'd. These are all things we could transform to using the global
1083 // for.
1084 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1085 return false;
1086
1087
Chris Lattner004e2502004-10-11 05:54:41 +00001088 // If we have a global that is only initialized with a fixed size malloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001089 // transform the program to use global memory instead of malloc'd memory.
1090 // This eliminates dynamic allocation, avoids an indirection accessing the
1091 // data, and exposes the resultant global to further GlobalOpt.
Chris Lattner80a01ef2006-09-30 19:40:30 +00001092 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
Chris Lattner24d3d422006-09-30 23:32:09 +00001093 // Restrict this transformation to only working on small allocations
1094 // (2048 bytes currently), as we don't want to introduce a 16M global or
1095 // something.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001096 if (NElements->getZExtValue()*
Chris Lattner24d3d422006-09-30 23:32:09 +00001097 TD.getTypeSize(MI->getAllocatedType()) < 2048) {
Chris Lattner004e2502004-10-11 05:54:41 +00001098 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1099 return true;
1100 }
Chris Lattner80a01ef2006-09-30 19:40:30 +00001101 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001102
1103 // If the allocation is an array of structures, consider transforming this
1104 // into multiple malloc'd arrays, one for each field. This is basically
1105 // SRoA for malloc'd memory.
1106 if (const StructType *AllocTy =
1107 dyn_cast<StructType>(MI->getAllocatedType())) {
1108 // This the structure has an unreasonable number of fields, leave it
1109 // alone.
1110 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1111 GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1112 GVI = PerformHeapAllocSRoA(GV, MI);
1113 return true;
1114 }
1115 }
Chris Lattnere42eb312004-10-10 23:14:11 +00001116 }
Chris Lattner09a52722004-10-09 21:48:45 +00001117 }
Chris Lattner004e2502004-10-11 05:54:41 +00001118
Chris Lattner09a52722004-10-09 21:48:45 +00001119 return false;
1120}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001121
Chris Lattner40e4cec2004-12-12 05:53:50 +00001122/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
Misha Brukmanb1c93172005-04-21 23:48:37 +00001123/// values ever stored into GV are its initializer and OtherVal.
Chris Lattner40e4cec2004-12-12 05:53:50 +00001124static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1125 // Create the new global, initializing it to false.
1126 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
Chris Lattner6ab03f62006-09-28 23:35:22 +00001127 GlobalValue::InternalLinkage, ConstantBool::getFalse(),
1128 GV->getName()+".b");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001129 GV->getParent()->getGlobalList().insert(GV, NewGV);
1130
1131 Constant *InitVal = GV->getInitializer();
1132 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
1133
1134 // If initialized to zero and storing one into the global, we can use a cast
1135 // instead of a select to synthesize the desired value.
1136 bool IsOneZero = false;
1137 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1138 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
1139
1140 while (!GV->use_empty()) {
1141 Instruction *UI = cast<Instruction>(GV->use_back());
1142 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1143 // Change the store into a boolean store.
1144 bool StoringOther = SI->getOperand(0) == OtherVal;
1145 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +00001146 Value *StoreVal;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001147 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner745196a2004-12-12 19:34:41 +00001148 StoreVal = ConstantBool::get(StoringOther);
1149 else {
1150 // Otherwise, we are storing a previously loaded copy. To do this,
1151 // change the copy from copying the original value to just copying the
1152 // bool.
1153 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1154
1155 // If we're already replaced the input, StoredVal will be a cast or
1156 // select instruction. If not, it will be a load of the original
1157 // global.
1158 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1159 assert(LI->getOperand(0) == GV && "Not a copy!");
1160 // Insert a new load, to preserve the saved value.
1161 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1162 } else {
1163 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1164 "This is not a form that we understand!");
1165 StoreVal = StoredVal->getOperand(0);
1166 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1167 }
1168 }
1169 new StoreInst(StoreVal, NewGV, SI);
1170 } else if (!UI->use_empty()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001171 // Change the load into a load of bool then a select.
1172 LoadInst *LI = cast<LoadInst>(UI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001173
Chris Lattner40e4cec2004-12-12 05:53:50 +00001174 std::string Name = LI->getName(); LI->setName("");
1175 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
1176 Value *NSI;
1177 if (IsOneZero)
1178 NSI = new CastInst(NLI, LI->getType(), Name, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001179 else
Chris Lattner40e4cec2004-12-12 05:53:50 +00001180 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
1181 LI->replaceAllUsesWith(NSI);
1182 }
1183 UI->eraseFromParent();
1184 }
1185
1186 GV->eraseFromParent();
1187}
1188
1189
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001190/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1191/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +00001192bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattner531f9e92005-03-15 04:54:21 +00001193 Module::global_iterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001194 std::set<PHINode*> PHIUsers;
1195 GlobalStatus GS;
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001196 GV->removeDeadConstantUsers();
1197
1198 if (GV->use_empty()) {
1199 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001200 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001201 ++NumDeleted;
1202 return true;
1203 }
1204
1205 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattner80a01ef2006-09-30 19:40:30 +00001206#if 0
1207 std::cerr << "Global: " << *GV;
1208 std::cerr << " isLoaded = " << GS.isLoaded << "\n";
1209 std::cerr << " StoredType = ";
1210 switch (GS.StoredType) {
1211 case GlobalStatus::NotStored: std::cerr << "NEVER STORED\n"; break;
1212 case GlobalStatus::isInitializerStored: std::cerr << "INIT STORED\n"; break;
1213 case GlobalStatus::isStoredOnce: std::cerr << "STORED ONCE\n"; break;
1214 case GlobalStatus::isStored: std::cerr << "stored\n"; break;
1215 }
1216 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1217 std::cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1218 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1219 std::cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1220 << "\n";
1221 std::cerr << " HasMultipleAccessingFunctions = "
1222 << GS.HasMultipleAccessingFunctions << "\n";
1223 std::cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1224 std::cerr << " isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1225 std::cerr << "\n";
1226#endif
1227
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001228 // If this is a first class global and has only one accessing function
1229 // and this function is main (which we know is not recursive we can make
1230 // this global a local variable) we replace the global with a local alloca
1231 // in this function.
1232 //
1233 // NOTE: It doesn't make sense to promote non first class types since we
1234 // are just replacing static memory to stack memory.
1235 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner50bdfcb2005-06-15 21:11:48 +00001236 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001237 GV->getType()->getElementType()->isFirstClassType() &&
1238 GS.AccessingFunction->getName() == "main" &&
1239 GS.AccessingFunction->hasExternalLinkage()) {
1240 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
1241 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1242 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman848622f2005-11-05 09:21:28 +00001243 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001244 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1245 if (!isa<UndefValue>(GV->getInitializer()))
1246 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001247
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001248 GV->replaceAllUsesWith(Alloca);
1249 GV->eraseFromParent();
1250 ++NumLocalized;
1251 return true;
1252 }
Chris Lattner80a01ef2006-09-30 19:40:30 +00001253
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001254 // If the global is never loaded (but may be stored to), it is dead.
1255 // Delete it now.
1256 if (!GS.isLoaded) {
1257 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +00001258
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001259 // Delete any stores we can find to the global. We may not be able to
1260 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +00001261 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +00001262
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001263 // If the global is dead now, delete it.
1264 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001265 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001266 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +00001267 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001268 }
Chris Lattnerf369b382004-10-09 03:32:52 +00001269 return Changed;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001270
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001271 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1272 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
1273 GV->setConstant(true);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001274
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001275 // Clean up any obviously simplifiable users now.
1276 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001277
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001278 // If the global is dead now, just nuke it.
1279 if (GV->use_empty()) {
1280 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
1281 "all users and delete global!\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001282 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001283 ++NumDeleted;
1284 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001285
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001286 ++NumMarked;
1287 return true;
1288 } else if (!GS.isNotSuitableForSRA &&
1289 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001290 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1291 GVI = FirstNewGV; // Don't skip the newly produced globals!
1292 return true;
1293 }
Chris Lattner09a52722004-10-09 21:48:45 +00001294 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001295 // If the initial value for the global was an undef value, and if only
1296 // one other value was stored into it, we can just change the
1297 // initializer to be an undef value, then delete all stores to the
1298 // global. This allows us to mark it constant.
1299 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1300 if (isa<UndefValue>(GV->getInitializer())) {
1301 // Change the initial value here.
1302 GV->setInitializer(SOVConstant);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001303
Chris Lattner40e4cec2004-12-12 05:53:50 +00001304 // Clean up any obviously simplifiable users now.
1305 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001306
Chris Lattner40e4cec2004-12-12 05:53:50 +00001307 if (GV->use_empty()) {
1308 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
1309 "simplify all users and delete global!\n");
1310 GV->eraseFromParent();
1311 ++NumDeleted;
1312 } else {
1313 GVI = GV;
1314 }
1315 ++NumSubstitute;
1316 return true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001317 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001318
Chris Lattner09a52722004-10-09 21:48:45 +00001319 // Try to optimize globals based on the knowledge that only one value
1320 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001321 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1322 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +00001323 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001324
1325 // Otherwise, if the global was not a boolean, we can shrink it to be a
1326 // boolean.
1327 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner1cbd5be2004-12-12 06:03:06 +00001328 if (GV->getType()->getElementType() != Type::BoolTy &&
Chris Lattner5a0bd612006-11-01 18:03:33 +00001329 !GV->getType()->getElementType()->isFloatingPoint() &&
1330 !GS.HasPHIUser) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001331 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
1332 ShrinkGlobalToBoolean(GV, SOVConstant);
1333 ++NumShrunkToBool;
1334 return true;
1335 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001336 }
1337 }
1338 return false;
1339}
1340
Chris Lattnera4c80222005-05-08 22:18:06 +00001341/// OnlyCalledDirectly - Return true if the specified function is only called
1342/// directly. In other words, its address is never taken.
1343static bool OnlyCalledDirectly(Function *F) {
1344 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1345 Instruction *User = dyn_cast<Instruction>(*UI);
1346 if (!User) return false;
1347 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1348
1349 // See if the function address is passed as an argument.
1350 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1351 if (User->getOperand(i) == F) return false;
1352 }
1353 return true;
1354}
1355
1356/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1357/// function, changing them to FastCC.
1358static void ChangeCalleesToFastCall(Function *F) {
1359 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1360 Instruction *User = cast<Instruction>(*UI);
1361 if (CallInst *CI = dyn_cast<CallInst>(User))
1362 CI->setCallingConv(CallingConv::Fast);
1363 else
1364 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1365 }
1366}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001367
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001368bool GlobalOpt::OptimizeFunctions(Module &M) {
1369 bool Changed = false;
1370 // Optimize functions.
1371 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1372 Function *F = FI++;
1373 F->removeDeadConstantUsers();
1374 if (F->use_empty() && (F->hasInternalLinkage() ||
1375 F->hasLinkOnceLinkage())) {
1376 M.getFunctionList().erase(F);
1377 Changed = true;
1378 ++NumFnDeleted;
1379 } else if (F->hasInternalLinkage() &&
1380 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1381 OnlyCalledDirectly(F)) {
1382 // If this function has C calling conventions, is not a varargs
1383 // function, and is only called directly, promote it to use the Fast
1384 // calling convention.
1385 F->setCallingConv(CallingConv::Fast);
1386 ChangeCalleesToFastCall(F);
1387 ++NumFastCallFns;
1388 Changed = true;
1389 }
1390 }
1391 return Changed;
1392}
1393
1394bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1395 bool Changed = false;
1396 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1397 GVI != E; ) {
1398 GlobalVariable *GV = GVI++;
1399 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1400 GV->hasInitializer())
1401 Changed |= ProcessInternalGlobal(GV, GVI);
1402 }
1403 return Changed;
1404}
1405
1406/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1407/// initializers have an init priority of 65535.
1408GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenoscb67b652005-10-25 11:18:06 +00001409 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1410 I != E; ++I)
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001411 if (I->getName() == "llvm.global_ctors") {
1412 // Found it, verify it's an array of { int, void()* }.
1413 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1414 if (!ATy) return 0;
1415 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1416 if (!STy || STy->getNumElements() != 2 ||
1417 STy->getElementType(0) != Type::IntTy) return 0;
1418 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1419 if (!PFTy) return 0;
1420 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1421 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1422 FTy->getNumParams() != 0)
1423 return 0;
1424
1425 // Verify that the initializer is simple enough for us to handle.
1426 if (!I->hasInitializer()) return 0;
1427 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1428 if (!CA) return 0;
1429 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1430 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
Chris Lattner838bdc12005-09-26 02:19:27 +00001431 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1432 continue;
1433
1434 // Must have a function or null ptr.
1435 if (!isa<Function>(CS->getOperand(1)))
1436 return 0;
1437
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001438 // Init priority must be standard.
1439 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencere0fc4df2006-10-20 07:07:24 +00001440 if (!CI || CI->getZExtValue() != 65535)
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001441 return 0;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001442 } else {
1443 return 0;
1444 }
1445
1446 return I;
1447 }
1448 return 0;
1449}
1450
Chris Lattner696beef2005-09-26 02:31:18 +00001451/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1452/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001453static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1454 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1455 std::vector<Function*> Result;
1456 Result.reserve(CA->getNumOperands());
1457 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1458 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1459 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1460 }
1461 return Result;
1462}
1463
Chris Lattner696beef2005-09-26 02:31:18 +00001464/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1465/// specified array, returning the new global to use.
1466static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1467 const std::vector<Function*> &Ctors) {
1468 // If we made a change, reassemble the initializer list.
1469 std::vector<Constant*> CSVals;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001470 CSVals.push_back(ConstantInt::get(Type::IntTy, 65535));
Chris Lattner696beef2005-09-26 02:31:18 +00001471 CSVals.push_back(0);
1472
1473 // Create the new init list.
1474 std::vector<Constant*> CAList;
1475 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001476 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00001477 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00001478 } else {
Chris Lattner696beef2005-09-26 02:31:18 +00001479 const Type *FTy = FunctionType::get(Type::VoidTy,
1480 std::vector<const Type*>(), false);
1481 const PointerType *PFTy = PointerType::get(FTy);
1482 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001483 CSVals[0] = ConstantInt::get(Type::IntTy, 2147483647);
Chris Lattner696beef2005-09-26 02:31:18 +00001484 }
1485 CAList.push_back(ConstantStruct::get(CSVals));
1486 }
1487
1488 // Create the array initializer.
1489 const Type *StructTy =
1490 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1491 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1492 CAList);
1493
1494 // If we didn't change the number of elements, don't create a new GV.
1495 if (CA->getType() == GCL->getInitializer()->getType()) {
1496 GCL->setInitializer(CA);
1497 return GCL;
1498 }
1499
1500 // Create the new global and insert it next to the existing list.
1501 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1502 GCL->getLinkage(), CA,
1503 GCL->getName());
1504 GCL->setName("");
1505 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1506
1507 // Nuke the old list, replacing any uses with the new one.
1508 if (!GCL->use_empty()) {
1509 Constant *V = NGV;
1510 if (V->getType() != GCL->getType())
1511 V = ConstantExpr::getCast(V, GCL->getType());
1512 GCL->replaceAllUsesWith(V);
1513 }
1514 GCL->eraseFromParent();
1515
1516 if (Ctors.size())
1517 return NGV;
1518 else
1519 return 0;
1520}
Chris Lattner99e23fa2005-09-26 04:44:35 +00001521
1522
1523static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1524 Value *V) {
1525 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1526 Constant *R = ComputedValues[V];
1527 assert(R && "Reference to an uncomputed value!");
1528 return R;
1529}
1530
1531/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1532/// enough for us to understand. In particular, if it is a cast of something,
1533/// we punt. We basically just support direct accesses to globals and GEP's of
1534/// globals. This should be kept up to date with CommitValueTo.
1535static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner29b27802005-09-27 04:50:03 +00001536 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1537 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001538 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001539 return !GV->isExternal(); // reject external globals.
Chris Lattner29b27802005-09-27 04:50:03 +00001540 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001541 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1542 // Handle a constantexpr gep.
1543 if (CE->getOpcode() == Instruction::GetElementPtr &&
1544 isa<GlobalVariable>(CE->getOperand(0))) {
1545 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattner29b27802005-09-27 04:50:03 +00001546 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001547 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner46af55e2005-09-26 06:52:44 +00001548 return GV->hasInitializer() &&
1549 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1550 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001551 return false;
1552}
1553
Chris Lattner46af55e2005-09-26 06:52:44 +00001554/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1555/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1556/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1557static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1558 ConstantExpr *Addr, unsigned OpNo) {
1559 // Base case of the recursion.
1560 if (OpNo == Addr->getNumOperands()) {
1561 assert(Val->getType() == Init->getType() && "Type mismatch!");
1562 return Val;
1563 }
1564
1565 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1566 std::vector<Constant*> Elts;
1567
1568 // Break up the constant into its elements.
1569 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1570 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1571 Elts.push_back(CS->getOperand(i));
1572 } else if (isa<ConstantAggregateZero>(Init)) {
1573 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1574 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1575 } else if (isa<UndefValue>(Init)) {
1576 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1577 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1578 } else {
1579 assert(0 && "This code is out of sync with "
1580 " ConstantFoldLoadThroughGEPConstantExpr");
1581 }
1582
1583 // Replace the element that we are supposed to.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001584 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1585 unsigned Idx = CU->getZExtValue();
1586 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner46af55e2005-09-26 06:52:44 +00001587 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1588
1589 // Return the modified struct.
1590 return ConstantStruct::get(Elts);
1591 } else {
1592 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1593 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1594
1595 // Break up the array into elements.
1596 std::vector<Constant*> Elts;
1597 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1598 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1599 Elts.push_back(CA->getOperand(i));
1600 } else if (isa<ConstantAggregateZero>(Init)) {
1601 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1602 Elts.assign(ATy->getNumElements(), Elt);
1603 } else if (isa<UndefValue>(Init)) {
1604 Constant *Elt = UndefValue::get(ATy->getElementType());
1605 Elts.assign(ATy->getNumElements(), Elt);
1606 } else {
1607 assert(0 && "This code is out of sync with "
1608 " ConstantFoldLoadThroughGEPConstantExpr");
1609 }
1610
Reid Spencere0fc4df2006-10-20 07:07:24 +00001611 assert(CI->getZExtValue() < ATy->getNumElements());
1612 Elts[CI->getZExtValue()] =
1613 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner46af55e2005-09-26 06:52:44 +00001614 return ConstantArray::get(ATy, Elts);
1615 }
1616}
1617
Chris Lattner99e23fa2005-09-26 04:44:35 +00001618/// CommitValueTo - We have decided that Addr (which satisfies the predicate
1619/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1620static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00001621 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1622 assert(GV->hasInitializer());
1623 GV->setInitializer(Val);
1624 return;
1625 }
1626
1627 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1628 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1629
1630 Constant *Init = GV->getInitializer();
1631 Init = EvaluateStoreInto(Init, Val, CE, 2);
1632 GV->setInitializer(Init);
Chris Lattner99e23fa2005-09-26 04:44:35 +00001633}
1634
Chris Lattnerb0096632005-09-26 05:16:34 +00001635/// ComputeLoadResult - Return the value that would be computed by a load from
1636/// P after the stores reflected by 'memory' have been performed. If we can't
1637/// decide, return null.
Chris Lattner4b05c322005-09-26 05:15:37 +00001638static Constant *ComputeLoadResult(Constant *P,
1639 const std::map<Constant*, Constant*> &Memory) {
1640 // If this memory location has been recently stored, use the stored value: it
1641 // is the most up-to-date.
1642 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1643 if (I != Memory.end()) return I->second;
1644
1645 // Access it.
1646 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1647 if (GV->hasInitializer())
1648 return GV->getInitializer();
1649 return 0;
Chris Lattner4b05c322005-09-26 05:15:37 +00001650 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001651
1652 // Handle a constantexpr getelementptr.
1653 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1654 if (CE->getOpcode() == Instruction::GetElementPtr &&
1655 isa<GlobalVariable>(CE->getOperand(0))) {
1656 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1657 if (GV->hasInitializer())
1658 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1659 }
1660
1661 return 0; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00001662}
1663
Chris Lattnerda1889b2005-09-27 04:27:01 +00001664/// EvaluateFunction - Evaluate a call to function F, returning true if
1665/// successful, false if we can't evaluate it. ActualArgs contains the formal
1666/// arguments for the function.
Chris Lattner65a3a092005-09-27 04:45:34 +00001667static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattnerda1889b2005-09-27 04:27:01 +00001668 const std::vector<Constant*> &ActualArgs,
1669 std::vector<Function*> &CallStack,
1670 std::map<Constant*, Constant*> &MutatedMemory,
1671 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001672 // Check to see if this function is already executing (recursion). If so,
1673 // bail out. TODO: we might want to accept limited recursion.
1674 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1675 return false;
1676
1677 CallStack.push_back(F);
1678
Chris Lattner99e23fa2005-09-26 04:44:35 +00001679 /// Values - As we compute SSA register values, we store their contents here.
1680 std::map<Value*, Constant*> Values;
Chris Lattner65a3a092005-09-27 04:45:34 +00001681
1682 // Initialize arguments to the incoming values specified.
1683 unsigned ArgNo = 0;
1684 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1685 ++AI, ++ArgNo)
1686 Values[AI] = ActualArgs[ArgNo];
Chris Lattnerda1889b2005-09-27 04:27:01 +00001687
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001688 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1689 /// we can only evaluate any one basic block at most once. This set keeps
1690 /// track of what we have executed so we can detect recursive cases etc.
1691 std::set<BasicBlock*> ExecutedBlocks;
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001692
Chris Lattner99e23fa2005-09-26 04:44:35 +00001693 // CurInst - The current instruction we're evaluating.
1694 BasicBlock::iterator CurInst = F->begin()->begin();
1695
1696 // This is the main evaluation loop.
1697 while (1) {
1698 Constant *InstResult = 0;
1699
1700 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001701 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001702 Constant *Ptr = getVal(Values, SI->getOperand(1));
1703 if (!isSimpleEnoughPointerToCommit(Ptr))
1704 // If this is too complex for us to commit, reject it.
Chris Lattner65a3a092005-09-27 04:45:34 +00001705 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001706 Constant *Val = getVal(Values, SI->getOperand(0));
1707 MutatedMemory[Ptr] = Val;
1708 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1709 InstResult = ConstantExpr::get(BO->getOpcode(),
1710 getVal(Values, BO->getOperand(0)),
1711 getVal(Values, BO->getOperand(1)));
1712 } else if (ShiftInst *SI = dyn_cast<ShiftInst>(CurInst)) {
1713 InstResult = ConstantExpr::get(SI->getOpcode(),
1714 getVal(Values, SI->getOperand(0)),
1715 getVal(Values, SI->getOperand(1)));
1716 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1717 InstResult = ConstantExpr::getCast(getVal(Values, CI->getOperand(0)),
1718 CI->getType());
1719 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1720 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1721 getVal(Values, SI->getOperand(1)),
1722 getVal(Values, SI->getOperand(2)));
Chris Lattner4b05c322005-09-26 05:15:37 +00001723 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1724 Constant *P = getVal(Values, GEP->getOperand(0));
1725 std::vector<Constant*> GEPOps;
1726 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1727 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1728 InstResult = ConstantExpr::getGetElementPtr(P, GEPOps);
1729 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001730 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner4b05c322005-09-26 05:15:37 +00001731 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1732 MutatedMemory);
Chris Lattner65a3a092005-09-27 04:45:34 +00001733 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001734 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001735 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001736 const Type *Ty = AI->getType()->getElementType();
1737 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1738 GlobalValue::InternalLinkage,
1739 UndefValue::get(Ty),
1740 AI->getName()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001741 InstResult = AllocaTmps.back();
1742 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00001743 // Cannot handle inline asm.
1744 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1745
Chris Lattner65a3a092005-09-27 04:45:34 +00001746 // Resolve function pointers.
1747 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1748 if (!Callee) return false; // Cannot resolve.
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001749
Chris Lattner65a3a092005-09-27 04:45:34 +00001750 std::vector<Constant*> Formals;
1751 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1752 Formals.push_back(getVal(Values, CI->getOperand(i)));
Chris Lattner65a3a092005-09-27 04:45:34 +00001753
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001754 if (Callee->isExternal()) {
1755 // If this is a function we can constant fold, do it.
1756 if (Constant *C = ConstantFoldCall(Callee, Formals)) {
1757 InstResult = C;
1758 } else {
1759 return false;
1760 }
1761 } else {
1762 if (Callee->getFunctionType()->isVarArg())
1763 return false;
1764
1765 Constant *RetVal;
1766
1767 // Execute the call, if successful, use the return value.
1768 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1769 MutatedMemory, AllocaTmps))
1770 return false;
1771 InstResult = RetVal;
1772 }
Reid Spencerde46e482006-11-02 20:25:50 +00001773 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001774 BasicBlock *NewBB = 0;
1775 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1776 if (BI->isUnconditional()) {
1777 NewBB = BI->getSuccessor(0);
1778 } else {
1779 ConstantBool *Cond =
1780 dyn_cast<ConstantBool>(getVal(Values, BI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001781 if (!Cond) return false; // Cannot determine.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001782 NewBB = BI->getSuccessor(!Cond->getValue());
1783 }
1784 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1785 ConstantInt *Val =
1786 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001787 if (!Val) return false; // Cannot determine.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001788 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1789 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001790 if (RI->getNumOperands())
1791 RetVal = getVal(Values, RI->getOperand(0));
1792
1793 CallStack.pop_back(); // return from fn.
Chris Lattnerda1889b2005-09-27 04:27:01 +00001794 return true; // We succeeded at evaluating this ctor!
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001795 } else {
Chris Lattner65a3a092005-09-27 04:45:34 +00001796 // invoke, unwind, unreachable.
1797 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001798 }
1799
1800 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattner65a3a092005-09-27 04:45:34 +00001801 // executed the new block before. If so, we have a looping function,
1802 // which we cannot evaluate in reasonable time.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001803 if (!ExecutedBlocks.insert(NewBB).second)
Chris Lattner65a3a092005-09-27 04:45:34 +00001804 return false; // looped!
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001805
1806 // Okay, we have never been in this block before. Check to see if there
1807 // are any PHI nodes. If so, evaluate them with information about where
1808 // we came from.
1809 BasicBlock *OldBB = CurInst->getParent();
1810 CurInst = NewBB->begin();
1811 PHINode *PN;
1812 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1813 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1814
1815 // Do NOT increment CurInst. We know that the terminator had no value.
1816 continue;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001817 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001818 // Did not know how to evaluate this!
Chris Lattner65a3a092005-09-27 04:45:34 +00001819 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001820 }
1821
1822 if (!CurInst->use_empty())
1823 Values[CurInst] = InstResult;
1824
1825 // Advance program counter.
1826 ++CurInst;
1827 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00001828}
1829
1830/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1831/// we can. Return true if we can, false otherwise.
1832static bool EvaluateStaticConstructor(Function *F) {
1833 /// MutatedMemory - For each store we execute, we update this map. Loads
1834 /// check this to get the most up-to-date value. If evaluation is successful,
1835 /// this state is committed to the process.
1836 std::map<Constant*, Constant*> MutatedMemory;
1837
1838 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1839 /// to represent its body. This vector is needed so we can delete the
1840 /// temporary globals when we are done.
1841 std::vector<GlobalVariable*> AllocaTmps;
1842
1843 /// CallStack - This is used to detect recursion. In pathological situations
1844 /// we could hit exponential behavior, but at least there is nothing
1845 /// unbounded.
1846 std::vector<Function*> CallStack;
1847
1848 // Call the function.
Chris Lattner65a3a092005-09-27 04:45:34 +00001849 Constant *RetValDummy;
1850 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1851 CallStack, MutatedMemory, AllocaTmps);
Chris Lattnerda1889b2005-09-27 04:27:01 +00001852 if (EvalSuccess) {
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001853 // We succeeded at evaluation: commit the result.
1854 DEBUG(std::cerr << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" <<
Chris Lattnerda1889b2005-09-27 04:27:01 +00001855 F->getName() << "' to " << MutatedMemory.size() << " stores.\n");
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001856 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1857 E = MutatedMemory.end(); I != E; ++I)
1858 CommitValueTo(I->second, I->first);
1859 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001860
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001861 // At this point, we are done interpreting. If we created any 'alloca'
1862 // temporaries, release them now.
1863 while (!AllocaTmps.empty()) {
1864 GlobalVariable *Tmp = AllocaTmps.back();
1865 AllocaTmps.pop_back();
Chris Lattnerda1889b2005-09-27 04:27:01 +00001866
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001867 // If there are still users of the alloca, the program is doing something
1868 // silly, e.g. storing the address of the alloca somewhere and using it
1869 // later. Since this is undefined, we'll just make it be null.
1870 if (!Tmp->use_empty())
1871 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1872 delete Tmp;
1873 }
Chris Lattner46d9ff082005-09-26 07:34:35 +00001874
Chris Lattnerda1889b2005-09-27 04:27:01 +00001875 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001876}
1877
Chris Lattner696beef2005-09-26 02:31:18 +00001878
Chris Lattnerda1889b2005-09-27 04:27:01 +00001879
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001880/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1881/// Return true if anything changed.
1882bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1883 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1884 bool MadeChange = false;
1885 if (Ctors.empty()) return false;
1886
1887 // Loop over global ctors, optimizing them when we can.
1888 for (unsigned i = 0; i != Ctors.size(); ++i) {
1889 Function *F = Ctors[i];
1890 // Found a null terminator in the middle of the list, prune off the rest of
1891 // the list.
Chris Lattner838bdc12005-09-26 02:19:27 +00001892 if (F == 0) {
1893 if (i != Ctors.size()-1) {
1894 Ctors.resize(i+1);
1895 MadeChange = true;
1896 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001897 break;
1898 }
1899
Chris Lattner99e23fa2005-09-26 04:44:35 +00001900 // We cannot simplify external ctor functions.
1901 if (F->empty()) continue;
1902
1903 // If we can evaluate the ctor at compile time, do.
1904 if (EvaluateStaticConstructor(F)) {
1905 Ctors.erase(Ctors.begin()+i);
1906 MadeChange = true;
1907 --i;
1908 ++NumCtorsEvaluated;
1909 continue;
1910 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001911 }
1912
1913 if (!MadeChange) return false;
1914
Chris Lattner696beef2005-09-26 02:31:18 +00001915 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001916 return true;
1917}
1918
1919
Chris Lattner25db5802004-10-07 04:16:33 +00001920bool GlobalOpt::runOnModule(Module &M) {
1921 bool Changed = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001922
1923 // Try to find the llvm.globalctors list.
1924 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001925
Chris Lattner25db5802004-10-07 04:16:33 +00001926 bool LocalChange = true;
1927 while (LocalChange) {
1928 LocalChange = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001929
1930 // Delete functions that are trivially dead, ccc -> fastcc
1931 LocalChange |= OptimizeFunctions(M);
1932
1933 // Optimize global_ctors list.
1934 if (GlobalCtors)
1935 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1936
1937 // Optimize non-address-taken globals.
1938 LocalChange |= OptimizeGlobalVars(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001939 Changed |= LocalChange;
1940 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001941
1942 // TODO: Move all global ctors functions to the end of the module for code
1943 // layout.
1944
Chris Lattner25db5802004-10-07 04:16:33 +00001945 return Changed;
1946}