blob: 206ce39903d1157bf77c87fc13711fcdb4ad5059 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Victor Hernandezf006b182009-10-27 20:05:49 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000027#include "llvm/Target/TargetData.h"
Duncan Sands548448a2008-02-18 17:32:13 +000028#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000029#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000032#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000033#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000034#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000035#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000036#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000037#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000038#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000039#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000040using namespace llvm;
41
Chris Lattner86453c52006-12-19 22:09:18 +000042STATISTIC(NumMarked , "Number of globals marked constant");
43STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
44STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
45STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
46STATISTIC(NumDeleted , "Number of globals deleted");
47STATISTIC(NumFnDeleted , "Number of functions deleted");
48STATISTIC(NumGlobUses , "Number of global uses devirtualized");
49STATISTIC(NumLocalized , "Number of globals localized");
50STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
51STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
52STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000053STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000054STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
55STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Chris Lattner079236d2004-02-25 21:34:36 +000056
Chris Lattner86453c52006-12-19 22:09:18 +000057namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000058 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000059 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner30ba5692004-10-11 05:54:41 +000060 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000061 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000062 GlobalOpt() : ModulePass(&ID) {}
Misha Brukmanfd939082005-04-21 23:48:37 +000063
Chris Lattnerb12914b2004-09-20 04:48:05 +000064 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000065
66 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000067 GlobalVariable *FindGlobalCtors(Module &M);
68 bool OptimizeFunctions(Module &M);
69 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000070 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000071 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000072 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000073 };
Chris Lattner079236d2004-02-25 21:34:36 +000074}
75
Dan Gohman844731a2008-05-13 00:00:25 +000076char GlobalOpt::ID = 0;
77static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
78
Chris Lattner7a90b682004-10-07 04:16:33 +000079ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000080
Dan Gohman844731a2008-05-13 00:00:25 +000081namespace {
82
Chris Lattner7a90b682004-10-07 04:16:33 +000083/// GlobalStatus - As we analyze each global, keep track of some information
84/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000085/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000086struct GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000087 /// isLoaded - True if the global is ever loaded. If the global isn't ever
88 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000089 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000090
91 /// StoredType - Keep track of what stores to the global look like.
92 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000093 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000094 /// NotStored - There is no store to this global. It can thus be marked
95 /// constant.
96 NotStored,
97
98 /// isInitializerStored - This global is stored to, but the only thing
99 /// stored is the constant it was initialized with. This is only tracked
100 /// for scalar globals.
101 isInitializerStored,
102
103 /// isStoredOnce - This global is stored to, but only its initializer and
104 /// one other value is ever stored to it. If this global isStoredOnce, we
105 /// track the value stored to it in StoredOnceValue below. This is only
106 /// tracked for scalar globals.
107 isStoredOnce,
108
109 /// isStored - This global is stored to by multiple values or something else
110 /// that we cannot track.
111 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000112 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000113
114 /// StoredOnceValue - If only one value (besides the initializer constant) is
115 /// ever stored to this global, keep track of what value it is.
116 Value *StoredOnceValue;
117
Chris Lattner25de4e52006-11-01 18:03:33 +0000118 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
119 /// null/false. When the first accessing function is noticed, it is recorded.
120 /// When a second different accessing function is noticed,
121 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000122 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000123 bool HasMultipleAccessingFunctions;
124
Chris Lattner25de4e52006-11-01 18:03:33 +0000125 /// HasNonInstructionUser - Set to true if this global has a user that is not
126 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000127 bool HasNonInstructionUser;
128
Chris Lattner25de4e52006-11-01 18:03:33 +0000129 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
130 bool HasPHIUser;
131
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000132 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000133 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner6a93fc02008-01-14 01:32:52 +0000134 HasNonInstructionUser(false), HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000135};
Chris Lattnere47ba742004-10-06 20:57:02 +0000136
Dan Gohman844731a2008-05-13 00:00:25 +0000137}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000138
Jay Foade3acf152009-06-09 21:37:11 +0000139// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
140// by constants itself. Note that constants cannot be cyclic, so this test is
141// pretty easy to implement recursively.
142//
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000143static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000144 if (isa<GlobalValue>(C)) return false;
145
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000146 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
147 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000148 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000149 } else
150 return false;
151 return true;
152}
153
154
Chris Lattner7a90b682004-10-07 04:16:33 +0000155/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
156/// structure. If the global has its address taken, return true to indicate we
157/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000158///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000159static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
160 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
161 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
162 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000163 GS.HasNonInstructionUser = true;
164
Chris Lattner7a90b682004-10-07 04:16:33 +0000165 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Chris Lattner670c8892004-10-08 17:32:09 +0000166
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000167 } else if (const Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000168 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000169 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000170 if (GS.AccessingFunction == 0)
171 GS.AccessingFunction = F;
172 else if (GS.AccessingFunction != F)
173 GS.HasMultipleAccessingFunctions = true;
174 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000175 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000176 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000177 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000178 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000179 // Don't allow a store OF the address, only stores TO the address.
180 if (SI->getOperand(0) == V) return true;
181
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000182 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
183
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000184 // If this is a direct store to the global (i.e., the global is a scalar
185 // value, not an aggregate), keep more specific information about
186 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000187 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000188 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000189 Value *StoredVal = SI->getOperand(0);
190 if (StoredVal == GV->getInitializer()) {
191 if (GS.StoredType < GlobalStatus::isInitializerStored)
192 GS.StoredType = GlobalStatus::isInitializerStored;
193 } else if (isa<LoadInst>(StoredVal) &&
194 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000195 if (GS.StoredType < GlobalStatus::isInitializerStored)
196 GS.StoredType = GlobalStatus::isInitializerStored;
197 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
198 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000199 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000200 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000201 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000202 // noop.
203 } else {
204 GS.StoredType = GlobalStatus::isStored;
205 }
206 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000207 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000208 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000209 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000210 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000211 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000212 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000214 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000215 // PHI nodes we can check just like select or GEP instructions, but we
216 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000217 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000218 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000219 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000220 } else if (isa<CmpInst>(I)) {
Chris Lattner8e108442009-03-08 03:37:35 +0000221 } else if (isa<MemTransferInst>(I)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000222 if (I->getOperand(1) == V)
223 GS.StoredType = GlobalStatus::isStored;
224 if (I->getOperand(2) == V)
225 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000226 } else if (isa<MemSetInst>(I)) {
227 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
228 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000229 } else {
230 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000231 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000232 } else if (const Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000233 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000234 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000235 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000236 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000237 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000238 GS.HasNonInstructionUser = true;
239 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000240 return true;
241 }
242
243 return false;
244}
245
Chris Lattner7b550cc2009-11-06 04:27:31 +0000246static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
Chris Lattner670c8892004-10-08 17:32:09 +0000247 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
248 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000249 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000250
Chris Lattner670c8892004-10-08 17:32:09 +0000251 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
252 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
253 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
254 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000255 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000256 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000257 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000258 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
259 if (IdxV < STy->getNumElements())
Owen Andersona7235ea2009-07-31 20:28:14 +0000260 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000261 } else if (const SequentialType *STy =
262 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000263 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000264 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000265 } else if (isa<UndefValue>(Agg)) {
266 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
267 if (IdxV < STy->getNumElements())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000268 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000269 } else if (const SequentialType *STy =
270 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000271 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000272 }
Chris Lattner670c8892004-10-08 17:32:09 +0000273 }
274 return 0;
275}
Chris Lattner7a90b682004-10-07 04:16:33 +0000276
Chris Lattner7a90b682004-10-07 04:16:33 +0000277
Chris Lattnere47ba742004-10-06 20:57:02 +0000278/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
279/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000280/// quick scan over the use list to clean up the easy and obvious cruft. This
281/// returns true if it made a change.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000282static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000283 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000284 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
285 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000286
Chris Lattner7a90b682004-10-07 04:16:33 +0000287 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000288 if (Init) {
289 // Replace the load with the initializer.
290 LI->replaceAllUsesWith(Init);
291 LI->eraseFromParent();
292 Changed = true;
293 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000294 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000295 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000296 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000297 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000298 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
299 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000300 Constant *SubInit = 0;
301 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000302 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000303 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000304 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000305 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000306 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000307 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000308 }
309
310 if (CE->use_empty()) {
311 CE->destroyConstant();
312 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000313 }
314 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000315 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
316 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
317 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000318 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000319 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
320 ConstantExpr *CE =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000321 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000322 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000323 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000324 }
Chris Lattner7b550cc2009-11-06 04:27:31 +0000325 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000326
Chris Lattner031955d2004-10-10 16:43:46 +0000327 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000328 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000329 Changed = true;
330 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000331 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
332 if (MI->getRawDest() == V) {
333 MI->eraseFromParent();
334 Changed = true;
335 }
336
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000337 } else if (Constant *C = dyn_cast<Constant>(U)) {
338 // If we have a chain of dead constantexprs or other things dangling from
339 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000340 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000341 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000342 // This could have invalidated UI, start over from scratch.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000343 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000344 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000345 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000346 }
347 }
Chris Lattner031955d2004-10-10 16:43:46 +0000348 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000349}
350
Chris Lattner941db492008-01-14 02:09:12 +0000351/// isSafeSROAElementUse - Return true if the specified instruction is a safe
352/// user of a derived expression from a global that we want to SROA.
353static bool isSafeSROAElementUse(Value *V) {
354 // We might have a dead and dangling constant hanging off of here.
355 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000356 return SafeToDestroyConstant(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000357
Chris Lattner941db492008-01-14 02:09:12 +0000358 Instruction *I = dyn_cast<Instruction>(V);
359 if (!I) return false;
360
361 // Loads are ok.
362 if (isa<LoadInst>(I)) return true;
363
364 // Stores *to* the pointer are ok.
365 if (StoreInst *SI = dyn_cast<StoreInst>(I))
366 return SI->getOperand(0) != V;
367
368 // Otherwise, it must be a GEP.
369 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
370 if (GEPI == 0) return false;
371
372 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
373 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
374 return false;
375
376 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
377 I != E; ++I)
378 if (!isSafeSROAElementUse(*I))
379 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000380 return true;
381}
382
Chris Lattner941db492008-01-14 02:09:12 +0000383
384/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
385/// Look at it and its uses and decide whether it is safe to SROA this global.
386///
387static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
388 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
389 if (!isa<GetElementPtrInst>(U) &&
390 (!isa<ConstantExpr>(U) ||
391 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
392 return false;
393
394 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
395 // don't like < 3 operand CE's, and we don't like non-constant integer
396 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
397 // value of C.
398 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
399 !cast<Constant>(U->getOperand(1))->isNullValue() ||
400 !isa<ConstantInt>(U->getOperand(2)))
401 return false;
402
403 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
404 ++GEPI; // Skip over the pointer index.
405
406 // If this is a use of an array allocation, do a bit more checking for sanity.
407 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
408 uint64_t NumElements = AT->getNumElements();
409 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
410
411 // Check to make sure that index falls within the array. If not,
412 // something funny is going on, so we won't do the optimization.
413 //
414 if (Idx->getZExtValue() >= NumElements)
415 return false;
416
417 // We cannot scalar repl this level of the array unless any array
418 // sub-indices are in-range constants. In particular, consider:
419 // A[0][i]. We cannot know that the user isn't doing invalid things like
420 // allowing i to index an out-of-range subscript that accesses A[1].
421 //
422 // Scalar replacing *just* the outer index of the array is probably not
423 // going to be a win anyway, so just give up.
424 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000425 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000426 ++GEPI) {
427 uint64_t NumElements;
428 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
429 NumElements = SubArrayTy->getNumElements();
Dan Gohman6874a2a2009-08-18 14:58:19 +0000430 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
431 NumElements = SubVectorTy->getNumElements();
432 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000433 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000434 "Indexed GEP type is not array, vector, or struct!");
435 continue;
436 }
Chris Lattner941db492008-01-14 02:09:12 +0000437
438 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
439 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
440 return false;
441 }
442 }
443
444 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
445 if (!isSafeSROAElementUse(*I))
446 return false;
447 return true;
448}
449
450/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
451/// is safe for us to perform this transformation.
452///
453static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
454 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
455 UI != E; ++UI) {
456 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
457 return false;
458 }
459 return true;
460}
461
462
Chris Lattner670c8892004-10-08 17:32:09 +0000463/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
464/// variable. This opens the door for other optimizations by exposing the
465/// behavior of the program in a more fine-grained way. We have determined that
466/// this transformation is safe already. We return the first global variable we
467/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000468static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000469 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000470 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000471 return 0;
472
Rafael Espindolabb46f522009-01-15 20:18:42 +0000473 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000474 Constant *Init = GV->getInitializer();
475 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000476
Chris Lattner670c8892004-10-08 17:32:09 +0000477 std::vector<GlobalVariable*> NewGlobals;
478 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
479
Chris Lattner998182b2008-04-26 07:40:11 +0000480 // Get the alignment of the global, either explicit or target-specific.
481 unsigned StartAlignment = GV->getAlignment();
482 if (StartAlignment == 0)
483 StartAlignment = TD.getABITypeAlignment(GV->getType());
484
Chris Lattner670c8892004-10-08 17:32:09 +0000485 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
486 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000487 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000488 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
489 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000490 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000491 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000492 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000493 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000494 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000495 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000496 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000497 Globals.insert(GV, NGV);
498 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000499
500 // Calculate the known alignment of the field. If the original aggregate
501 // had 256 byte alignment for example, something might depend on that:
502 // propagate info to each field.
503 uint64_t FieldOffset = Layout.getElementOffset(i);
504 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
505 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
506 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000507 }
508 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
509 unsigned NumElements = 0;
510 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
511 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000512 else
Chris Lattner998182b2008-04-26 07:40:11 +0000513 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000514
Chris Lattner1f21ef12005-02-23 16:53:04 +0000515 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000516 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000517 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000518
Duncan Sands777d2302009-05-09 07:06:46 +0000519 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000520 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000521 for (unsigned i = 0, e = NumElements; i != e; ++i) {
522 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000523 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000524 assert(In && "Couldn't get element of initializer?");
525
Chris Lattner7b550cc2009-11-06 04:27:31 +0000526 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000527 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000528 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000529 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000530 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000531 Globals.insert(GV, NGV);
532 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000533
534 // Calculate the known alignment of the field. If the original aggregate
535 // had 256 byte alignment for example, something might depend on that:
536 // propagate info to each field.
537 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
538 if (NewAlign > EltAlign)
539 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000540 }
541 }
542
543 if (NewGlobals.empty())
544 return 0;
Chris Lattnerc6a669b2010-02-26 23:35:25 +0000545
David Greene3215b0e2010-01-05 01:28:05 +0000546 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000547
Chris Lattner7b550cc2009-11-06 04:27:31 +0000548 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000549
550 // Loop over all of the uses of the global, replacing the constantexpr geps,
551 // with smaller constantexpr geps or direct references.
552 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000553 User *GEP = GV->use_back();
554 assert(((isa<ConstantExpr>(GEP) &&
555 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
556 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000557
Chris Lattner670c8892004-10-08 17:32:09 +0000558 // Ignore the 1th operand, which has to be zero or else the program is quite
559 // broken (undefined). Get the 2nd operand, which is the structure or array
560 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000561 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000562 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
563
Chris Lattner30ba5692004-10-11 05:54:41 +0000564 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000565
566 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000567 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000569 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000570 Idxs.push_back(NullInt);
571 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
572 Idxs.push_back(CE->getOperand(i));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000573 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000574 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000575 } else {
576 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000577 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000578 Idxs.push_back(NullInt);
579 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
580 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000581 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000582 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000583 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000584 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000585 GEP->replaceAllUsesWith(NewPtr);
586
587 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000588 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000589 else
590 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000591 }
592
Chris Lattnere40e2d12004-10-08 20:25:55 +0000593 // Delete the old global, now that it is dead.
594 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000595 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000596
597 // Loop over the new globals array deleting any globals that are obviously
598 // dead. This can arise due to scalarization of a structure or an array that
599 // has elements that are dead.
600 unsigned FirstGlobal = 0;
601 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
602 if (NewGlobals[i]->use_empty()) {
603 Globals.erase(NewGlobals[i]);
604 if (FirstGlobal == i) ++FirstGlobal;
605 }
606
607 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000608}
609
Chris Lattner9b34a612004-10-09 21:48:45 +0000610/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000611/// value will trap if the value is dynamically null. PHIs keeps track of any
612/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000613static bool AllUsesOfValueWillTrapIfNull(const Value *V,
614 SmallPtrSet<const PHINode*, 8> &PHIs) {
615 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000616 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000617 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000618
619 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000620 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000621 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000622 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000623 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000624 return false; // Storing the value.
625 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000626 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000627 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000628 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000629 return false; // Not calling the ptr
630 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000631 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000632 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000633 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000634 return false; // Not calling the ptr
635 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000636 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000637 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000638 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000639 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000640 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000641 // If we've already seen this phi node, ignore it, it has already been
642 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000643 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
644 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000645 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000646 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000647 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000648 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000649 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000650 return false;
651 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000652 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000653 return true;
654}
655
656/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000657/// from GV will trap if the loaded value is null. Note that this also permits
658/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000659static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
660 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000661 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000662 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000663
Gabor Greif6ce02b52010-04-06 19:24:18 +0000664 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
665 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000666 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000667 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000668 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000669 // Ignore stores to the global.
670 } else {
671 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000672 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000673 return false;
674 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000675 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000676 return true;
677}
678
Chris Lattner7b550cc2009-11-06 04:27:31 +0000679static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000680 bool Changed = false;
681 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
682 Instruction *I = cast<Instruction>(*UI++);
683 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
684 LI->setOperand(0, NewV);
685 Changed = true;
686 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
687 if (SI->getOperand(1) == V) {
688 SI->setOperand(1, NewV);
689 Changed = true;
690 }
691 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000692 CallSite CS(I);
693 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000694 // Calling through the pointer! Turn into a direct call, but be careful
695 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000696 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000697 Changed = true;
698 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000699 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
700 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000701 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000702 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000703 }
704
705 if (PassedAsArg) {
706 // Being passed as an argument also. Be careful to not invalidate UI!
707 UI = V->use_begin();
708 }
709 }
710 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
711 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000712 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000713 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000714 if (CI->use_empty()) {
715 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000716 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000717 }
718 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
719 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000720 SmallVector<Constant*, 8> Idxs;
721 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000722 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
723 i != e; ++i)
724 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000725 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000726 else
727 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000728 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000729 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000730 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Chris Lattner7b550cc2009-11-06 04:27:31 +0000731 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000732 if (GEPI->use_empty()) {
733 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000734 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000735 }
736 }
737 }
738
739 return Changed;
740}
741
742
743/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
744/// value stored into it. If there are uses of the loaded value that would trap
745/// if the loaded value is dynamically null, then we know that they cannot be
746/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000747static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000748 bool Changed = false;
749
Chris Lattner92c6bd22009-01-14 00:12:58 +0000750 // Keep track of whether we are able to remove all the uses of the global
751 // other than the store that defines it.
752 bool AllNonStoreUsesGone = true;
753
Chris Lattner708148e2004-10-10 23:14:11 +0000754 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000755 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
756 User *GlobalUser = *GUI++;
757 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000758 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000759 // If we were able to delete all uses of the loads
760 if (LI->use_empty()) {
761 LI->eraseFromParent();
762 Changed = true;
763 } else {
764 AllNonStoreUsesGone = false;
765 }
766 } else if (isa<StoreInst>(GlobalUser)) {
767 // Ignore the store that stores "LV" to the global.
768 assert(GlobalUser->getOperand(1) == GV &&
769 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000770 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000771 AllNonStoreUsesGone = false;
772
773 // If we get here we could have other crazy uses that are transitively
774 // loaded.
775 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
776 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000777 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000778 }
Chris Lattner708148e2004-10-10 23:14:11 +0000779
780 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000781 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000782 ++NumGlobUses;
783 }
784
Chris Lattner708148e2004-10-10 23:14:11 +0000785 // If we nuked all of the loads, then none of the stores are needed either,
786 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000787 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000788 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000789 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000790 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000791 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000792 ++NumDeleted;
793 }
794 Changed = true;
795 }
796 return Changed;
797}
798
Chris Lattner30ba5692004-10-11 05:54:41 +0000799/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
800/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000801static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000802 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
803 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chris Lattner7b550cc2009-11-06 04:27:31 +0000804 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000805 I->replaceAllUsesWith(NewC);
806
Chris Lattnerd514d822005-02-01 01:23:31 +0000807 // Advance UI to the next non-I use to avoid invalidating it!
808 // Instructions could multiply use V.
809 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000810 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000811 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000812 }
813}
814
815/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
816/// variable, and transforms the program as if it always contained the result of
817/// the specified malloc. Because it is always the result of the specified
818/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000819/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000820static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000821 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000822 const Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000823 ConstantInt *NElements,
Victor Hernandez83d63912009-09-18 22:35:49 +0000824 TargetData* TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000825 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Victor Hernandez83d63912009-09-18 22:35:49 +0000826
Chris Lattnera6874652010-02-25 22:33:52 +0000827 const Type *GlobalType;
828 if (NElements->getZExtValue() == 1)
829 GlobalType = AllocTy;
830 else
831 // If we have an array allocation, the global variable is of an array.
832 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000833
834 // Create the new global variable. The contents of the malloc'd memory is
835 // undefined, so initialize with an undef value.
Victor Hernandez83d63912009-09-18 22:35:49 +0000836 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000837 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000838 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000839 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000840 GV->getName()+".body",
841 GV,
842 GV->isThreadLocal());
843
Chris Lattnera6874652010-02-25 22:33:52 +0000844 // If there are bitcast users of the malloc (which is typical, usually we have
845 // a malloc + bitcast) then replace them with uses of the new global. Update
846 // other users to use the global as well.
847 BitCastInst *TheBC = 0;
848 while (!CI->use_empty()) {
849 Instruction *User = cast<Instruction>(CI->use_back());
850 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
851 if (BCI->getType() == NewGV->getType()) {
852 BCI->replaceAllUsesWith(NewGV);
853 BCI->eraseFromParent();
854 } else {
855 BCI->setOperand(0, NewGV);
856 }
857 } else {
858 if (TheBC == 0)
859 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
860 User->replaceUsesOfWith(CI, TheBC);
861 }
862 }
863
Victor Hernandez83d63912009-09-18 22:35:49 +0000864 Constant *RepValue = NewGV;
865 if (NewGV->getType() != GV->getType()->getElementType())
866 RepValue = ConstantExpr::getBitCast(RepValue,
867 GV->getType()->getElementType());
868
869 // If there is a comparison against null, we will insert a global bool to
870 // keep track of whether the global was initialized yet or not.
871 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000872 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000873 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000874 ConstantInt::getFalse(GV->getContext()),
875 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000876 bool InitBoolUsed = false;
877
878 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000879 while (!GV->use_empty()) {
880 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000881 // The global is initialized when the store to it occurs.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000882 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000883 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000884 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000885 }
Chris Lattnera6874652010-02-25 22:33:52 +0000886
887 LoadInst *LI = cast<LoadInst>(GV->use_back());
888 while (!LI->use_empty()) {
889 Use &LoadUse = LI->use_begin().getUse();
890 if (!isa<ICmpInst>(LoadUse.getUser())) {
891 LoadUse = RepValue;
892 continue;
893 }
894
895 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
896 // Replace the cmp X, 0 with a use of the bool value.
897 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
898 InitBoolUsed = true;
899 switch (ICI->getPredicate()) {
900 default: llvm_unreachable("Unknown ICmp Predicate!");
901 case ICmpInst::ICMP_ULT:
902 case ICmpInst::ICMP_SLT: // X < null -> always false
903 LV = ConstantInt::getFalse(GV->getContext());
904 break;
905 case ICmpInst::ICMP_ULE:
906 case ICmpInst::ICMP_SLE:
907 case ICmpInst::ICMP_EQ:
908 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
909 break;
910 case ICmpInst::ICMP_NE:
911 case ICmpInst::ICMP_UGE:
912 case ICmpInst::ICMP_SGE:
913 case ICmpInst::ICMP_UGT:
914 case ICmpInst::ICMP_SGT:
915 break; // no change.
916 }
917 ICI->replaceAllUsesWith(LV);
918 ICI->eraseFromParent();
919 }
920 LI->eraseFromParent();
921 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000922
923 // If the initialization boolean was used, insert it, otherwise delete it.
924 if (!InitBoolUsed) {
925 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000926 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000927 delete InitBool;
928 } else
929 GV->getParent()->getGlobalList().insert(GV, InitBool);
930
Chris Lattnera6874652010-02-25 22:33:52 +0000931 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000932 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000933 CI->eraseFromParent();
934
935 // To further other optimizations, loop over all users of NewGV and try to
936 // constant prop them. This will promote GEP instructions with constant
937 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000938 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000939 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000940 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000941
942 return NewGV;
943}
944
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000945/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
946/// to make sure that there are no complex uses of V. We permit simple things
947/// like dereferencing the pointer, but not storing through the address, unless
948/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000949static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
950 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000951 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000952 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000953 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000954 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000955
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000956 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
957 continue; // Fine, ignore.
958 }
959
Gabor Greif0b520db2010-04-06 18:58:22 +0000960 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000961 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
962 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000963 continue; // Otherwise, storing through it, or storing into GV... fine.
964 }
965
966 if (isa<GetElementPtrInst>(Inst)) {
967 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000968 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000969 continue;
970 }
971
Gabor Greif0b520db2010-04-06 18:58:22 +0000972 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000973 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
974 // cycles.
975 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000976 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
977 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000978 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000979 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000980
Gabor Greif0b520db2010-04-06 18:58:22 +0000981 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000982 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
983 return false;
984 continue;
985 }
986
987 return false;
988 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000989 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000990}
991
Chris Lattner86395032006-09-30 23:32:09 +0000992/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
993/// somewhere. Transform all uses of the allocation into loads from the
994/// global and uses of the resultant pointer. Further, delete the store into
995/// GV. This assumes that these value pass the
996/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
997static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
998 GlobalVariable *GV) {
999 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001000 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1001 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001002 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1003 // If this is the store of the allocation into the global, remove it.
1004 if (SI->getOperand(1) == GV) {
1005 SI->eraseFromParent();
1006 continue;
1007 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001008 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1009 // Insert the load in the corresponding predecessor, not right before the
1010 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001011 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001012 } else if (isa<BitCastInst>(U)) {
1013 // Must be bitcast between the malloc and store to initialize the global.
1014 ReplaceUsesOfMallocWithGlobal(U, GV);
1015 U->eraseFromParent();
1016 continue;
1017 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1018 // If this is a "GEP bitcast" and the user is a store to the global, then
1019 // just process it as a bitcast.
1020 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1021 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1022 if (SI->getOperand(1) == GV) {
1023 // Must be bitcast GEP between the malloc and store to initialize
1024 // the global.
1025 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1026 GEPI->eraseFromParent();
1027 continue;
1028 }
Chris Lattner86395032006-09-30 23:32:09 +00001029 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001030
Chris Lattner86395032006-09-30 23:32:09 +00001031 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001032 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001033 U->replaceUsesOfWith(Alloc, NL);
1034 }
1035}
1036
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001037/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1038/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1039/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001040static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1041 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1042 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001043 // We permit two users of the load: setcc comparing against the null
1044 // pointer, and a getelementptr of a specific form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001045 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1046 const Instruction *User = cast<Instruction>(*UI);
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001047
1048 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001049 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001050 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1051 return false;
1052 continue;
1053 }
1054
1055 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001056 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001057 // Must index into the array and into the struct.
1058 if (GEPI->getNumOperands() < 3)
1059 return false;
1060
1061 // Otherwise the GEP is ok.
1062 continue;
1063 }
1064
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001065 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001066 if (!LoadUsingPHIsPerLoad.insert(PN))
1067 // This means some phi nodes are dependent on each other.
1068 // Avoid infinite looping!
1069 return false;
1070 if (!LoadUsingPHIs.insert(PN))
1071 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001072 continue;
1073
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001074 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001075 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1076 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001077 return false;
1078
1079 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001080 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001081
1082 // Otherwise we don't know what this is, not ok.
1083 return false;
1084 }
1085
1086 return true;
1087}
1088
1089
1090/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1091/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001092static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001093 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001094 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1095 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1096 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001097 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001098 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001099 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1100 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001101 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001102 LoadUsingPHIsPerLoad.clear();
1103 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001104
1105 // If we reach here, we know that all uses of the loads and transitive uses
1106 // (through PHI nodes) are simple enough to transform. However, we don't know
1107 // that all inputs the to the PHI nodes are in the same equivalence sets.
1108 // Check to verify that all operands of the PHIs are either PHIS that can be
1109 // transformed, loads from GV, or MI itself.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001110 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin(),
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001111 E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001112 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001113 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1114 Value *InVal = PN->getIncomingValue(op);
1115
1116 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001117 if (InVal == StoredVal) continue;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001118
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001119 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001120 // One of the PHIs in our set is (optimistically) ok.
1121 if (LoadUsingPHIs.count(InPN))
1122 continue;
1123 return false;
1124 }
1125
1126 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001127 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001128 if (LI->getOperand(0) == GV)
1129 continue;
1130
1131 // UNDEF? NULL?
1132
1133 // Anything else is rejected.
1134 return false;
1135 }
1136 }
1137
Chris Lattner86395032006-09-30 23:32:09 +00001138 return true;
1139}
1140
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001141static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1142 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001143 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001144 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1145
1146 if (FieldNo >= FieldVals.size())
1147 FieldVals.resize(FieldNo+1);
1148
1149 // If we already have this value, just reuse the previously scalarized
1150 // version.
1151 if (Value *FieldVal = FieldVals[FieldNo])
1152 return FieldVal;
1153
1154 // Depending on what instruction this is, we have several cases.
1155 Value *Result;
1156 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1157 // This is a scalarized version of the load from the global. Just create
1158 // a new Load of the scalarized global.
1159 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1160 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001161 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001162 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001163 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1164 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1165 // field.
1166 const StructType *ST =
1167 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1168
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001169 Result =
Owen Andersondebcb012009-07-29 22:17:13 +00001170 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001171 PN->getName()+".f"+Twine(FieldNo), PN);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001172 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1173 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001174 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001175 Result = 0;
1176 }
1177
1178 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001179}
1180
Chris Lattner330245e2007-09-13 17:29:05 +00001181/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1182/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001183static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1184 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001185 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001186 // If this is a comparison against null, handle it.
1187 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1188 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1189 // If we have a setcc of the loaded pointer, we can use a setcc of any
1190 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001191 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001192 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner330245e2007-09-13 17:29:05 +00001193
Owen Anderson333c4002009-07-09 23:48:35 +00001194 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Owen Andersona7235ea2009-07-31 20:28:14 +00001195 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001196 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001197 SCI->replaceAllUsesWith(New);
1198 SCI->eraseFromParent();
1199 return;
1200 }
1201
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001202 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001203 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1204 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1205 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001206
Chris Lattnera637a8b2007-09-13 18:00:31 +00001207 // Load the pointer for this field.
1208 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001209 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001210 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001211
1212 // Create the new GEP idx vector.
1213 SmallVector<Value*, 8> GEPIdx;
1214 GEPIdx.push_back(GEPI->getOperand(1));
1215 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1216
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001217 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1218 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001219 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001220 GEPI->replaceAllUsesWith(NGEPI);
1221 GEPI->eraseFromParent();
1222 return;
1223 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001224
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001225 // Recursively transform the users of PHI nodes. This will lazily create the
1226 // PHIs that are needed for individual elements. Keep track of what PHIs we
1227 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1228 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1229 // already been seen first by another load, so its uses have already been
1230 // processed.
1231 PHINode *PN = cast<PHINode>(LoadUser);
1232 bool Inserted;
1233 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1234 tie(InsertPos, Inserted) =
1235 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1236 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001237
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001238 // If this is the first time we've seen this PHI, recursively process all
1239 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001240 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1241 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001242 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001243 }
Chris Lattner330245e2007-09-13 17:29:05 +00001244}
1245
Chris Lattner86395032006-09-30 23:32:09 +00001246/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1247/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1248/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001249/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001250static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001251 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001252 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001253 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001254 UI != E; ) {
1255 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001256 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001257 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001258
1259 if (Load->use_empty()) {
1260 Load->eraseFromParent();
1261 InsertedScalarizedValues.erase(Load);
1262 }
Chris Lattner86395032006-09-30 23:32:09 +00001263}
1264
Victor Hernandez83d63912009-09-18 22:35:49 +00001265/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1266/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001267static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1268 Value* NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001269 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Victor Hernandez83d63912009-09-18 22:35:49 +00001270 const Type* MAT = getMallocAllocatedType(CI);
1271 const StructType *STy = cast<StructType>(MAT);
1272
1273 // There is guaranteed to be at least one use of the malloc (storing
1274 // it into GV). If there are other uses, change them to be uses of
1275 // the global to simplify later code. This also deletes the store
1276 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001277 ReplaceUsesOfMallocWithGlobal(CI, GV);
1278
Victor Hernandez83d63912009-09-18 22:35:49 +00001279 // Okay, at this point, there are no users of the malloc. Insert N
1280 // new mallocs at the same place as CI, and N globals.
1281 std::vector<Value*> FieldGlobals;
1282 std::vector<Value*> FieldMallocs;
1283
1284 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1285 const Type *FieldTy = STy->getElementType(FieldNo);
1286 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1287
1288 GlobalVariable *NGV =
1289 new GlobalVariable(*GV->getParent(),
1290 PFieldTy, false, GlobalValue::InternalLinkage,
1291 Constant::getNullValue(PFieldTy),
1292 GV->getName() + ".f" + Twine(FieldNo), GV,
1293 GV->isThreadLocal());
1294 FieldGlobals.push_back(NGV);
1295
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001296 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Victor Hernandez631f3c02009-11-07 00:41:19 +00001297 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001298 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez631f3c02009-11-07 00:41:19 +00001299 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001300 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1301 ConstantInt::get(IntPtrTy, TypeSize),
1302 NElems,
1303 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001304 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001305 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001306 }
1307
1308 // The tricky aspect of this transformation is handling the case when malloc
1309 // fails. In the original code, malloc failing would set the result pointer
1310 // of malloc to null. In this case, some mallocs could succeed and others
1311 // could fail. As such, we emit code that looks like this:
1312 // F0 = malloc(field0)
1313 // F1 = malloc(field1)
1314 // F2 = malloc(field2)
1315 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1316 // if (F0) { free(F0); F0 = 0; }
1317 // if (F1) { free(F1); F1 = 0; }
1318 // if (F2) { free(F2); F2 = 0; }
1319 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001320 // The malloc can also fail if its argument is too large.
1321 Constant *ConstantZero = ConstantInt::get(CI->getOperand(1)->getType(), 0);
1322 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getOperand(1),
1323 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001324 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001325 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1326 Constant::getNullValue(FieldMallocs[i]->getType()),
1327 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001328 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001329 }
1330
1331 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001332 BasicBlock *OrigBB = CI->getParent();
1333 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Victor Hernandez83d63912009-09-18 22:35:49 +00001334
1335 // Create the block to check the first condition. Put all these blocks at the
1336 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001337 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1338 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001339 OrigBB->getParent());
1340
1341 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1342 // branch on RunningOr.
1343 OrigBB->getTerminator()->eraseFromParent();
1344 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1345
1346 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1347 // pointer, because some may be null while others are not.
1348 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1349 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1350 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1351 Constant::getNullValue(GVVal->getType()),
1352 "tmp");
Chris Lattner7b550cc2009-11-06 04:27:31 +00001353 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001354 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001355 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001356 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001357 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1358 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001359
1360 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001361 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001362 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1363 FreeBlock);
1364 BranchInst::Create(NextBlock, FreeBlock);
1365
1366 NullPtrBlock = NextBlock;
1367 }
1368
1369 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001370
1371 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001372 CI->eraseFromParent();
1373
1374 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1375 /// update all uses of the load, keep track of what scalarized loads are
1376 /// inserted for a given load.
1377 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1378 InsertedScalarizedValues[GV] = FieldGlobals;
1379
1380 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1381
1382 // Okay, the malloc site is completely handled. All of the uses of GV are now
1383 // loads, and all uses of those loads are simple. Rewrite them to use loads
1384 // of the per-field globals instead.
1385 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1386 Instruction *User = cast<Instruction>(*UI++);
1387
1388 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001389 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001390 continue;
1391 }
1392
1393 // Must be a store of null.
1394 StoreInst *SI = cast<StoreInst>(User);
1395 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1396 "Unexpected heap-sra user!");
1397
1398 // Insert a store of null into each global.
1399 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1400 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1401 Constant *Null = Constant::getNullValue(PT->getElementType());
1402 new StoreInst(Null, FieldGlobals[i], SI);
1403 }
1404 // Erase the original store.
1405 SI->eraseFromParent();
1406 }
1407
1408 // While we have PHIs that are interesting to rewrite, do it.
1409 while (!PHIsToRewrite.empty()) {
1410 PHINode *PN = PHIsToRewrite.back().first;
1411 unsigned FieldNo = PHIsToRewrite.back().second;
1412 PHIsToRewrite.pop_back();
1413 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1414 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1415
1416 // Add all the incoming values. This can materialize more phis.
1417 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1418 Value *InVal = PN->getIncomingValue(i);
1419 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001420 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001421 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1422 }
1423 }
1424
1425 // Drop all inter-phi links and any loads that made it this far.
1426 for (DenseMap<Value*, std::vector<Value*> >::iterator
1427 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1428 I != E; ++I) {
1429 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1430 PN->dropAllReferences();
1431 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1432 LI->dropAllReferences();
1433 }
1434
1435 // Delete all the phis and loads now that inter-references are dead.
1436 for (DenseMap<Value*, std::vector<Value*> >::iterator
1437 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1438 I != E; ++I) {
1439 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1440 PN->eraseFromParent();
1441 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1442 LI->eraseFromParent();
1443 }
1444
1445 // The old global is now dead, remove it.
1446 GV->eraseFromParent();
1447
1448 ++NumHeapSRA;
1449 return cast<GlobalVariable>(FieldGlobals[0]);
1450}
1451
Chris Lattnere61d0a62008-12-15 21:02:25 +00001452/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1453/// pointer global variable with a single value stored it that is a malloc or
1454/// cast of malloc.
1455static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001456 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001457 const Type *AllocTy,
Victor Hernandez83d63912009-09-18 22:35:49 +00001458 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001459 TargetData *TD) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001460 // If this is a malloc of an abstract type, don't touch it.
1461 if (!AllocTy->isSized())
1462 return false;
1463
1464 // We can't optimize this global unless all uses of it are *known* to be
1465 // of the malloc value, not of the null initializer value (consider a use
1466 // that compares the global's value against zero to see if the malloc has
1467 // been reached). To do this, we check to see if all uses of the global
1468 // would trap if the global were null: this proves that they must all
1469 // happen after the malloc.
1470 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1471 return false;
1472
1473 // We can't optimize this if the malloc itself is used in a complex way,
1474 // for example, being stored into multiple globals. This allows the
1475 // malloc to be stored into the specified global, loaded setcc'd, and
1476 // GEP'd. These are all things we could transform to using the global
1477 // for.
1478 {
Gabor Greif0b520db2010-04-06 18:58:22 +00001479 SmallPtrSet<const PHINode*, 8> PHIs;
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001480 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
Victor Hernandez83d63912009-09-18 22:35:49 +00001481 return false;
1482 }
1483
1484 // If we have a global that is only initialized with a fixed size malloc,
1485 // transform the program to use global memory instead of malloc'd memory.
1486 // This eliminates dynamic allocation, avoids an indirection accessing the
1487 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001488 // We cannot optimize the malloc if we cannot determine malloc array size.
Victor Hernandez8e345a12009-11-10 08:32:25 +00001489 if (Value *NElems = getMallocArraySize(CI, TD, true)) {
Victor Hernandez2491ce02009-10-15 20:14:52 +00001490 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1491 // Restrict this transformation to only working on small allocations
1492 // (2048 bytes currently), as we don't want to introduce a 16M global or
1493 // something.
1494 if (TD &&
1495 NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Chris Lattnera6874652010-02-25 22:33:52 +00001496 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
Victor Hernandez2491ce02009-10-15 20:14:52 +00001497 return true;
1498 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001499
Victor Hernandez8db42d22009-10-16 23:12:25 +00001500 // If the allocation is an array of structures, consider transforming this
1501 // into multiple malloc'd arrays, one for each field. This is basically
1502 // SRoA for malloc'd memory.
Victor Hernandez83d63912009-09-18 22:35:49 +00001503
Victor Hernandez8db42d22009-10-16 23:12:25 +00001504 // If this is an allocation of a fixed size array of structs, analyze as a
1505 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Victor Hernandez90f48e72009-10-28 20:18:55 +00001506 if (NElems == ConstantInt::get(CI->getOperand(1)->getType(), 1))
Victor Hernandez8db42d22009-10-16 23:12:25 +00001507 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1508 AllocTy = AT->getElementType();
Victor Hernandez83d63912009-09-18 22:35:49 +00001509
Victor Hernandez8db42d22009-10-16 23:12:25 +00001510 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1511 // This the structure has an unreasonable number of fields, leave it
1512 // alone.
1513 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001514 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001515
Victor Hernandez8db42d22009-10-16 23:12:25 +00001516 // If this is a fixed size array, transform the Malloc to be an alloc of
1517 // structs. malloc [100 x struct],1 -> malloc struct, 100
1518 if (const ArrayType *AT =
1519 dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001520 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1521 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1522 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1523 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1524 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1525 AllocSize, NumElements,
1526 CI->getName());
1527 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1528 CI->replaceAllUsesWith(Cast);
Victor Hernandez8db42d22009-10-16 23:12:25 +00001529 CI->eraseFromParent();
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001530 CI = dyn_cast<BitCastInst>(Malloc) ?
Victor Hernandez631f3c02009-11-07 00:41:19 +00001531 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
Victor Hernandez8db42d22009-10-16 23:12:25 +00001532 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001533
Victor Hernandez8e345a12009-11-10 08:32:25 +00001534 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
Victor Hernandez8db42d22009-10-16 23:12:25 +00001535 return true;
1536 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001537 }
1538 }
1539
1540 return false;
1541}
1542
Chris Lattner9b34a612004-10-09 21:48:45 +00001543// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1544// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001545static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001546 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001547 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001548 // Ignore no-op GEPs and bitcasts.
1549 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001550
Chris Lattner708148e2004-10-10 23:14:11 +00001551 // If we are dealing with a pointer global that is initialized to null and
1552 // only has one (non-null) value stored into it, then we can optimize any
1553 // users of the loaded value (often calls and loads) that would trap if the
1554 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001555 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001556 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001557 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1558 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001559 SOVC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001560 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001561
Chris Lattner708148e2004-10-10 23:14:11 +00001562 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001563 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001564 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001565 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001566 const Type* MallocType = getMallocAllocatedType(CI);
1567 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
1568 GVI, TD))
1569 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001570 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001571 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001572
Chris Lattner9b34a612004-10-09 21:48:45 +00001573 return false;
1574}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001575
Chris Lattner58e44f42008-01-14 01:17:44 +00001576/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1577/// two values ever stored into GV are its initializer and OtherVal. See if we
1578/// can shrink the global into a boolean and select between the two values
1579/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001580static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001581 const Type *GVElType = GV->getType()->getElementType();
1582
1583 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001584 // an FP value, pointer or vector, don't do this optimization because a select
1585 // between them is very expensive and unlikely to lead to later
1586 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1587 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001588 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001589 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001590 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001591 return false;
1592
1593 // Walk the use list of the global seeing if all the uses are load or store.
1594 // If there is anything else, bail out.
1595 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel771281f2009-03-06 01:39:36 +00001596 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattner58e44f42008-01-14 01:17:44 +00001597 return false;
1598
David Greene3215b0e2010-01-05 01:28:05 +00001599 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Chris Lattner58e44f42008-01-14 01:17:44 +00001600
Chris Lattner96a86b22004-12-12 05:53:50 +00001601 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001602 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1603 false,
1604 GlobalValue::InternalLinkage,
1605 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001606 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001607 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001608 GV->getParent()->getGlobalList().insert(GV, NewGV);
1609
1610 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001611 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001612 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001613
1614 // If initialized to zero and storing one into the global, we can use a cast
1615 // instead of a select to synthesize the desired value.
1616 bool IsOneZero = false;
1617 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001618 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001619
1620 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001621 Instruction *UI = cast<Instruction>(GV->use_back());
1622 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001623 // Change the store into a boolean store.
1624 bool StoringOther = SI->getOperand(0) == OtherVal;
1625 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001626 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001627 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001628 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1629 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001630 else {
1631 // Otherwise, we are storing a previously loaded copy. To do this,
1632 // change the copy from copying the original value to just copying the
1633 // bool.
1634 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1635
1636 // If we're already replaced the input, StoredVal will be a cast or
1637 // select instruction. If not, it will be a load of the original
1638 // global.
1639 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1640 assert(LI->getOperand(0) == GV && "Not a copy!");
1641 // Insert a new load, to preserve the saved value.
1642 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1643 } else {
1644 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1645 "This is not a form that we understand!");
1646 StoreVal = StoredVal->getOperand(0);
1647 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1648 }
1649 }
1650 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001651 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001652 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001653 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001654 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001655 Value *NSI;
1656 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001657 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001658 else
Gabor Greif051a9502008-04-06 20:25:17 +00001659 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001660 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001661 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001662 }
1663 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001664 }
1665
1666 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001667 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001668}
1669
1670
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001671/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1672/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001673bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001674 Module::global_iterator &GVI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001675 SmallPtrSet<const PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001676 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001677 GV->removeDeadConstantUsers();
1678
1679 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001680 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001681 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001682 ++NumDeleted;
1683 return true;
1684 }
1685
1686 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001687#if 0
David Greene3215b0e2010-01-05 01:28:05 +00001688 DEBUG(dbgs() << "Global: " << *GV);
1689 DEBUG(dbgs() << " isLoaded = " << GS.isLoaded << "\n");
1690 DEBUG(dbgs() << " StoredType = ");
Chris Lattnercff16732006-09-30 19:40:30 +00001691 switch (GS.StoredType) {
David Greene3215b0e2010-01-05 01:28:05 +00001692 case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break;
1693 case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n");
Victor Hernandez631f3c02009-11-07 00:41:19 +00001694 break;
David Greene3215b0e2010-01-05 01:28:05 +00001695 case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break;
1696 case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break;
Chris Lattnercff16732006-09-30 19:40:30 +00001697 }
1698 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
David Greene3215b0e2010-01-05 01:28:05 +00001699 DEBUG(dbgs() << " StoredOnceValue = " << *GS.StoredOnceValue << "\n");
Chris Lattnercff16732006-09-30 19:40:30 +00001700 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
David Greene3215b0e2010-01-05 01:28:05 +00001701 DEBUG(dbgs() << " AccessingFunction = " << GS.AccessingFunction->getName()
Victor Hernandez631f3c02009-11-07 00:41:19 +00001702 << "\n");
David Greene3215b0e2010-01-05 01:28:05 +00001703 DEBUG(dbgs() << " HasMultipleAccessingFunctions = "
Victor Hernandez631f3c02009-11-07 00:41:19 +00001704 << GS.HasMultipleAccessingFunctions << "\n");
David Greene3215b0e2010-01-05 01:28:05 +00001705 DEBUG(dbgs() << " HasNonInstructionUser = "
Victor Hernandez631f3c02009-11-07 00:41:19 +00001706 << GS.HasNonInstructionUser<<"\n");
David Greene3215b0e2010-01-05 01:28:05 +00001707 DEBUG(dbgs() << "\n");
Chris Lattnercff16732006-09-30 19:40:30 +00001708#endif
1709
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001710 // If this is a first class global and has only one accessing function
1711 // and this function is main (which we know is not recursive we can make
1712 // this global a local variable) we replace the global with a local alloca
1713 // in this function.
1714 //
Dan Gohman399101a2008-05-23 00:17:26 +00001715 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001716 // are just replacing static memory to stack memory.
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001717 //
1718 // If the global is in different address space, don't bring it to stack.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001719 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001720 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001721 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001722 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001723 GS.AccessingFunction->hasExternalLinkage() &&
1724 GV->getType()->getAddressSpace() == 0) {
David Greene3215b0e2010-01-05 01:28:05 +00001725 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001726 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1727 ->getEntryBlock().begin());
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001728 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001729 // FIXME: Pass Global's alignment when globals have alignment
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001730 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001731 if (!isa<UndefValue>(GV->getInitializer()))
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001732 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001733
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001734 GV->replaceAllUsesWith(Alloca);
1735 GV->eraseFromParent();
1736 ++NumLocalized;
1737 return true;
1738 }
Chris Lattnercff16732006-09-30 19:40:30 +00001739
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001740 // If the global is never loaded (but may be stored to), it is dead.
1741 // Delete it now.
1742 if (!GS.isLoaded) {
David Greene3215b0e2010-01-05 01:28:05 +00001743 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattner930f4752004-10-09 03:32:52 +00001744
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001745 // Delete any stores we can find to the global. We may not be able to
1746 // make it completely dead though.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001747 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001748
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001749 // If the global is dead now, delete it.
1750 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001751 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001752 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001753 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001754 }
Chris Lattner930f4752004-10-09 03:32:52 +00001755 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001756
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001757 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
David Greene3215b0e2010-01-05 01:28:05 +00001758 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001759 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001760
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001761 // Clean up any obviously simplifiable users now.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001762 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001763
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001764 // If the global is dead now, just nuke it.
1765 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001766 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
Chris Lattnerbdff5482009-08-23 04:37:46 +00001767 << "all users and delete global!\n");
Chris Lattner7a7ed022004-10-16 18:09:00 +00001768 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001769 ++NumDeleted;
1770 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001771
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001772 ++NumMarked;
1773 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001774 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Dan Gohman7eb28f32009-08-14 00:11:03 +00001775 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
Chris Lattner7b550cc2009-11-06 04:27:31 +00001776 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
Dan Gohman7eb28f32009-08-14 00:11:03 +00001777 GVI = FirstNewGV; // Don't skip the newly produced globals!
1778 return true;
1779 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001780 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001781 // If the initial value for the global was an undef value, and if only
1782 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001783 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001784 // global. This allows us to mark it constant.
1785 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1786 if (isa<UndefValue>(GV->getInitializer())) {
1787 // Change the initial value here.
1788 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001789
Chris Lattner96a86b22004-12-12 05:53:50 +00001790 // Clean up any obviously simplifiable users now.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001791 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001792
Chris Lattner96a86b22004-12-12 05:53:50 +00001793 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001794 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Chris Lattnerbdff5482009-08-23 04:37:46 +00001795 << "simplify all users and delete global!\n");
Chris Lattner96a86b22004-12-12 05:53:50 +00001796 GV->eraseFromParent();
1797 ++NumDeleted;
1798 } else {
1799 GVI = GV;
1800 }
1801 ++NumSubstitute;
1802 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001803 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001804
Chris Lattner9b34a612004-10-09 21:48:45 +00001805 // Try to optimize globals based on the knowledge that only one value
1806 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001807 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001808 getAnalysisIfAvailable<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001809 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001810
1811 // Otherwise, if the global was not a boolean, we can shrink it to be a
1812 // boolean.
1813 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001814 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001815 ++NumShrunkToBool;
1816 return true;
1817 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001818 }
1819 }
1820 return false;
1821}
1822
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001823/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1824/// function, changing them to FastCC.
1825static void ChangeCalleesToFastCall(Function *F) {
1826 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001827 CallSite User(cast<Instruction>(*UI));
1828 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001829 }
1830}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001831
Devang Patel05988662008-09-25 21:00:45 +00001832static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001833 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001834 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001835 continue;
1836
Duncan Sands548448a2008-02-18 17:32:13 +00001837 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001838 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001839 }
1840
1841 return Attrs;
1842}
1843
1844static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001845 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001846 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001847 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001848 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001849 }
1850}
1851
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001852bool GlobalOpt::OptimizeFunctions(Module &M) {
1853 bool Changed = false;
1854 // Optimize functions.
1855 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1856 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001857 // Functions without names cannot be referenced outside this module.
1858 if (!F->hasName() && !F->isDeclaration())
1859 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001860 F->removeDeadConstantUsers();
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001861 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1862 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001863 Changed = true;
1864 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001865 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001866 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001867 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001868 // If this function has C calling conventions, is not a varargs
1869 // function, and is only called directly, promote it to use the Fast
1870 // calling convention.
1871 F->setCallingConv(CallingConv::Fast);
1872 ChangeCalleesToFastCall(F);
1873 ++NumFastCallFns;
1874 Changed = true;
1875 }
1876
Devang Patel05988662008-09-25 21:00:45 +00001877 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001878 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001879 // The function is not used by a trampoline intrinsic, so it is safe
1880 // to remove the 'nest' attribute.
1881 RemoveNestAttribute(F);
1882 ++NumNestRemoved;
1883 Changed = true;
1884 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001885 }
1886 }
1887 return Changed;
1888}
1889
1890bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1891 bool Changed = false;
1892 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1893 GVI != E; ) {
1894 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001895 // Global variables without names cannot be referenced outside this module.
1896 if (!GV->hasName() && !GV->isDeclaration())
1897 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001898 // Simplify the initializer.
1899 if (GV->hasInitializer())
1900 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohmanf860db22010-04-02 03:04:37 +00001901 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman01b97dd2009-11-23 16:22:21 +00001902 Constant *New = ConstantFoldConstantExpression(CE, TD);
1903 if (New && New != CE)
1904 GV->setInitializer(New);
1905 }
1906 // Do more involved optimizations if the global is internal.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001907 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001908 GV->hasInitializer())
1909 Changed |= ProcessInternalGlobal(GV, GVI);
1910 }
1911 return Changed;
1912}
1913
1914/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1915/// initializers have an init priority of 65535.
1916GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001917 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1918 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001919 if (I->getName() == "llvm.global_ctors") {
1920 // Found it, verify it's an array of { int, void()* }.
1921 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1922 if (!ATy) return 0;
1923 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1924 if (!STy || STy->getNumElements() != 2 ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001925 !STy->getElementType(0)->isIntegerTy(32)) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001926 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1927 if (!PFTy) return 0;
1928 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
Benjamin Kramerf0127052010-01-05 13:12:22 +00001929 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001930 FTy->isVarArg() || FTy->getNumParams() != 0)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001931 return 0;
1932
1933 // Verify that the initializer is simple enough for us to handle.
Dan Gohman82555732009-08-19 18:20:44 +00001934 if (!I->hasDefinitiveInitializer()) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001935 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1936 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001937 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1938 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001939 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1940 continue;
1941
1942 // Must have a function or null ptr.
1943 if (!isa<Function>(CS->getOperand(1)))
1944 return 0;
1945
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001946 // Init priority must be standard.
1947 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001948 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001949 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001950 } else {
1951 return 0;
1952 }
1953
1954 return I;
1955 }
1956 return 0;
1957}
1958
Chris Lattnerdb973e62005-09-26 02:31:18 +00001959/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1960/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001961static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1962 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1963 std::vector<Function*> Result;
1964 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001965 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1966 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001967 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1968 }
1969 return Result;
1970}
1971
Chris Lattnerdb973e62005-09-26 02:31:18 +00001972/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1973/// specified array, returning the new global to use.
1974static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001975 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001976 // If we made a change, reassemble the initializer list.
1977 std::vector<Constant*> CSVals;
Chris Lattner7b550cc2009-11-06 04:27:31 +00001978 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001979 CSVals.push_back(0);
1980
1981 // Create the new init list.
1982 std::vector<Constant*> CAList;
1983 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001984 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001985 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001986 } else {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001987 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
1988 false);
Owen Andersondebcb012009-07-29 22:17:13 +00001989 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00001990 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001991 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
1992 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001993 }
Chris Lattner7b550cc2009-11-06 04:27:31 +00001994 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001995 }
1996
1997 // Create the array initializer.
1998 const Type *StructTy =
Nick Lewyckyc332fba2009-09-19 20:30:26 +00001999 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson1fd70962009-07-28 18:32:17 +00002000 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002001 CAList.size()), CAList);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002002
2003 // If we didn't change the number of elements, don't create a new GV.
2004 if (CA->getType() == GCL->getInitializer()->getType()) {
2005 GCL->setInitializer(CA);
2006 return GCL;
2007 }
2008
2009 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002010 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002011 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002012 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002013 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002014 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002015
2016 // Nuke the old list, replacing any uses with the new one.
2017 if (!GCL->use_empty()) {
2018 Constant *V = NGV;
2019 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002020 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002021 GCL->replaceAllUsesWith(V);
2022 }
2023 GCL->eraseFromParent();
2024
2025 if (Ctors.size())
2026 return NGV;
2027 else
2028 return 0;
2029}
Chris Lattner79c11012005-09-26 04:44:35 +00002030
2031
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002032static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00002033 Value *V) {
2034 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2035 Constant *R = ComputedValues[V];
2036 assert(R && "Reference to an uncomputed value!");
2037 return R;
2038}
2039
2040/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2041/// enough for us to understand. In particular, if it is a cast of something,
2042/// we punt. We basically just support direct accesses to globals and GEP's of
2043/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002044static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002045 // Conservatively, avoid aggregate types. This is because we don't
2046 // want to worry about them partially overlapping other stores.
2047 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2048 return false;
2049
Dan Gohmanfd54a892009-09-07 22:31:26 +00002050 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2051 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2052 // external globals.
2053 return GV->hasDefinitiveInitializer();
2054
Chris Lattner798b4d52005-09-26 06:52:44 +00002055 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2056 // Handle a constantexpr gep.
2057 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002058 isa<GlobalVariable>(CE->getOperand(0)) &&
2059 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002060 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohmanfd54a892009-09-07 22:31:26 +00002061 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2062 // external globals.
2063 if (!GV->hasDefinitiveInitializer())
2064 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002065
Dan Gohman80bdc962009-09-07 22:44:55 +00002066 // The first index must be zero.
Dan Gohmane6992f72009-09-10 23:37:55 +00002067 ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002068 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002069
2070 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002071 // notional bounds of the corresponding static array types.
2072 if (!CE->isGEPWithNoNotionalOverIndexing())
2073 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002074
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002075 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002076 }
Chris Lattner79c11012005-09-26 04:44:35 +00002077 return false;
2078}
2079
Chris Lattner798b4d52005-09-26 06:52:44 +00002080/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2081/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2082/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2083static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002084 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002085 // Base case of the recursion.
2086 if (OpNo == Addr->getNumOperands()) {
2087 assert(Val->getType() == Init->getType() && "Type mismatch!");
2088 return Val;
2089 }
2090
Chris Lattnera0e9a242010-01-07 01:16:21 +00002091 std::vector<Constant*> Elts;
Chris Lattner798b4d52005-09-26 06:52:44 +00002092 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002093
2094 // Break up the constant into its elements.
2095 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002096 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2097 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002098 } else if (isa<ConstantAggregateZero>(Init)) {
2099 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002100 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002101 } else if (isa<UndefValue>(Init)) {
2102 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002103 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002104 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002105 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002106 " ConstantFoldLoadThroughGEPConstantExpr");
2107 }
2108
2109 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002110 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2111 unsigned Idx = CU->getZExtValue();
2112 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002113 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00002114
2115 // Return the modified struct.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002116 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2117 STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002118 } else {
2119 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002120 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002121
Chris Lattnera0e9a242010-01-07 01:16:21 +00002122 uint64_t NumElts;
2123 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2124 NumElts = ATy->getNumElements();
2125 else
2126 NumElts = cast<VectorType>(InitTy)->getNumElements();
2127
2128
Chris Lattner798b4d52005-09-26 06:52:44 +00002129 // Break up the array into elements.
Chris Lattner798b4d52005-09-26 06:52:44 +00002130 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002131 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2132 Elts.push_back(cast<Constant>(*i));
Chris Lattner4039bd02010-01-07 01:20:20 +00002133 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2134 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2135 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002136 } else if (isa<ConstantAggregateZero>(Init)) {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002137 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002138 } else {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002139 assert(isa<UndefValue>(Init) && "This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002140 " ConstantFoldLoadThroughGEPConstantExpr");
Chris Lattnera0e9a242010-01-07 01:16:21 +00002141 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002142 }
2143
Chris Lattnera0e9a242010-01-07 01:16:21 +00002144 assert(CI->getZExtValue() < NumElts);
Reid Spencerb83eb642006-10-20 07:07:24 +00002145 Elts[CI->getZExtValue()] =
Chris Lattner7b550cc2009-11-06 04:27:31 +00002146 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnera0e9a242010-01-07 01:16:21 +00002147
Duncan Sands1df98592010-02-16 11:11:14 +00002148 if (Init->getType()->isArrayTy())
Chris Lattnera0e9a242010-01-07 01:16:21 +00002149 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2150 else
2151 return ConstantVector::get(&Elts[0], Elts.size());
Chris Lattner798b4d52005-09-26 06:52:44 +00002152 }
2153}
2154
Chris Lattner79c11012005-09-26 04:44:35 +00002155/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2156/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002157static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002158 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2159 assert(GV->hasInitializer());
2160 GV->setInitializer(Val);
2161 return;
2162 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002163
Chris Lattner798b4d52005-09-26 06:52:44 +00002164 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2165 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002166 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002167}
2168
Chris Lattner562a0552005-09-26 05:16:34 +00002169/// ComputeLoadResult - Return the value that would be computed by a load from
2170/// P after the stores reflected by 'memory' have been performed. If we can't
2171/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002172static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002173 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002174 // If this memory location has been recently stored, use the stored value: it
2175 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002176 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002177 if (I != Memory.end()) return I->second;
2178
2179 // Access it.
2180 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002181 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002182 return GV->getInitializer();
2183 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002184 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002185
2186 // Handle a constantexpr getelementptr.
2187 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2188 if (CE->getOpcode() == Instruction::GetElementPtr &&
2189 isa<GlobalVariable>(CE->getOperand(0))) {
2190 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002191 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002192 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002193 }
2194
2195 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002196}
2197
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002198/// EvaluateFunction - Evaluate a call to function F, returning true if
2199/// successful, false if we can't evaluate it. ActualArgs contains the formal
2200/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002201static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002202 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002203 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002204 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002205 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002206 // Check to see if this function is already executing (recursion). If so,
2207 // bail out. TODO: we might want to accept limited recursion.
2208 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2209 return false;
2210
2211 CallStack.push_back(F);
2212
Chris Lattner79c11012005-09-26 04:44:35 +00002213 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002214 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002215
2216 // Initialize arguments to the incoming values specified.
2217 unsigned ArgNo = 0;
2218 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2219 ++AI, ++ArgNo)
2220 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002221
Chris Lattnercdf98be2005-09-26 04:57:38 +00002222 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2223 /// we can only evaluate any one basic block at most once. This set keeps
2224 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002225 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002226
Chris Lattner79c11012005-09-26 04:44:35 +00002227 // CurInst - The current instruction we're evaluating.
2228 BasicBlock::iterator CurInst = F->begin()->begin();
2229
2230 // This is the main evaluation loop.
2231 while (1) {
2232 Constant *InstResult = 0;
2233
2234 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002235 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002236 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002237 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002238 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002239 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002240 Constant *Val = getVal(Values, SI->getOperand(0));
2241 MutatedMemory[Ptr] = Val;
2242 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002243 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002244 getVal(Values, BO->getOperand(0)),
2245 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002246 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002247 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002248 getVal(Values, CI->getOperand(0)),
2249 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002250 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002251 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002252 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002253 CI->getType());
2254 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002255 InstResult =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002256 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002257 getVal(Values, SI->getOperand(1)),
2258 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002259 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2260 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002261 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002262 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2263 i != e; ++i)
2264 GEPOps.push_back(getVal(Values, *i));
Dan Gohman4a7e6b72009-09-07 22:34:43 +00002265 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2266 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2267 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002268 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002269 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002270 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002271 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002272 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002273 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002274 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002275 const Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002276 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002277 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002278 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002279 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002280 InstResult = AllocaTmps.back();
2281 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002282
2283 // Debug info can safely be ignored here.
2284 if (isa<DbgInfoIntrinsic>(CI)) {
2285 ++CurInst;
2286 continue;
2287 }
2288
Chris Lattner7cd580f2006-07-07 21:37:01 +00002289 // Cannot handle inline asm.
2290 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2291
Chris Lattnercd271422005-09-27 04:45:34 +00002292 // Resolve function pointers.
2293 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2294 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002295
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002296 SmallVector<Constant*, 8> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002297 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2298 i != e; ++i)
2299 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002300
Reid Spencer5cbf9852007-01-30 20:08:39 +00002301 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002302 // If this is a function we can constant fold, do it.
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002303 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
Chris Lattner6c1f5652007-01-30 23:14:52 +00002304 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002305 InstResult = C;
2306 } else {
2307 return false;
2308 }
2309 } else {
2310 if (Callee->getFunctionType()->isVarArg())
2311 return false;
2312
2313 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002314 // Execute the call, if successful, use the return value.
2315 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2316 MutatedMemory, AllocaTmps))
2317 return false;
2318 InstResult = RetVal;
2319 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002320 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002321 BasicBlock *NewBB = 0;
2322 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2323 if (BI->isUnconditional()) {
2324 NewBB = BI->getSuccessor(0);
2325 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002326 ConstantInt *Cond =
2327 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002328 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002329
Reid Spencer579dca12007-01-12 04:24:46 +00002330 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002331 }
2332 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2333 ConstantInt *Val =
2334 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002335 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002336 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002337 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2338 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2339 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2340 NewBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002341 else
2342 return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002343 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002344 if (RI->getNumOperands())
2345 RetVal = getVal(Values, RI->getOperand(0));
2346
2347 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002348 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002349 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002350 // invoke, unwind, unreachable.
2351 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002352 }
2353
2354 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002355 // executed the new block before. If so, we have a looping function,
2356 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002357 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002358 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002359
2360 // Okay, we have never been in this block before. Check to see if there
2361 // are any PHI nodes. If so, evaluate them with information about where
2362 // we came from.
2363 BasicBlock *OldBB = CurInst->getParent();
2364 CurInst = NewBB->begin();
2365 PHINode *PN;
2366 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2367 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2368
2369 // Do NOT increment CurInst. We know that the terminator had no value.
2370 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002371 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002372 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002373 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002374 }
2375
2376 if (!CurInst->use_empty())
2377 Values[CurInst] = InstResult;
2378
2379 // Advance program counter.
2380 ++CurInst;
2381 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002382}
2383
2384/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2385/// we can. Return true if we can, false otherwise.
2386static bool EvaluateStaticConstructor(Function *F) {
2387 /// MutatedMemory - For each store we execute, we update this map. Loads
2388 /// check this to get the most up-to-date value. If evaluation is successful,
2389 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002390 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002391
2392 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2393 /// to represent its body. This vector is needed so we can delete the
2394 /// temporary globals when we are done.
2395 std::vector<GlobalVariable*> AllocaTmps;
2396
2397 /// CallStack - This is used to detect recursion. In pathological situations
2398 /// we could hit exponential behavior, but at least there is nothing
2399 /// unbounded.
2400 std::vector<Function*> CallStack;
2401
2402 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002403 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002404 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2405 SmallVector<Constant*, 0>(), CallStack,
2406 MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002407 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002408 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002409 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002410 << F->getName() << "' to " << MutatedMemory.size()
2411 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002412 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002413 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002414 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002415 }
Chris Lattner79c11012005-09-26 04:44:35 +00002416
Chris Lattnera22fdb02005-09-26 17:07:09 +00002417 // At this point, we are done interpreting. If we created any 'alloca'
2418 // temporaries, release them now.
2419 while (!AllocaTmps.empty()) {
2420 GlobalVariable *Tmp = AllocaTmps.back();
2421 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002422
Chris Lattnera22fdb02005-09-26 17:07:09 +00002423 // If there are still users of the alloca, the program is doing something
2424 // silly, e.g. storing the address of the alloca somewhere and using it
2425 // later. Since this is undefined, we'll just make it be null.
2426 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002427 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002428 delete Tmp;
2429 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002430
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002431 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002432}
2433
Chris Lattnerdb973e62005-09-26 02:31:18 +00002434
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002435
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002436/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2437/// Return true if anything changed.
2438bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2439 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2440 bool MadeChange = false;
2441 if (Ctors.empty()) return false;
2442
2443 // Loop over global ctors, optimizing them when we can.
2444 for (unsigned i = 0; i != Ctors.size(); ++i) {
2445 Function *F = Ctors[i];
2446 // Found a null terminator in the middle of the list, prune off the rest of
2447 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002448 if (F == 0) {
2449 if (i != Ctors.size()-1) {
2450 Ctors.resize(i+1);
2451 MadeChange = true;
2452 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002453 break;
2454 }
2455
Chris Lattner79c11012005-09-26 04:44:35 +00002456 // We cannot simplify external ctor functions.
2457 if (F->empty()) continue;
2458
2459 // If we can evaluate the ctor at compile time, do.
2460 if (EvaluateStaticConstructor(F)) {
2461 Ctors.erase(Ctors.begin()+i);
2462 MadeChange = true;
2463 --i;
2464 ++NumCtorsEvaluated;
2465 continue;
2466 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002467 }
2468
2469 if (!MadeChange) return false;
2470
Chris Lattner7b550cc2009-11-06 04:27:31 +00002471 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002472 return true;
2473}
2474
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002475bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002476 bool Changed = false;
2477
Duncan Sands177d84e2009-01-07 20:01:06 +00002478 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002479 I != E;) {
2480 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002481 // Aliases without names cannot be referenced outside this module.
2482 if (!J->hasName() && !J->isDeclaration())
2483 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002484 // If the aliasee may change at link time, nothing can be done - bail out.
2485 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002486 continue;
2487
Duncan Sands4782b302009-02-15 09:56:08 +00002488 Constant *Aliasee = J->getAliasee();
2489 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002490 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002491 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2492
2493 // Make all users of the alias use the aliasee instead.
2494 if (!J->use_empty()) {
2495 J->replaceAllUsesWith(Aliasee);
2496 ++NumAliasesResolved;
2497 Changed = true;
2498 }
2499
Duncan Sands7a154cf2009-12-08 10:10:20 +00002500 // If the alias is externally visible, we may still be able to simplify it.
2501 if (!J->hasLocalLinkage()) {
2502 // If the aliasee has internal linkage, give it the name and linkage
2503 // of the alias, and delete the alias. This turns:
2504 // define internal ... @f(...)
2505 // @a = alias ... @f
2506 // into:
2507 // define ... @a(...)
2508 if (!Target->hasLocalLinkage())
2509 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002510
Duncan Sands7a154cf2009-12-08 10:10:20 +00002511 // Do not perform the transform if multiple aliases potentially target the
2512 // aliasee. This check also ensures that it is safe to replace the section
2513 // and other attributes of the aliasee with those of the alias.
2514 if (!hasOneUse)
2515 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002516
Duncan Sands7a154cf2009-12-08 10:10:20 +00002517 // Give the aliasee the name, linkage and other attributes of the alias.
2518 Target->takeName(J);
2519 Target->setLinkage(J->getLinkage());
2520 Target->GlobalValue::copyAttributesFrom(J);
2521 }
Duncan Sands4782b302009-02-15 09:56:08 +00002522
2523 // Delete the alias.
2524 M.getAliasList().erase(J);
2525 ++NumAliasesRemoved;
2526 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002527 }
2528
2529 return Changed;
2530}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002531
Chris Lattner7a90b682004-10-07 04:16:33 +00002532bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002533 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002534
2535 // Try to find the llvm.globalctors list.
2536 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002537
Chris Lattner7a90b682004-10-07 04:16:33 +00002538 bool LocalChange = true;
2539 while (LocalChange) {
2540 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002541
2542 // Delete functions that are trivially dead, ccc -> fastcc
2543 LocalChange |= OptimizeFunctions(M);
2544
2545 // Optimize global_ctors list.
2546 if (GlobalCtors)
2547 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2548
2549 // Optimize non-address-taken globals.
2550 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002551
2552 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002553 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002554 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002555 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002556
2557 // TODO: Move all global ctors functions to the end of the module for code
2558 // layout.
2559
Chris Lattner079236d2004-02-25 21:34:36 +00002560 return Changed;
2561}