blob: 6aea4aa0e879b3f9d38f9098eeb3638d45ef7932 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +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 Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// 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.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000026#include "llvm/Target/TargetData.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000027#include "llvm/Support/Compiler.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000028#include "llvm/Support/Debug.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000029#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/ADT/Statistic.h"
Chris Lattner670c8892004-10-08 17:32:09 +000031#include "llvm/ADT/StringExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000032#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000033#include <set>
Chris Lattner079236d2004-02-25 21:34:36 +000034using namespace llvm;
35
Chris Lattner86453c52006-12-19 22:09:18 +000036STATISTIC(NumMarked , "Number of globals marked constant");
37STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
38STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
39STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
40STATISTIC(NumDeleted , "Number of globals deleted");
41STATISTIC(NumFnDeleted , "Number of functions deleted");
42STATISTIC(NumGlobUses , "Number of global uses devirtualized");
43STATISTIC(NumLocalized , "Number of globals localized");
44STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
45STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
46STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Chris Lattner079236d2004-02-25 21:34:36 +000047
Chris Lattner86453c52006-12-19 22:09:18 +000048namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000049 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000050 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addRequired<TargetData>();
52 }
Devang Patel19974732007-05-03 01:11:54 +000053 static char ID; // Pass identifcation, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000054 GlobalOpt() : ModulePass((intptr_t)&ID) {}
Misha Brukmanfd939082005-04-21 23:48:37 +000055
Chris Lattnerb12914b2004-09-20 04:48:05 +000056 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000057
58 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000059 GlobalVariable *FindGlobalCtors(Module &M);
60 bool OptimizeFunctions(Module &M);
61 bool OptimizeGlobalVars(Module &M);
62 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000063 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000064 };
65
Devang Patel19974732007-05-03 01:11:54 +000066 char GlobalOpt::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000067 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
Chris Lattner079236d2004-02-25 21:34:36 +000068}
69
Chris Lattner7a90b682004-10-07 04:16:33 +000070ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000071
Chris Lattner7a90b682004-10-07 04:16:33 +000072/// 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 Lattnercf4d2a52004-10-07 21:30:30 +000074/// this info will be accurate.
Reid Spencer9133fe22007-02-05 23:32:05 +000075struct VISIBILITY_HIDDEN GlobalStatus {
Chris Lattnercf4d2a52004-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 Lattner7a90b682004-10-07 04:16:33 +000078 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000079
80 /// StoredType - Keep track of what stores to the global look like.
81 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000082 enum StoredType {
Chris Lattnercf4d2a52004-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 Lattner7a90b682004-10-07 04:16:33 +0000101 } StoredType;
Chris Lattnercf4d2a52004-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 Lattner25de4e52006-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 Evlogimenosf64ea9d2005-02-10 18:36:30 +0000111 Function *AccessingFunction;
112 bool HasMultipleAccessingFunctions;
113
Chris Lattner25de4e52006-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 Lattner553ca522005-06-15 21:11:48 +0000116 bool HasNonInstructionUser;
117
Chris Lattner25de4e52006-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 Lattnercf4d2a52004-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 Lattner7a90b682004-10-07 04:16:33 +0000124 bool isNotSuitableForSRA;
Chris Lattner9ce30002004-07-20 03:58:07 +0000125
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000126 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000127 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner25de4e52006-11-01 18:03:33 +0000128 HasNonInstructionUser(false), HasPHIUser(false),
129 isNotSuitableForSRA(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000130};
Chris Lattnere47ba742004-10-06 20:57:02 +0000131
Chris Lattnera4be1dc2004-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 Lattner7a90b682004-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.
Chris Lattner079236d2004-02-25 21:34:36 +0000153///
Chris Lattner7a90b682004-10-07 04:16:33 +0000154static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
155 std::set<PHINode*> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000156 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000157 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000158 GS.HasNonInstructionUser = true;
159
Chris Lattner7a90b682004-10-07 04:16:33 +0000160 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
161 if (CE->getOpcode() != Instruction::GetElementPtr)
162 GS.isNotSuitableForSRA = true;
Chris Lattner670c8892004-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 Lattner079236d2004-02-25 21:34:36 +0000178 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-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 Lattner7a90b682004-10-07 04:16:33 +0000186 if (isa<LoadInst>(I)) {
187 GS.isLoaded = true;
188 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-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 Lattnercf4d2a52004-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 Lattnerbd38edf2004-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 Lattnercf4d2a52004-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 Lattnerbd38edf2004-11-14 20:50:30 +0000208 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000209 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000210 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000211 // noop.
212 } else {
213 GS.StoredType = GlobalStatus::isStored;
214 }
215 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000216 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000217 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000218 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000219 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner30ba5692004-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 Brukmanfd939082005-04-21 23:48:37 +0000224 !cast<Constant>(I->getOperand(1))->isNullValue() ||
Chris Lattner30ba5692004-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 Lattner35c81b02005-02-27 18:58:52 +0000236 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-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 Lattner25de4e52006-11-01 18:03:33 +0000245 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000246 } else if (isa<CmpInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000247 GS.isNotSuitableForSRA = true;
Chris Lattner35c81b02005-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 Lattner7a90b682004-10-07 04:16:33 +0000258 } else {
259 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000260 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000261 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000262 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-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 Lattner079236d2004-02-25 21:34:36 +0000266 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000267 GS.HasNonInstructionUser = true;
268 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000269 return true;
270 }
271
272 return false;
273}
274
Chris Lattner670c8892004-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 Spencerb83eb642006-10-20 07:07:24 +0000278 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000279
Chris Lattner670c8892004-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);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000284 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000285 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000286 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-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 Lattner7a7ed022004-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 Lattner670c8892004-10-08 17:32:09 +0000302 }
303 return 0;
304}
Chris Lattner7a90b682004-10-07 04:16:33 +0000305
Chris Lattner7a90b682004-10-07 04:16:33 +0000306
Chris Lattnere47ba742004-10-06 20:57:02 +0000307/// 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 Lattner031955d2004-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 Lattner7a90b682004-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 Brukmanfd939082005-04-21 23:48:37 +0000315
Chris Lattner7a90b682004-10-07 04:16:33 +0000316 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-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 Lattner7a90b682004-10-07 04:16:33 +0000323 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000324 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000325 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000326 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000327 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
328 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000329 Constant *SubInit = 0;
330 if (Init)
331 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000332 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000333 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000334 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 Lattner7a90b682004-10-07 04:16:33 +0000342 }
343 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner0b142e32005-09-26 05:34:07 +0000344 Constant *SubInit = 0;
Chris Lattner798b4d52005-09-26 06:52:44 +0000345 ConstantExpr *CE =
346 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner9a5582f2005-09-27 22:28:11 +0000347 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner0b142e32005-09-26 05:34:07 +0000348 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000349 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000350
Chris Lattner031955d2004-10-10 16:43:46 +0000351 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000352 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000353 Changed = true;
354 }
Chris Lattner35c81b02005-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 Lattnera4be1dc2004-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 Lattner35c81b02005-02-27 18:58:52 +0000366 // This could have invalidated UI, start over from scratch.
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000367 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000368 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000369 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000370 }
371 }
Chris Lattner031955d2004-10-10 16:43:46 +0000372 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000373}
374
Chris Lattner670c8892004-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 Brukmanfd939082005-04-21 23:48:37 +0000384
Chris Lattner670c8892004-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 Spencerc5b206b2006-12-31 05:48:39 +0000392 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-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,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000396 In, GV->getName()+"."+utostr(i),
397 (Module *)NULL,
398 GV->isThreadLocal());
Chris Lattner670c8892004-10-08 17:32:09 +0000399 Globals.insert(GV, NGV);
400 NewGlobals.push_back(NGV);
401 }
402 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
403 unsigned NumElements = 0;
404 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
405 NumElements = ATy->getNumElements();
Reid Spencer9d6565a2007-02-15 02:26:10 +0000406 else if (const VectorType *PTy = dyn_cast<VectorType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000407 NumElements = PTy->getNumElements();
408 else
409 assert(0 && "Unknown aggregate sequential type!");
410
Chris Lattner1f21ef12005-02-23 16:53:04 +0000411 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000412 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000413 NewGlobals.reserve(NumElements);
414 for (unsigned i = 0, e = NumElements; i != e; ++i) {
415 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000416 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000417 assert(In && "Couldn't get element of initializer?");
418
419 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
420 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000421 In, GV->getName()+"."+utostr(i),
422 (Module *)NULL,
423 GV->isThreadLocal());
Chris Lattner670c8892004-10-08 17:32:09 +0000424 Globals.insert(GV, NGV);
425 NewGlobals.push_back(NGV);
426 }
427 }
428
429 if (NewGlobals.empty())
430 return 0;
431
Bill Wendling0a81aac2006-11-26 10:02:32 +0000432 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000433
Reid Spencerc5b206b2006-12-31 05:48:39 +0000434 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner670c8892004-10-08 17:32:09 +0000435
436 // Loop over all of the uses of the global, replacing the constantexpr geps,
437 // with smaller constantexpr geps or direct references.
438 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000439 User *GEP = GV->use_back();
440 assert(((isa<ConstantExpr>(GEP) &&
441 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
442 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000443
Chris Lattner670c8892004-10-08 17:32:09 +0000444 // Ignore the 1th operand, which has to be zero or else the program is quite
445 // broken (undefined). Get the 2nd operand, which is the structure or array
446 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000447 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000448 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
449
Chris Lattner30ba5692004-10-11 05:54:41 +0000450 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000451
452 // Form a shorter GEP if needed.
Chris Lattner30ba5692004-10-11 05:54:41 +0000453 if (GEP->getNumOperands() > 3)
454 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000455 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000456 Idxs.push_back(NullInt);
457 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
458 Idxs.push_back(CE->getOperand(i));
Chris Lattner55eb1c42007-01-31 04:40:53 +0000459 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
460 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000461 } else {
462 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000463 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000464 Idxs.push_back(NullInt);
465 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
466 Idxs.push_back(GEPI->getOperand(i));
Chris Lattner699d1442007-01-31 19:59:55 +0000467 NewPtr = new GetElementPtrInst(NewPtr, &Idxs[0], Idxs.size(),
Chris Lattner30ba5692004-10-11 05:54:41 +0000468 GEPI->getName()+"."+utostr(Val), GEPI);
469 }
470 GEP->replaceAllUsesWith(NewPtr);
471
472 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000473 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000474 else
475 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000476 }
477
Chris Lattnere40e2d12004-10-08 20:25:55 +0000478 // Delete the old global, now that it is dead.
479 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000480 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000481
482 // Loop over the new globals array deleting any globals that are obviously
483 // dead. This can arise due to scalarization of a structure or an array that
484 // has elements that are dead.
485 unsigned FirstGlobal = 0;
486 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
487 if (NewGlobals[i]->use_empty()) {
488 Globals.erase(NewGlobals[i]);
489 if (FirstGlobal == i) ++FirstGlobal;
490 }
491
492 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000493}
494
Chris Lattner9b34a612004-10-09 21:48:45 +0000495/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
496/// value will trap if the value is dynamically null.
497static bool AllUsesOfValueWillTrapIfNull(Value *V) {
498 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
499 if (isa<LoadInst>(*UI)) {
500 // Will trap.
501 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
502 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000503 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000504 return false; // Storing the value.
505 }
506 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
507 if (CI->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000508 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000509 return false; // Not calling the ptr
510 }
511 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
512 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000513 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000514 return false; // Not calling the ptr
515 }
516 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
517 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
518 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
519 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000520 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000521 isa<ConstantPointerNull>(UI->getOperand(1))) {
522 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000523 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000524 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000525 return false;
526 }
527 return true;
528}
529
530/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000531/// from GV will trap if the loaded value is null. Note that this also permits
532/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000533static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
534 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
535 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
536 if (!AllUsesOfValueWillTrapIfNull(LI))
537 return false;
538 } else if (isa<StoreInst>(*UI)) {
539 // Ignore stores to the global.
540 } else {
541 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000542 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000543 return false;
544 }
545
546 return true;
547}
548
Chris Lattner708148e2004-10-10 23:14:11 +0000549static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
550 bool Changed = false;
551 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
552 Instruction *I = cast<Instruction>(*UI++);
553 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
554 LI->setOperand(0, NewV);
555 Changed = true;
556 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
557 if (SI->getOperand(1) == V) {
558 SI->setOperand(1, NewV);
559 Changed = true;
560 }
561 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
562 if (I->getOperand(0) == V) {
563 // Calling through the pointer! Turn into a direct call, but be careful
564 // that the pointer is not also being passed as an argument.
565 I->setOperand(0, NewV);
566 Changed = true;
567 bool PassedAsArg = false;
568 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
569 if (I->getOperand(i) == V) {
570 PassedAsArg = true;
571 I->setOperand(i, NewV);
572 }
573
574 if (PassedAsArg) {
575 // Being passed as an argument also. Be careful to not invalidate UI!
576 UI = V->use_begin();
577 }
578 }
579 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
580 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000581 ConstantExpr::getCast(CI->getOpcode(),
582 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000583 if (CI->use_empty()) {
584 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000585 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000586 }
587 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
588 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000589 SmallVector<Constant*, 8> Idxs;
590 Idxs.reserve(GEPI->getNumOperands()-1);
Chris Lattner708148e2004-10-10 23:14:11 +0000591 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
592 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000593 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000594 else
595 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000596 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000597 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Chris Lattner55eb1c42007-01-31 04:40:53 +0000598 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
599 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000600 if (GEPI->use_empty()) {
601 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000602 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000603 }
604 }
605 }
606
607 return Changed;
608}
609
610
611/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
612/// value stored into it. If there are uses of the loaded value that would trap
613/// if the loaded value is dynamically null, then we know that they cannot be
614/// reachable with a null optimize away the load.
615static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
616 std::vector<LoadInst*> Loads;
617 bool Changed = false;
618
619 // Replace all uses of loads with uses of uses of the stored value.
620 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
621 GUI != E; ++GUI)
622 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
623 Loads.push_back(LI);
624 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
625 } else {
626 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
627 }
628
629 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000630 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000631 ++NumGlobUses;
632 }
633
634 // Delete all of the loads we can, keeping track of whether we nuked them all!
635 bool AllLoadsGone = true;
636 while (!Loads.empty()) {
637 LoadInst *L = Loads.back();
638 if (L->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000639 L->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000640 Changed = true;
641 } else {
642 AllLoadsGone = false;
643 }
644 Loads.pop_back();
645 }
646
647 // If we nuked all of the loads, then none of the stores are needed either,
648 // nor is the global.
649 if (AllLoadsGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000650 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattner708148e2004-10-10 23:14:11 +0000651 CleanupConstantGlobalUsers(GV, 0);
652 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000653 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000654 ++NumDeleted;
655 }
656 Changed = true;
657 }
658 return Changed;
659}
660
Chris Lattner30ba5692004-10-11 05:54:41 +0000661/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
662/// instructions that are foldable.
663static void ConstantPropUsersOf(Value *V) {
664 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
665 if (Instruction *I = dyn_cast<Instruction>(*UI++))
666 if (Constant *NewC = ConstantFoldInstruction(I)) {
667 I->replaceAllUsesWith(NewC);
668
Chris Lattnerd514d822005-02-01 01:23:31 +0000669 // Advance UI to the next non-I use to avoid invalidating it!
670 // Instructions could multiply use V.
671 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000672 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000673 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000674 }
675}
676
677/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
678/// variable, and transforms the program as if it always contained the result of
679/// the specified malloc. Because it is always the result of the specified
680/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000681/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000682static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
683 MallocInst *MI) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000684 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000685 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
686
Reid Spencerb83eb642006-10-20 07:07:24 +0000687 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000688 // If we have an array allocation, transform it to a single element
689 // allocation to make the code below simpler.
690 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000691 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000692 MallocInst *NewMI =
Reid Spencerc5b206b2006-12-31 05:48:39 +0000693 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
Nate Begeman14b05292005-11-05 09:21:28 +0000694 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000695 Value* Indices[2];
696 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
697 Value *NewGEP = new GetElementPtrInst(NewMI, Indices, 2,
Chris Lattner30ba5692004-10-11 05:54:41 +0000698 NewMI->getName()+".el0", MI);
699 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000700 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000701 MI = NewMI;
702 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000703
Chris Lattner7a7ed022004-10-16 18:09:00 +0000704 // Create the new global variable. The contents of the malloc'd memory is
705 // undefined, so initialize with an undef value.
706 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000707 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
708 GlobalValue::InternalLinkage, Init,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000709 GV->getName()+".body",
710 (Module *)NULL,
711 GV->isThreadLocal());
Chris Lattner30ba5692004-10-11 05:54:41 +0000712 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanfd939082005-04-21 23:48:37 +0000713
Chris Lattner30ba5692004-10-11 05:54:41 +0000714 // Anything that used the malloc now uses the global directly.
715 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000716
717 Constant *RepValue = NewGV;
718 if (NewGV->getType() != GV->getType()->getElementType())
Reid Spencerd977d862006-12-12 23:36:14 +0000719 RepValue = ConstantExpr::getBitCast(RepValue,
720 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000721
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000722 // If there is a comparison against null, we will insert a global bool to
723 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000724 GlobalVariable *InitBool =
Reid Spencer4fe16d62007-01-11 18:21:29 +0000725 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000726 ConstantInt::getFalse(), GV->getName()+".init",
727 (Module *)NULL, GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000728 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000729
Chris Lattner30ba5692004-10-11 05:54:41 +0000730 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000731 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000732 while (!GV->use_empty())
733 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000734 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000735 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000736 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000737 LoadUse = RepValue;
738 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000739 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
740 // Replace the cmp X, 0 with a use of the bool value.
741 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000742 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000743 switch (CI->getPredicate()) {
744 default: assert(0 && "Unknown ICmp Predicate!");
745 case ICmpInst::ICMP_ULT:
746 case ICmpInst::ICMP_SLT:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000747 LV = ConstantInt::getFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000748 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000749 case ICmpInst::ICMP_ULE:
750 case ICmpInst::ICMP_SLE:
751 case ICmpInst::ICMP_EQ:
752 LV = BinaryOperator::createNot(LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000753 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000754 case ICmpInst::ICMP_NE:
755 case ICmpInst::ICMP_UGE:
756 case ICmpInst::ICMP_SGE:
757 case ICmpInst::ICMP_UGT:
758 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000759 break; // no change.
760 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000761 CI->replaceAllUsesWith(LV);
762 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000763 }
764 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000765 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000766 } else {
767 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000768 // The global is initialized when the store to it occurs.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000769 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000770 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000771 }
772
Chris Lattnerbc965b92004-12-02 06:25:58 +0000773 // If the initialization boolean was used, insert it, otherwise delete it.
774 if (!InitBoolUsed) {
775 while (!InitBool->use_empty()) // Delete initializations
776 cast<Instruction>(InitBool->use_back())->eraseFromParent();
777 delete InitBool;
778 } else
779 GV->getParent()->getGlobalList().insert(GV, InitBool);
780
781
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000782 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000783 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000784 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000785
786 // To further other optimizations, loop over all users of NewGV and try to
787 // constant prop them. This will promote GEP instructions with constant
788 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
789 ConstantPropUsersOf(NewGV);
790 if (RepValue != NewGV)
791 ConstantPropUsersOf(RepValue);
792
793 return NewGV;
794}
Chris Lattner708148e2004-10-10 23:14:11 +0000795
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000796/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
797/// to make sure that there are no complex uses of V. We permit simple things
798/// like dereferencing the pointer, but not storing through the address, unless
799/// it is to the specified global.
800static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
801 GlobalVariable *GV) {
802 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
Reid Spencere4d87aa2006-12-23 06:05:41 +0000803 if (isa<LoadInst>(*UI) || isa<CmpInst>(*UI)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000804 // Fine, ignore.
805 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
806 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
807 return false; // Storing the pointer itself... bad.
808 // Otherwise, storing through it, or storing into GV... fine.
809 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
810 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
811 return false;
812 } else {
813 return false;
814 }
815 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000816}
817
Chris Lattner86395032006-09-30 23:32:09 +0000818/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
819/// somewhere. Transform all uses of the allocation into loads from the
820/// global and uses of the resultant pointer. Further, delete the store into
821/// GV. This assumes that these value pass the
822/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
823static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
824 GlobalVariable *GV) {
825 while (!Alloc->use_empty()) {
826 Instruction *U = Alloc->use_back();
827 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
828 // If this is the store of the allocation into the global, remove it.
829 if (SI->getOperand(1) == GV) {
830 SI->eraseFromParent();
831 continue;
832 }
833 }
834
835 // Insert a load from the global, and use it instead of the malloc.
836 Value *NL = new LoadInst(GV, GV->getName()+".val", U);
837 U->replaceUsesOfWith(Alloc, NL);
838 }
839}
840
841/// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
842/// GV are simple enough to perform HeapSRA, return true.
843static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
844 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
845 ++UI)
846 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
847 // We permit two users of the load: setcc comparing against the null
848 // pointer, and a getelementptr of a specific form.
849 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
850 ++UI) {
851 // Comparison against null is ok.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000852 if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
853 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
Chris Lattner86395032006-09-30 23:32:09 +0000854 return false;
855 continue;
856 }
857
858 // getelementptr is also ok, but only a simple form.
859 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
860 if (!GEPI) return false;
861
862 // Must index into the array and into the struct.
863 if (GEPI->getNumOperands() < 3)
864 return false;
865
866 // Otherwise the GEP is ok.
867 continue;
868 }
869 }
870 return true;
871}
872
873/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
874/// is a value loaded from the global. Eliminate all uses of Ptr, making them
875/// use FieldGlobals instead. All uses of loaded values satisfy
876/// GlobalLoadUsesSimpleEnoughForHeapSRA.
877static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr,
878 const std::vector<GlobalVariable*> &FieldGlobals) {
879 std::vector<Value *> InsertedLoadsForPtr;
880 //InsertedLoadsForPtr.resize(FieldGlobals.size());
881 while (!Ptr->use_empty()) {
882 Instruction *User = Ptr->use_back();
883
884 // If this is a comparison against null, handle it.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000885 if (ICmpInst *SCI = dyn_cast<ICmpInst>(User)) {
Chris Lattner86395032006-09-30 23:32:09 +0000886 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
887 // If we have a setcc of the loaded pointer, we can use a setcc of any
888 // field.
889 Value *NPtr;
890 if (InsertedLoadsForPtr.empty()) {
891 NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
892 InsertedLoadsForPtr.push_back(Ptr);
893 } else {
894 NPtr = InsertedLoadsForPtr.back();
895 }
896
Reid Spencere4d87aa2006-12-23 06:05:41 +0000897 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
898 Constant::getNullValue(NPtr->getType()),
899 SCI->getName(), SCI);
Chris Lattner86395032006-09-30 23:32:09 +0000900 SCI->replaceAllUsesWith(New);
901 SCI->eraseFromParent();
902 continue;
903 }
904
905 // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
906 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
Reid Spencerb83eb642006-10-20 07:07:24 +0000907 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
Chris Lattner86395032006-09-30 23:32:09 +0000908 && "Unexpected GEPI!");
909
910 // Load the pointer for this field.
Reid Spencerb83eb642006-10-20 07:07:24 +0000911 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner86395032006-09-30 23:32:09 +0000912 if (InsertedLoadsForPtr.size() <= FieldNo)
913 InsertedLoadsForPtr.resize(FieldNo+1);
914 if (InsertedLoadsForPtr[FieldNo] == 0)
915 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
916 Ptr->getName()+".f" +
917 utostr(FieldNo), Ptr);
918 Value *NewPtr = InsertedLoadsForPtr[FieldNo];
919
920 // Create the new GEP idx vector.
Chris Lattner1ccd1852007-02-12 22:56:41 +0000921 SmallVector<Value*, 8> GEPIdx;
Chris Lattner86395032006-09-30 23:32:09 +0000922 GEPIdx.push_back(GEPI->getOperand(1));
Chris Lattner1ccd1852007-02-12 22:56:41 +0000923 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Chris Lattner86395032006-09-30 23:32:09 +0000924
Chris Lattner1ccd1852007-02-12 22:56:41 +0000925 Value *NGEPI = new GetElementPtrInst(NewPtr, &GEPIdx[0], GEPIdx.size(),
926 GEPI->getName(), GEPI);
Chris Lattner86395032006-09-30 23:32:09 +0000927 GEPI->replaceAllUsesWith(NGEPI);
928 GEPI->eraseFromParent();
929 }
930}
931
932/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
933/// it up into multiple allocations of arrays of the fields.
934static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Bill Wendling0a81aac2006-11-26 10:02:32 +0000935 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +0000936 const StructType *STy = cast<StructType>(MI->getAllocatedType());
937
938 // There is guaranteed to be at least one use of the malloc (storing
939 // it into GV). If there are other uses, change them to be uses of
940 // the global to simplify later code. This also deletes the store
941 // into GV.
942 ReplaceUsesOfMallocWithGlobal(MI, GV);
943
944 // Okay, at this point, there are no users of the malloc. Insert N
945 // new mallocs at the same place as MI, and N globals.
946 std::vector<GlobalVariable*> FieldGlobals;
947 std::vector<MallocInst*> FieldMallocs;
948
949 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
950 const Type *FieldTy = STy->getElementType(FieldNo);
951 const Type *PFieldTy = PointerType::get(FieldTy);
952
953 GlobalVariable *NGV =
954 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
955 Constant::getNullValue(PFieldTy),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000956 GV->getName() + ".f" + utostr(FieldNo), GV,
957 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +0000958 FieldGlobals.push_back(NGV);
959
960 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
961 MI->getName() + ".f" + utostr(FieldNo),MI);
962 FieldMallocs.push_back(NMI);
963 new StoreInst(NMI, NGV, MI);
964 }
965
966 // The tricky aspect of this transformation is handling the case when malloc
967 // fails. In the original code, malloc failing would set the result pointer
968 // of malloc to null. In this case, some mallocs could succeed and others
969 // could fail. As such, we emit code that looks like this:
970 // F0 = malloc(field0)
971 // F1 = malloc(field1)
972 // F2 = malloc(field2)
973 // if (F0 == 0 || F1 == 0 || F2 == 0) {
974 // if (F0) { free(F0); F0 = 0; }
975 // if (F1) { free(F1); F1 = 0; }
976 // if (F2) { free(F2); F2 = 0; }
977 // }
978 Value *RunningOr = 0;
979 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000980 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Chris Lattner86395032006-09-30 23:32:09 +0000981 Constant::getNullValue(FieldMallocs[i]->getType()),
982 "isnull", MI);
983 if (!RunningOr)
984 RunningOr = Cond; // First seteq
985 else
986 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
987 }
988
989 // Split the basic block at the old malloc.
990 BasicBlock *OrigBB = MI->getParent();
991 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
992
993 // Create the block to check the first condition. Put all these blocks at the
994 // end of the function as they are unlikely to be executed.
995 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
996 OrigBB->getParent());
997
998 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
999 // branch on RunningOr.
1000 OrigBB->getTerminator()->eraseFromParent();
1001 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
1002
1003 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1004 // pointer, because some may be null while others are not.
1005 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1006 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001007 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1008 Constant::getNullValue(GVVal->getType()),
1009 "tmp", NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001010 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
1011 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
1012 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1013
1014 // Fill in FreeBlock.
1015 new FreeInst(GVVal, FreeBlock);
1016 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1017 FreeBlock);
1018 new BranchInst(NextBlock, FreeBlock);
1019
1020 NullPtrBlock = NextBlock;
1021 }
1022
1023 new BranchInst(ContBB, NullPtrBlock);
1024
1025
1026 // MI is no longer needed, remove it.
1027 MI->eraseFromParent();
1028
1029
1030 // Okay, the malloc site is completely handled. All of the uses of GV are now
1031 // loads, and all uses of those loads are simple. Rewrite them to use loads
1032 // of the per-field globals instead.
1033 while (!GV->use_empty()) {
Chris Lattner39ff1e22007-01-09 23:29:37 +00001034 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1035 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1036 LI->eraseFromParent();
1037 } else {
1038 // Must be a store of null.
1039 StoreInst *SI = cast<StoreInst>(GV->use_back());
1040 assert(isa<Constant>(SI->getOperand(0)) &&
1041 cast<Constant>(SI->getOperand(0))->isNullValue() &&
1042 "Unexpected heap-sra user!");
1043
1044 // Insert a store of null into each global.
1045 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1046 Constant *Null =
1047 Constant::getNullValue(FieldGlobals[i]->getType()->getElementType());
1048 new StoreInst(Null, FieldGlobals[i], SI);
1049 }
1050 // Erase the original store.
1051 SI->eraseFromParent();
1052 }
Chris Lattner86395032006-09-30 23:32:09 +00001053 }
1054
1055 // The old global is now dead, remove it.
1056 GV->eraseFromParent();
1057
1058 ++NumHeapSRA;
1059 return FieldGlobals[0];
1060}
1061
1062
Chris Lattner9b34a612004-10-09 21:48:45 +00001063// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1064// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001065static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001066 Module::global_iterator &GVI,
1067 TargetData &TD) {
Chris Lattner9b34a612004-10-09 21:48:45 +00001068 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1069 StoredOnceVal = CI->getOperand(0);
1070 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattner708148e2004-10-10 23:14:11 +00001071 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner9b34a612004-10-09 21:48:45 +00001072 bool IsJustACast = true;
1073 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1074 if (!isa<Constant>(GEPI->getOperand(i)) ||
1075 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1076 IsJustACast = false;
1077 break;
1078 }
1079 if (IsJustACast)
1080 StoredOnceVal = GEPI->getOperand(0);
1081 }
1082
Chris Lattner708148e2004-10-10 23:14:11 +00001083 // If we are dealing with a pointer global that is initialized to null and
1084 // only has one (non-null) value stored into it, then we can optimize any
1085 // users of the loaded value (often calls and loads) that would trap if the
1086 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001087 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1088 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001089 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1090 if (GV->getInitializer()->getType() != SOVC->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001091 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001092
Chris Lattner708148e2004-10-10 23:14:11 +00001093 // Optimize away any trapping uses of the loaded value.
1094 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001095 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001096 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001097 // If this is a malloc of an abstract type, don't touch it.
1098 if (!MI->getAllocatedType()->isSized())
1099 return false;
1100
Chris Lattner86395032006-09-30 23:32:09 +00001101 // We can't optimize this global unless all uses of it are *known* to be
1102 // of the malloc value, not of the null initializer value (consider a use
1103 // that compares the global's value against zero to see if the malloc has
1104 // been reached). To do this, we check to see if all uses of the global
1105 // would trap if the global were null: this proves that they must all
1106 // happen after the malloc.
1107 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1108 return false;
1109
1110 // We can't optimize this if the malloc itself is used in a complex way,
1111 // for example, being stored into multiple globals. This allows the
1112 // malloc to be stored into the specified global, loaded setcc'd, and
1113 // GEP'd. These are all things we could transform to using the global
1114 // for.
1115 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1116 return false;
1117
1118
Chris Lattner30ba5692004-10-11 05:54:41 +00001119 // If we have a global that is only initialized with a fixed size malloc,
Chris Lattner86395032006-09-30 23:32:09 +00001120 // transform the program to use global memory instead of malloc'd memory.
1121 // This eliminates dynamic allocation, avoids an indirection accessing the
1122 // data, and exposes the resultant global to further GlobalOpt.
Chris Lattnercff16732006-09-30 19:40:30 +00001123 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
Chris Lattner86395032006-09-30 23:32:09 +00001124 // Restrict this transformation to only working on small allocations
1125 // (2048 bytes currently), as we don't want to introduce a 16M global or
1126 // something.
Reid Spencerb83eb642006-10-20 07:07:24 +00001127 if (NElements->getZExtValue()*
Chris Lattner86395032006-09-30 23:32:09 +00001128 TD.getTypeSize(MI->getAllocatedType()) < 2048) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001129 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1130 return true;
1131 }
Chris Lattnercff16732006-09-30 19:40:30 +00001132 }
Chris Lattner86395032006-09-30 23:32:09 +00001133
1134 // If the allocation is an array of structures, consider transforming this
1135 // into multiple malloc'd arrays, one for each field. This is basically
1136 // SRoA for malloc'd memory.
1137 if (const StructType *AllocTy =
1138 dyn_cast<StructType>(MI->getAllocatedType())) {
1139 // This the structure has an unreasonable number of fields, leave it
1140 // alone.
1141 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1142 GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1143 GVI = PerformHeapAllocSRoA(GV, MI);
1144 return true;
1145 }
1146 }
Chris Lattner708148e2004-10-10 23:14:11 +00001147 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001148 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001149
Chris Lattner9b34a612004-10-09 21:48:45 +00001150 return false;
1151}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001152
Chris Lattner96a86b22004-12-12 05:53:50 +00001153/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
Misha Brukmanfd939082005-04-21 23:48:37 +00001154/// values ever stored into GV are its initializer and OtherVal.
Chris Lattner96a86b22004-12-12 05:53:50 +00001155static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1156 // Create the new global, initializing it to false.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001157 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001158 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001159 GV->getName()+".b",
1160 (Module *)NULL,
1161 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001162 GV->getParent()->getGlobalList().insert(GV, NewGV);
1163
1164 Constant *InitVal = GV->getInitializer();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001165 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001166
1167 // If initialized to zero and storing one into the global, we can use a cast
1168 // instead of a select to synthesize the desired value.
1169 bool IsOneZero = false;
1170 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001171 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001172
1173 while (!GV->use_empty()) {
1174 Instruction *UI = cast<Instruction>(GV->use_back());
1175 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1176 // Change the store into a boolean store.
1177 bool StoringOther = SI->getOperand(0) == OtherVal;
1178 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001179 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001180 if (StoringOther || SI->getOperand(0) == InitVal)
Reid Spencer579dca12007-01-12 04:24:46 +00001181 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001182 else {
1183 // Otherwise, we are storing a previously loaded copy. To do this,
1184 // change the copy from copying the original value to just copying the
1185 // bool.
1186 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1187
1188 // If we're already replaced the input, StoredVal will be a cast or
1189 // select instruction. If not, it will be a load of the original
1190 // global.
1191 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1192 assert(LI->getOperand(0) == GV && "Not a copy!");
1193 // Insert a new load, to preserve the saved value.
1194 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1195 } else {
1196 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1197 "This is not a form that we understand!");
1198 StoreVal = StoredVal->getOperand(0);
1199 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1200 }
1201 }
1202 new StoreInst(StoreVal, NewGV, SI);
1203 } else if (!UI->use_empty()) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001204 // Change the load into a load of bool then a select.
1205 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001206 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001207 Value *NSI;
1208 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001209 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001210 else
Chris Lattner046800a2007-02-11 01:08:35 +00001211 NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI);
1212 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001213 LI->replaceAllUsesWith(NSI);
1214 }
1215 UI->eraseFromParent();
1216 }
1217
1218 GV->eraseFromParent();
1219}
1220
1221
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001222/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1223/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001224bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001225 Module::global_iterator &GVI) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001226 std::set<PHINode*> PHIUsers;
1227 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001228 GV->removeDeadConstantUsers();
1229
1230 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001231 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001232 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001233 ++NumDeleted;
1234 return true;
1235 }
1236
1237 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001238#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001239 cerr << "Global: " << *GV;
1240 cerr << " isLoaded = " << GS.isLoaded << "\n";
1241 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001242 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001243 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1244 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1245 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1246 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001247 }
1248 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001249 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001250 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001251 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001252 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001253 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001254 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001255 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1256 cerr << " isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1257 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001258#endif
1259
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001260 // If this is a first class global and has only one accessing function
1261 // and this function is main (which we know is not recursive we can make
1262 // this global a local variable) we replace the global with a local alloca
1263 // in this function.
1264 //
1265 // NOTE: It doesn't make sense to promote non first class types since we
1266 // are just replacing static memory to stack memory.
1267 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001268 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001269 GV->getType()->getElementType()->isFirstClassType() &&
1270 GS.AccessingFunction->getName() == "main" &&
1271 GS.AccessingFunction->hasExternalLinkage()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001272 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001273 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1274 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001275 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001276 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1277 if (!isa<UndefValue>(GV->getInitializer()))
1278 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001279
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001280 GV->replaceAllUsesWith(Alloca);
1281 GV->eraseFromParent();
1282 ++NumLocalized;
1283 return true;
1284 }
Chris Lattnercff16732006-09-30 19:40:30 +00001285
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001286 // If the global is never loaded (but may be stored to), it is dead.
1287 // Delete it now.
1288 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001289 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001290
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001291 // Delete any stores we can find to the global. We may not be able to
1292 // make it completely dead though.
Chris Lattner031955d2004-10-10 16:43:46 +00001293 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001294
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001295 // If the global is dead now, delete it.
1296 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001297 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001298 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001299 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001300 }
Chris Lattner930f4752004-10-09 03:32:52 +00001301 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001302
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001303 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001304 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001305 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001306
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001307 // Clean up any obviously simplifiable users now.
1308 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001309
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001310 // If the global is dead now, just nuke it.
1311 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001312 DOUT << " *** Marking constant allowed us to simplify "
1313 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001314 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001315 ++NumDeleted;
1316 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001317
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001318 ++NumMarked;
1319 return true;
1320 } else if (!GS.isNotSuitableForSRA &&
1321 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001322 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1323 GVI = FirstNewGV; // Don't skip the newly produced globals!
1324 return true;
1325 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001326 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001327 // If the initial value for the global was an undef value, and if only
1328 // one other value was stored into it, we can just change the
1329 // initializer to be an undef value, then delete all stores to the
1330 // global. This allows us to mark it constant.
1331 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1332 if (isa<UndefValue>(GV->getInitializer())) {
1333 // Change the initial value here.
1334 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001335
Chris Lattner96a86b22004-12-12 05:53:50 +00001336 // Clean up any obviously simplifiable users now.
1337 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001338
Chris Lattner96a86b22004-12-12 05:53:50 +00001339 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001340 DOUT << " *** Substituting initializer allowed us to "
1341 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001342 GV->eraseFromParent();
1343 ++NumDeleted;
1344 } else {
1345 GVI = GV;
1346 }
1347 ++NumSubstitute;
1348 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001349 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001350
Chris Lattner9b34a612004-10-09 21:48:45 +00001351 // Try to optimize globals based on the knowledge that only one value
1352 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001353 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1354 getAnalysis<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001355 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001356
1357 // Otherwise, if the global was not a boolean, we can shrink it to be a
1358 // boolean.
1359 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Reid Spencer4fe16d62007-01-11 18:21:29 +00001360 if (GV->getType()->getElementType() != Type::Int1Ty &&
Chris Lattner25de4e52006-11-01 18:03:33 +00001361 !GV->getType()->getElementType()->isFloatingPoint() &&
Reid Spencer9d6565a2007-02-15 02:26:10 +00001362 !isa<VectorType>(GV->getType()->getElementType()) &&
Chris Lattner4913bf42007-04-05 21:09:42 +00001363 !GS.HasPHIUser && !GS.isNotSuitableForSRA) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001364 DOUT << " *** SHRINKING TO BOOL: " << *GV;
Chris Lattner96a86b22004-12-12 05:53:50 +00001365 ShrinkGlobalToBoolean(GV, SOVConstant);
1366 ++NumShrunkToBool;
1367 return true;
1368 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001369 }
1370 }
1371 return false;
1372}
1373
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001374/// OnlyCalledDirectly - Return true if the specified function is only called
1375/// directly. In other words, its address is never taken.
1376static bool OnlyCalledDirectly(Function *F) {
1377 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1378 Instruction *User = dyn_cast<Instruction>(*UI);
1379 if (!User) return false;
1380 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1381
1382 // See if the function address is passed as an argument.
1383 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1384 if (User->getOperand(i) == F) return false;
1385 }
1386 return true;
1387}
1388
1389/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1390/// function, changing them to FastCC.
1391static void ChangeCalleesToFastCall(Function *F) {
1392 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1393 Instruction *User = cast<Instruction>(*UI);
1394 if (CallInst *CI = dyn_cast<CallInst>(User))
1395 CI->setCallingConv(CallingConv::Fast);
1396 else
1397 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1398 }
1399}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001400
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001401bool GlobalOpt::OptimizeFunctions(Module &M) {
1402 bool Changed = false;
1403 // Optimize functions.
1404 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1405 Function *F = FI++;
1406 F->removeDeadConstantUsers();
1407 if (F->use_empty() && (F->hasInternalLinkage() ||
1408 F->hasLinkOnceLinkage())) {
1409 M.getFunctionList().erase(F);
1410 Changed = true;
1411 ++NumFnDeleted;
1412 } else if (F->hasInternalLinkage() &&
1413 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1414 OnlyCalledDirectly(F)) {
1415 // If this function has C calling conventions, is not a varargs
1416 // function, and is only called directly, promote it to use the Fast
1417 // calling convention.
1418 F->setCallingConv(CallingConv::Fast);
1419 ChangeCalleesToFastCall(F);
1420 ++NumFastCallFns;
1421 Changed = true;
1422 }
1423 }
1424 return Changed;
1425}
1426
1427bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1428 bool Changed = false;
1429 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1430 GVI != E; ) {
1431 GlobalVariable *GV = GVI++;
1432 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1433 GV->hasInitializer())
1434 Changed |= ProcessInternalGlobal(GV, GVI);
1435 }
1436 return Changed;
1437}
1438
1439/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1440/// initializers have an init priority of 65535.
1441GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001442 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1443 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001444 if (I->getName() == "llvm.global_ctors") {
1445 // Found it, verify it's an array of { int, void()* }.
1446 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1447 if (!ATy) return 0;
1448 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1449 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc5b206b2006-12-31 05:48:39 +00001450 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001451 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1452 if (!PFTy) return 0;
1453 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1454 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1455 FTy->getNumParams() != 0)
1456 return 0;
1457
1458 // Verify that the initializer is simple enough for us to handle.
1459 if (!I->hasInitializer()) return 0;
1460 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1461 if (!CA) return 0;
1462 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1463 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001464 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1465 continue;
1466
1467 // Must have a function or null ptr.
1468 if (!isa<Function>(CS->getOperand(1)))
1469 return 0;
1470
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001471 // Init priority must be standard.
1472 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001473 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001474 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001475 } else {
1476 return 0;
1477 }
1478
1479 return I;
1480 }
1481 return 0;
1482}
1483
Chris Lattnerdb973e62005-09-26 02:31:18 +00001484/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1485/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001486static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1487 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1488 std::vector<Function*> Result;
1489 Result.reserve(CA->getNumOperands());
1490 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1491 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1492 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1493 }
1494 return Result;
1495}
1496
Chris Lattnerdb973e62005-09-26 02:31:18 +00001497/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1498/// specified array, returning the new global to use.
1499static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1500 const std::vector<Function*> &Ctors) {
1501 // If we made a change, reassemble the initializer list.
1502 std::vector<Constant*> CSVals;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001503 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001504 CSVals.push_back(0);
1505
1506 // Create the new init list.
1507 std::vector<Constant*> CAList;
1508 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001509 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001510 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001511 } else {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001512 const Type *FTy = FunctionType::get(Type::VoidTy,
1513 std::vector<const Type*>(), false);
1514 const PointerType *PFTy = PointerType::get(FTy);
1515 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001516 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001517 }
1518 CAList.push_back(ConstantStruct::get(CSVals));
1519 }
1520
1521 // Create the array initializer.
1522 const Type *StructTy =
1523 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1524 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1525 CAList);
1526
1527 // If we didn't change the number of elements, don't create a new GV.
1528 if (CA->getType() == GCL->getInitializer()->getType()) {
1529 GCL->setInitializer(CA);
1530 return GCL;
1531 }
1532
1533 // Create the new global and insert it next to the existing list.
1534 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001535 GCL->getLinkage(), CA, "",
1536 (Module *)NULL,
1537 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001538 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001539 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001540
1541 // Nuke the old list, replacing any uses with the new one.
1542 if (!GCL->use_empty()) {
1543 Constant *V = NGV;
1544 if (V->getType() != GCL->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001545 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001546 GCL->replaceAllUsesWith(V);
1547 }
1548 GCL->eraseFromParent();
1549
1550 if (Ctors.size())
1551 return NGV;
1552 else
1553 return 0;
1554}
Chris Lattner79c11012005-09-26 04:44:35 +00001555
1556
1557static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1558 Value *V) {
1559 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1560 Constant *R = ComputedValues[V];
1561 assert(R && "Reference to an uncomputed value!");
1562 return R;
1563}
1564
1565/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1566/// enough for us to understand. In particular, if it is a cast of something,
1567/// we punt. We basically just support direct accesses to globals and GEP's of
1568/// globals. This should be kept up to date with CommitValueTo.
1569static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner231308c2005-09-27 04:50:03 +00001570 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1571 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001572 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00001573 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00001574 }
Chris Lattner798b4d52005-09-26 06:52:44 +00001575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1576 // Handle a constantexpr gep.
1577 if (CE->getOpcode() == Instruction::GetElementPtr &&
1578 isa<GlobalVariable>(CE->getOperand(0))) {
1579 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattner231308c2005-09-27 04:50:03 +00001580 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001581 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00001582 return GV->hasInitializer() &&
1583 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1584 }
Chris Lattner79c11012005-09-26 04:44:35 +00001585 return false;
1586}
1587
Chris Lattner798b4d52005-09-26 06:52:44 +00001588/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1589/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1590/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1591static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1592 ConstantExpr *Addr, unsigned OpNo) {
1593 // Base case of the recursion.
1594 if (OpNo == Addr->getNumOperands()) {
1595 assert(Val->getType() == Init->getType() && "Type mismatch!");
1596 return Val;
1597 }
1598
1599 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1600 std::vector<Constant*> Elts;
1601
1602 // Break up the constant into its elements.
1603 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1604 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1605 Elts.push_back(CS->getOperand(i));
1606 } else if (isa<ConstantAggregateZero>(Init)) {
1607 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1608 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1609 } else if (isa<UndefValue>(Init)) {
1610 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1611 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1612 } else {
1613 assert(0 && "This code is out of sync with "
1614 " ConstantFoldLoadThroughGEPConstantExpr");
1615 }
1616
1617 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00001618 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1619 unsigned Idx = CU->getZExtValue();
1620 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner798b4d52005-09-26 06:52:44 +00001621 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1622
1623 // Return the modified struct.
1624 return ConstantStruct::get(Elts);
1625 } else {
1626 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1627 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1628
1629 // Break up the array into elements.
1630 std::vector<Constant*> Elts;
1631 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1632 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1633 Elts.push_back(CA->getOperand(i));
1634 } else if (isa<ConstantAggregateZero>(Init)) {
1635 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1636 Elts.assign(ATy->getNumElements(), Elt);
1637 } else if (isa<UndefValue>(Init)) {
1638 Constant *Elt = UndefValue::get(ATy->getElementType());
1639 Elts.assign(ATy->getNumElements(), Elt);
1640 } else {
1641 assert(0 && "This code is out of sync with "
1642 " ConstantFoldLoadThroughGEPConstantExpr");
1643 }
1644
Reid Spencerb83eb642006-10-20 07:07:24 +00001645 assert(CI->getZExtValue() < ATy->getNumElements());
1646 Elts[CI->getZExtValue()] =
1647 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00001648 return ConstantArray::get(ATy, Elts);
1649 }
1650}
1651
Chris Lattner79c11012005-09-26 04:44:35 +00001652/// CommitValueTo - We have decided that Addr (which satisfies the predicate
1653/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1654static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00001655 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1656 assert(GV->hasInitializer());
1657 GV->setInitializer(Val);
1658 return;
1659 }
1660
1661 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1662 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1663
1664 Constant *Init = GV->getInitializer();
1665 Init = EvaluateStoreInto(Init, Val, CE, 2);
1666 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00001667}
1668
Chris Lattner562a0552005-09-26 05:16:34 +00001669/// ComputeLoadResult - Return the value that would be computed by a load from
1670/// P after the stores reflected by 'memory' have been performed. If we can't
1671/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001672static Constant *ComputeLoadResult(Constant *P,
1673 const std::map<Constant*, Constant*> &Memory) {
1674 // If this memory location has been recently stored, use the stored value: it
1675 // is the most up-to-date.
1676 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1677 if (I != Memory.end()) return I->second;
1678
1679 // Access it.
1680 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1681 if (GV->hasInitializer())
1682 return GV->getInitializer();
1683 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00001684 }
Chris Lattner798b4d52005-09-26 06:52:44 +00001685
1686 // Handle a constantexpr getelementptr.
1687 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1688 if (CE->getOpcode() == Instruction::GetElementPtr &&
1689 isa<GlobalVariable>(CE->getOperand(0))) {
1690 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1691 if (GV->hasInitializer())
1692 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1693 }
1694
1695 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001696}
1697
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001698/// EvaluateFunction - Evaluate a call to function F, returning true if
1699/// successful, false if we can't evaluate it. ActualArgs contains the formal
1700/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00001701static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001702 const std::vector<Constant*> &ActualArgs,
1703 std::vector<Function*> &CallStack,
1704 std::map<Constant*, Constant*> &MutatedMemory,
1705 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00001706 // Check to see if this function is already executing (recursion). If so,
1707 // bail out. TODO: we might want to accept limited recursion.
1708 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1709 return false;
1710
1711 CallStack.push_back(F);
1712
Chris Lattner79c11012005-09-26 04:44:35 +00001713 /// Values - As we compute SSA register values, we store their contents here.
1714 std::map<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00001715
1716 // Initialize arguments to the incoming values specified.
1717 unsigned ArgNo = 0;
1718 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1719 ++AI, ++ArgNo)
1720 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001721
Chris Lattnercdf98be2005-09-26 04:57:38 +00001722 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1723 /// we can only evaluate any one basic block at most once. This set keeps
1724 /// track of what we have executed so we can detect recursive cases etc.
1725 std::set<BasicBlock*> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00001726
Chris Lattner79c11012005-09-26 04:44:35 +00001727 // CurInst - The current instruction we're evaluating.
1728 BasicBlock::iterator CurInst = F->begin()->begin();
1729
1730 // This is the main evaluation loop.
1731 while (1) {
1732 Constant *InstResult = 0;
1733
1734 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001735 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00001736 Constant *Ptr = getVal(Values, SI->getOperand(1));
1737 if (!isSimpleEnoughPointerToCommit(Ptr))
1738 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00001739 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00001740 Constant *Val = getVal(Values, SI->getOperand(0));
1741 MutatedMemory[Ptr] = Val;
1742 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1743 InstResult = ConstantExpr::get(BO->getOpcode(),
1744 getVal(Values, BO->getOperand(0)),
1745 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001746 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
1747 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
1748 getVal(Values, CI->getOperand(0)),
1749 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00001750 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Chris Lattner9a989f02006-11-30 17:26:08 +00001751 InstResult = ConstantExpr::getCast(CI->getOpcode(),
1752 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00001753 CI->getType());
1754 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1755 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1756 getVal(Values, SI->getOperand(1)),
1757 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00001758 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1759 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00001760 SmallVector<Constant*, 8> GEPOps;
Chris Lattner04de1cf2005-09-26 05:15:37 +00001761 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1762 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
Chris Lattner55eb1c42007-01-31 04:40:53 +00001763 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00001764 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001765 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001766 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1767 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00001768 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00001769 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001770 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00001771 const Type *Ty = AI->getType()->getElementType();
1772 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1773 GlobalValue::InternalLinkage,
1774 UndefValue::get(Ty),
1775 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00001776 InstResult = AllocaTmps.back();
1777 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattner7cd580f2006-07-07 21:37:01 +00001778 // Cannot handle inline asm.
1779 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1780
Chris Lattnercd271422005-09-27 04:45:34 +00001781 // Resolve function pointers.
1782 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1783 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00001784
Chris Lattnercd271422005-09-27 04:45:34 +00001785 std::vector<Constant*> Formals;
1786 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1787 Formals.push_back(getVal(Values, CI->getOperand(i)));
Chris Lattnercd271422005-09-27 04:45:34 +00001788
Reid Spencer5cbf9852007-01-30 20:08:39 +00001789 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00001790 // If this is a function we can constant fold, do it.
Chris Lattner6c1f5652007-01-30 23:14:52 +00001791 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
1792 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00001793 InstResult = C;
1794 } else {
1795 return false;
1796 }
1797 } else {
1798 if (Callee->getFunctionType()->isVarArg())
1799 return false;
1800
1801 Constant *RetVal;
1802
1803 // Execute the call, if successful, use the return value.
1804 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1805 MutatedMemory, AllocaTmps))
1806 return false;
1807 InstResult = RetVal;
1808 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00001809 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00001810 BasicBlock *NewBB = 0;
1811 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1812 if (BI->isUnconditional()) {
1813 NewBB = BI->getSuccessor(0);
1814 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001815 ConstantInt *Cond =
1816 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00001817 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001818
Reid Spencer579dca12007-01-12 04:24:46 +00001819 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00001820 }
1821 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1822 ConstantInt *Val =
1823 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00001824 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00001825 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1826 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001827 if (RI->getNumOperands())
1828 RetVal = getVal(Values, RI->getOperand(0));
1829
1830 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001831 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00001832 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00001833 // invoke, unwind, unreachable.
1834 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00001835 }
1836
1837 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00001838 // executed the new block before. If so, we have a looping function,
1839 // which we cannot evaluate in reasonable time.
Chris Lattnercdf98be2005-09-26 04:57:38 +00001840 if (!ExecutedBlocks.insert(NewBB).second)
Chris Lattnercd271422005-09-27 04:45:34 +00001841 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00001842
1843 // Okay, we have never been in this block before. Check to see if there
1844 // are any PHI nodes. If so, evaluate them with information about where
1845 // we came from.
1846 BasicBlock *OldBB = CurInst->getParent();
1847 CurInst = NewBB->begin();
1848 PHINode *PN;
1849 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1850 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1851
1852 // Do NOT increment CurInst. We know that the terminator had no value.
1853 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00001854 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00001855 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00001856 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00001857 }
1858
1859 if (!CurInst->use_empty())
1860 Values[CurInst] = InstResult;
1861
1862 // Advance program counter.
1863 ++CurInst;
1864 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001865}
1866
1867/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1868/// we can. Return true if we can, false otherwise.
1869static bool EvaluateStaticConstructor(Function *F) {
1870 /// MutatedMemory - For each store we execute, we update this map. Loads
1871 /// check this to get the most up-to-date value. If evaluation is successful,
1872 /// this state is committed to the process.
1873 std::map<Constant*, Constant*> MutatedMemory;
1874
1875 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1876 /// to represent its body. This vector is needed so we can delete the
1877 /// temporary globals when we are done.
1878 std::vector<GlobalVariable*> AllocaTmps;
1879
1880 /// CallStack - This is used to detect recursion. In pathological situations
1881 /// we could hit exponential behavior, but at least there is nothing
1882 /// unbounded.
1883 std::vector<Function*> CallStack;
1884
1885 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00001886 Constant *RetValDummy;
1887 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1888 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001889 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00001890 // We succeeded at evaluation: commit the result.
Bill Wendling0a81aac2006-11-26 10:02:32 +00001891 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
1892 << F->getName() << "' to " << MutatedMemory.size()
1893 << " stores.\n";
Chris Lattnera22fdb02005-09-26 17:07:09 +00001894 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1895 E = MutatedMemory.end(); I != E; ++I)
1896 CommitValueTo(I->second, I->first);
1897 }
Chris Lattner79c11012005-09-26 04:44:35 +00001898
Chris Lattnera22fdb02005-09-26 17:07:09 +00001899 // At this point, we are done interpreting. If we created any 'alloca'
1900 // temporaries, release them now.
1901 while (!AllocaTmps.empty()) {
1902 GlobalVariable *Tmp = AllocaTmps.back();
1903 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001904
Chris Lattnera22fdb02005-09-26 17:07:09 +00001905 // If there are still users of the alloca, the program is doing something
1906 // silly, e.g. storing the address of the alloca somewhere and using it
1907 // later. Since this is undefined, we'll just make it be null.
1908 if (!Tmp->use_empty())
1909 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1910 delete Tmp;
1911 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00001912
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001913 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00001914}
1915
Chris Lattnerdb973e62005-09-26 02:31:18 +00001916
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001917
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001918/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1919/// Return true if anything changed.
1920bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1921 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1922 bool MadeChange = false;
1923 if (Ctors.empty()) return false;
1924
1925 // Loop over global ctors, optimizing them when we can.
1926 for (unsigned i = 0; i != Ctors.size(); ++i) {
1927 Function *F = Ctors[i];
1928 // Found a null terminator in the middle of the list, prune off the rest of
1929 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001930 if (F == 0) {
1931 if (i != Ctors.size()-1) {
1932 Ctors.resize(i+1);
1933 MadeChange = true;
1934 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001935 break;
1936 }
1937
Chris Lattner79c11012005-09-26 04:44:35 +00001938 // We cannot simplify external ctor functions.
1939 if (F->empty()) continue;
1940
1941 // If we can evaluate the ctor at compile time, do.
1942 if (EvaluateStaticConstructor(F)) {
1943 Ctors.erase(Ctors.begin()+i);
1944 MadeChange = true;
1945 --i;
1946 ++NumCtorsEvaluated;
1947 continue;
1948 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001949 }
1950
1951 if (!MadeChange) return false;
1952
Chris Lattnerdb973e62005-09-26 02:31:18 +00001953 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001954 return true;
1955}
1956
1957
Chris Lattner7a90b682004-10-07 04:16:33 +00001958bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00001959 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001960
1961 // Try to find the llvm.globalctors list.
1962 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00001963
Chris Lattner7a90b682004-10-07 04:16:33 +00001964 bool LocalChange = true;
1965 while (LocalChange) {
1966 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001967
1968 // Delete functions that are trivially dead, ccc -> fastcc
1969 LocalChange |= OptimizeFunctions(M);
1970
1971 // Optimize global_ctors list.
1972 if (GlobalCtors)
1973 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1974
1975 // Optimize non-address-taken globals.
1976 LocalChange |= OptimizeGlobalVars(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00001977 Changed |= LocalChange;
1978 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001979
1980 // TODO: Move all global ctors functions to the end of the module for code
1981 // layout.
1982
Chris Lattner079236d2004-02-25 21:34:36 +00001983 return Changed;
1984}