blob: 9b5511f3f215ad8c9e057dbbafe47c8dffb9e4f9 [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 Greif27236912010-04-07 18:59:26 +0000146 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
147 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000148 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000149 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000150 } else
151 return false;
152 return true;
153}
154
155
Chris Lattner7a90b682004-10-07 04:16:33 +0000156/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
157/// structure. If the global has its address taken, return true to indicate we
158/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000159///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000160static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
161 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000162 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000163 ++UI) {
164 const User *U = *UI;
165 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000166 GS.HasNonInstructionUser = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000167 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000168 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000169 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000170 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000171 if (GS.AccessingFunction == 0)
172 GS.AccessingFunction = F;
173 else if (GS.AccessingFunction != F)
174 GS.HasMultipleAccessingFunctions = true;
175 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000176 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000177 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000178 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000179 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000180 // Don't allow a store OF the address, only stores TO the address.
181 if (SI->getOperand(0) == V) return true;
182
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000183 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
184
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000185 // If this is a direct store to the global (i.e., the global is a scalar
186 // value, not an aggregate), keep more specific information about
187 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000188 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000189 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
190 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000191 Value *StoredVal = SI->getOperand(0);
192 if (StoredVal == GV->getInitializer()) {
193 if (GS.StoredType < GlobalStatus::isInitializerStored)
194 GS.StoredType = GlobalStatus::isInitializerStored;
195 } else if (isa<LoadInst>(StoredVal) &&
196 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000197 if (GS.StoredType < GlobalStatus::isInitializerStored)
198 GS.StoredType = GlobalStatus::isInitializerStored;
199 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
200 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000201 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000202 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000203 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000204 // noop.
205 } else {
206 GS.StoredType = GlobalStatus::isStored;
207 }
208 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000209 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000210 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000211 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000212 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000214 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000215 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000216 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000217 // PHI nodes we can check just like select or GEP instructions, but we
218 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000219 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000220 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000221 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000222 } else if (isa<CmpInst>(I)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +0000223 // Nothing to analyse.
Chris Lattner8e108442009-03-08 03:37:35 +0000224 } else if (isa<MemTransferInst>(I)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +0000225 const MemTransferInst *MTI = cast<MemTransferInst>(I);
226 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000227 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000228 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000229 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000230 } else if (isa<MemSetInst>(I)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +0000231 assert(cast<MemSetInst>(I)->getArgOperand(0) == V &&
232 "Memset only takes one pointer!");
Chris Lattner35c81b02005-02-27 18:58:52 +0000233 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000234 } else {
235 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000236 }
Gabor Greife6642672010-07-09 16:51:20 +0000237 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000238 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000239 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000240 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000241 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000242 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000243 GS.HasNonInstructionUser = true;
244 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000245 return true;
246 }
Gabor Greife6642672010-07-09 16:51:20 +0000247 }
Chris Lattner079236d2004-02-25 21:34:36 +0000248
249 return false;
250}
251
Chris Lattner7b550cc2009-11-06 04:27:31 +0000252static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
Chris Lattner670c8892004-10-08 17:32:09 +0000253 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
254 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000255 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000256
Chris Lattner670c8892004-10-08 17:32:09 +0000257 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
258 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
259 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
260 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000261 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000262 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000263 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000264 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
265 if (IdxV < STy->getNumElements())
Owen Andersona7235ea2009-07-31 20:28:14 +0000266 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000267 } else if (const SequentialType *STy =
268 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000269 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000270 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000271 } else if (isa<UndefValue>(Agg)) {
272 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
273 if (IdxV < STy->getNumElements())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000274 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000275 } else if (const SequentialType *STy =
276 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000277 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000278 }
Chris Lattner670c8892004-10-08 17:32:09 +0000279 }
280 return 0;
281}
Chris Lattner7a90b682004-10-07 04:16:33 +0000282
Chris Lattner7a90b682004-10-07 04:16:33 +0000283
Chris Lattnere47ba742004-10-06 20:57:02 +0000284/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
285/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000286/// quick scan over the use list to clean up the easy and obvious cruft. This
287/// returns true if it made a change.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000288static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000289 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000290 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
291 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000292
Chris Lattner7a90b682004-10-07 04:16:33 +0000293 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000294 if (Init) {
295 // Replace the load with the initializer.
296 LI->replaceAllUsesWith(Init);
297 LI->eraseFromParent();
298 Changed = true;
299 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000300 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000301 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000302 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000303 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000304 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
305 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000306 Constant *SubInit = 0;
307 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000308 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000309 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000310 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000311 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000312 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000313 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000314 }
315
316 if (CE->use_empty()) {
317 CE->destroyConstant();
318 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000319 }
320 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000321 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
322 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
323 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000324 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000325 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
326 ConstantExpr *CE =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000327 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000328 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000329 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000330 }
Chris Lattner7b550cc2009-11-06 04:27:31 +0000331 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000332
Chris Lattner031955d2004-10-10 16:43:46 +0000333 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000334 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000335 Changed = true;
336 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000337 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
338 if (MI->getRawDest() == V) {
339 MI->eraseFromParent();
340 Changed = true;
341 }
342
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000343 } else if (Constant *C = dyn_cast<Constant>(U)) {
344 // If we have a chain of dead constantexprs or other things dangling from
345 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000346 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000347 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000348 // This could have invalidated UI, start over from scratch.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000349 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000350 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000351 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000352 }
353 }
Chris Lattner031955d2004-10-10 16:43:46 +0000354 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000355}
356
Chris Lattner941db492008-01-14 02:09:12 +0000357/// isSafeSROAElementUse - Return true if the specified instruction is a safe
358/// user of a derived expression from a global that we want to SROA.
359static bool isSafeSROAElementUse(Value *V) {
360 // We might have a dead and dangling constant hanging off of here.
361 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000362 return SafeToDestroyConstant(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000363
Chris Lattner941db492008-01-14 02:09:12 +0000364 Instruction *I = dyn_cast<Instruction>(V);
365 if (!I) return false;
366
367 // Loads are ok.
368 if (isa<LoadInst>(I)) return true;
369
370 // Stores *to* the pointer are ok.
371 if (StoreInst *SI = dyn_cast<StoreInst>(I))
372 return SI->getOperand(0) != V;
373
374 // Otherwise, it must be a GEP.
375 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
376 if (GEPI == 0) return false;
377
378 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
379 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
380 return false;
381
382 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
383 I != E; ++I)
384 if (!isSafeSROAElementUse(*I))
385 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000386 return true;
387}
388
Chris Lattner941db492008-01-14 02:09:12 +0000389
390/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
391/// Look at it and its uses and decide whether it is safe to SROA this global.
392///
393static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
394 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
395 if (!isa<GetElementPtrInst>(U) &&
396 (!isa<ConstantExpr>(U) ||
397 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
398 return false;
399
400 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
401 // don't like < 3 operand CE's, and we don't like non-constant integer
402 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
403 // value of C.
404 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
405 !cast<Constant>(U->getOperand(1))->isNullValue() ||
406 !isa<ConstantInt>(U->getOperand(2)))
407 return false;
408
409 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
410 ++GEPI; // Skip over the pointer index.
411
412 // If this is a use of an array allocation, do a bit more checking for sanity.
413 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
414 uint64_t NumElements = AT->getNumElements();
415 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
416
417 // Check to make sure that index falls within the array. If not,
418 // something funny is going on, so we won't do the optimization.
419 //
420 if (Idx->getZExtValue() >= NumElements)
421 return false;
422
423 // We cannot scalar repl this level of the array unless any array
424 // sub-indices are in-range constants. In particular, consider:
425 // A[0][i]. We cannot know that the user isn't doing invalid things like
426 // allowing i to index an out-of-range subscript that accesses A[1].
427 //
428 // Scalar replacing *just* the outer index of the array is probably not
429 // going to be a win anyway, so just give up.
430 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000431 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000432 ++GEPI) {
433 uint64_t NumElements;
434 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
435 NumElements = SubArrayTy->getNumElements();
Dan Gohman6874a2a2009-08-18 14:58:19 +0000436 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
437 NumElements = SubVectorTy->getNumElements();
438 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000439 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000440 "Indexed GEP type is not array, vector, or struct!");
441 continue;
442 }
Chris Lattner941db492008-01-14 02:09:12 +0000443
444 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
445 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
446 return false;
447 }
448 }
449
450 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
451 if (!isSafeSROAElementUse(*I))
452 return false;
453 return true;
454}
455
456/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
457/// is safe for us to perform this transformation.
458///
459static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
460 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
461 UI != E; ++UI) {
462 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
463 return false;
464 }
465 return true;
466}
467
468
Chris Lattner670c8892004-10-08 17:32:09 +0000469/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
470/// variable. This opens the door for other optimizations by exposing the
471/// behavior of the program in a more fine-grained way. We have determined that
472/// this transformation is safe already. We return the first global variable we
473/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000474static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000475 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000476 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000477 return 0;
478
Rafael Espindolabb46f522009-01-15 20:18:42 +0000479 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000480 Constant *Init = GV->getInitializer();
481 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000482
Chris Lattner670c8892004-10-08 17:32:09 +0000483 std::vector<GlobalVariable*> NewGlobals;
484 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
485
Chris Lattner998182b2008-04-26 07:40:11 +0000486 // Get the alignment of the global, either explicit or target-specific.
487 unsigned StartAlignment = GV->getAlignment();
488 if (StartAlignment == 0)
489 StartAlignment = TD.getABITypeAlignment(GV->getType());
490
Chris Lattner670c8892004-10-08 17:32:09 +0000491 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
492 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000493 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000494 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
495 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000496 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000497 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000498 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000499 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000500 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000501 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000502 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000503 Globals.insert(GV, NGV);
504 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000505
506 // Calculate the known alignment of the field. If the original aggregate
507 // had 256 byte alignment for example, something might depend on that:
508 // propagate info to each field.
509 uint64_t FieldOffset = Layout.getElementOffset(i);
510 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
511 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
512 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000513 }
514 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
515 unsigned NumElements = 0;
516 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
517 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000518 else
Chris Lattner998182b2008-04-26 07:40:11 +0000519 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000520
Chris Lattner1f21ef12005-02-23 16:53:04 +0000521 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000522 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000523 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000524
Duncan Sands777d2302009-05-09 07:06:46 +0000525 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000526 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000527 for (unsigned i = 0, e = NumElements; i != e; ++i) {
528 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000529 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000530 assert(In && "Couldn't get element of initializer?");
531
Chris Lattner7b550cc2009-11-06 04:27:31 +0000532 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000533 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000534 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000535 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000536 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000537 Globals.insert(GV, NGV);
538 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000539
540 // Calculate the known alignment of the field. If the original aggregate
541 // had 256 byte alignment for example, something might depend on that:
542 // propagate info to each field.
543 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
544 if (NewAlign > EltAlign)
545 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000546 }
547 }
548
549 if (NewGlobals.empty())
550 return 0;
Chris Lattnerc6a669b2010-02-26 23:35:25 +0000551
David Greene3215b0e2010-01-05 01:28:05 +0000552 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000553
Chris Lattner7b550cc2009-11-06 04:27:31 +0000554 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000555
556 // Loop over all of the uses of the global, replacing the constantexpr geps,
557 // with smaller constantexpr geps or direct references.
558 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000559 User *GEP = GV->use_back();
560 assert(((isa<ConstantExpr>(GEP) &&
561 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
562 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000563
Chris Lattner670c8892004-10-08 17:32:09 +0000564 // Ignore the 1th operand, which has to be zero or else the program is quite
565 // broken (undefined). Get the 2nd operand, which is the structure or array
566 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000567 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000568 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
569
Chris Lattner30ba5692004-10-11 05:54:41 +0000570 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000571
572 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000573 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000574 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000575 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000576 Idxs.push_back(NullInt);
577 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
578 Idxs.push_back(CE->getOperand(i));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000579 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000580 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000581 } else {
582 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000583 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000584 Idxs.push_back(NullInt);
585 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
586 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000587 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000588 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000589 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000590 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000591 GEP->replaceAllUsesWith(NewPtr);
592
593 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000594 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000595 else
596 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000597 }
598
Chris Lattnere40e2d12004-10-08 20:25:55 +0000599 // Delete the old global, now that it is dead.
600 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000601 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000602
603 // Loop over the new globals array deleting any globals that are obviously
604 // dead. This can arise due to scalarization of a structure or an array that
605 // has elements that are dead.
606 unsigned FirstGlobal = 0;
607 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
608 if (NewGlobals[i]->use_empty()) {
609 Globals.erase(NewGlobals[i]);
610 if (FirstGlobal == i) ++FirstGlobal;
611 }
612
613 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000614}
615
Chris Lattner9b34a612004-10-09 21:48:45 +0000616/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000617/// value will trap if the value is dynamically null. PHIs keeps track of any
618/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000619static bool AllUsesOfValueWillTrapIfNull(const Value *V,
620 SmallPtrSet<const PHINode*, 8> &PHIs) {
621 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000622 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000623 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000624
625 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000626 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000627 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000628 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000629 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000630 return false; // Storing the value.
631 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000632 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000633 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000634 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000635 return false; // Not calling the ptr
636 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000637 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000638 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000639 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000640 return false; // Not calling the ptr
641 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000642 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000643 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000644 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000645 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000646 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000647 // If we've already seen this phi node, ignore it, it has already been
648 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000649 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
650 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000651 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000652 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000653 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000654 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000655 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000656 return false;
657 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000658 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000659 return true;
660}
661
662/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000663/// from GV will trap if the loaded value is null. Note that this also permits
664/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000665static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
666 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000667 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000668 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000669
Gabor Greif6ce02b52010-04-06 19:24:18 +0000670 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
671 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000672 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000673 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000674 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000675 // Ignore stores to the global.
676 } else {
677 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000678 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000679 return false;
680 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000681 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000682 return true;
683}
684
Chris Lattner7b550cc2009-11-06 04:27:31 +0000685static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000686 bool Changed = false;
687 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
688 Instruction *I = cast<Instruction>(*UI++);
689 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
690 LI->setOperand(0, NewV);
691 Changed = true;
692 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
693 if (SI->getOperand(1) == V) {
694 SI->setOperand(1, NewV);
695 Changed = true;
696 }
697 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000698 CallSite CS(I);
699 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000700 // Calling through the pointer! Turn into a direct call, but be careful
701 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000702 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000703 Changed = true;
704 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000705 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
706 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000707 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000708 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000709 }
710
711 if (PassedAsArg) {
712 // Being passed as an argument also. Be careful to not invalidate UI!
713 UI = V->use_begin();
714 }
715 }
716 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
717 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000718 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000719 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000720 if (CI->use_empty()) {
721 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000722 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000723 }
724 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
725 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000726 SmallVector<Constant*, 8> Idxs;
727 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000728 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
729 i != e; ++i)
730 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000731 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000732 else
733 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000734 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000735 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000736 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Chris Lattner7b550cc2009-11-06 04:27:31 +0000737 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000738 if (GEPI->use_empty()) {
739 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000740 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000741 }
742 }
743 }
744
745 return Changed;
746}
747
748
749/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
750/// value stored into it. If there are uses of the loaded value that would trap
751/// if the loaded value is dynamically null, then we know that they cannot be
752/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000753static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000754 bool Changed = false;
755
Chris Lattner92c6bd22009-01-14 00:12:58 +0000756 // Keep track of whether we are able to remove all the uses of the global
757 // other than the store that defines it.
758 bool AllNonStoreUsesGone = true;
759
Chris Lattner708148e2004-10-10 23:14:11 +0000760 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000761 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
762 User *GlobalUser = *GUI++;
763 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000764 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000765 // If we were able to delete all uses of the loads
766 if (LI->use_empty()) {
767 LI->eraseFromParent();
768 Changed = true;
769 } else {
770 AllNonStoreUsesGone = false;
771 }
772 } else if (isa<StoreInst>(GlobalUser)) {
773 // Ignore the store that stores "LV" to the global.
774 assert(GlobalUser->getOperand(1) == GV &&
775 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000776 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000777 AllNonStoreUsesGone = false;
778
779 // If we get here we could have other crazy uses that are transitively
780 // loaded.
781 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
782 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000783 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000784 }
Chris Lattner708148e2004-10-10 23:14:11 +0000785
786 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000787 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000788 ++NumGlobUses;
789 }
790
Chris Lattner708148e2004-10-10 23:14:11 +0000791 // If we nuked all of the loads, then none of the stores are needed either,
792 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000793 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000794 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000795 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000796 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000797 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000798 ++NumDeleted;
799 }
800 Changed = true;
801 }
802 return Changed;
803}
804
Chris Lattner30ba5692004-10-11 05:54:41 +0000805/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
806/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000807static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000808 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
809 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chris Lattner7b550cc2009-11-06 04:27:31 +0000810 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000811 I->replaceAllUsesWith(NewC);
812
Chris Lattnerd514d822005-02-01 01:23:31 +0000813 // Advance UI to the next non-I use to avoid invalidating it!
814 // Instructions could multiply use V.
815 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000816 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000817 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000818 }
819}
820
821/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
822/// variable, and transforms the program as if it always contained the result of
823/// the specified malloc. Because it is always the result of the specified
824/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000825/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000826static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000827 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000828 const Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000829 ConstantInt *NElements,
Victor Hernandez83d63912009-09-18 22:35:49 +0000830 TargetData* TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000831 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Victor Hernandez83d63912009-09-18 22:35:49 +0000832
Chris Lattnera6874652010-02-25 22:33:52 +0000833 const Type *GlobalType;
834 if (NElements->getZExtValue() == 1)
835 GlobalType = AllocTy;
836 else
837 // If we have an array allocation, the global variable is of an array.
838 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000839
840 // Create the new global variable. The contents of the malloc'd memory is
841 // undefined, so initialize with an undef value.
Victor Hernandez83d63912009-09-18 22:35:49 +0000842 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000843 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000844 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000845 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000846 GV->getName()+".body",
847 GV,
848 GV->isThreadLocal());
849
Chris Lattnera6874652010-02-25 22:33:52 +0000850 // If there are bitcast users of the malloc (which is typical, usually we have
851 // a malloc + bitcast) then replace them with uses of the new global. Update
852 // other users to use the global as well.
853 BitCastInst *TheBC = 0;
854 while (!CI->use_empty()) {
855 Instruction *User = cast<Instruction>(CI->use_back());
856 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
857 if (BCI->getType() == NewGV->getType()) {
858 BCI->replaceAllUsesWith(NewGV);
859 BCI->eraseFromParent();
860 } else {
861 BCI->setOperand(0, NewGV);
862 }
863 } else {
864 if (TheBC == 0)
865 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
866 User->replaceUsesOfWith(CI, TheBC);
867 }
868 }
869
Victor Hernandez83d63912009-09-18 22:35:49 +0000870 Constant *RepValue = NewGV;
871 if (NewGV->getType() != GV->getType()->getElementType())
872 RepValue = ConstantExpr::getBitCast(RepValue,
873 GV->getType()->getElementType());
874
875 // If there is a comparison against null, we will insert a global bool to
876 // keep track of whether the global was initialized yet or not.
877 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000878 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000879 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000880 ConstantInt::getFalse(GV->getContext()),
881 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000882 bool InitBoolUsed = false;
883
884 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000885 while (!GV->use_empty()) {
886 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000887 // The global is initialized when the store to it occurs.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000888 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000889 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000890 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000891 }
Chris Lattnera6874652010-02-25 22:33:52 +0000892
893 LoadInst *LI = cast<LoadInst>(GV->use_back());
894 while (!LI->use_empty()) {
895 Use &LoadUse = LI->use_begin().getUse();
896 if (!isa<ICmpInst>(LoadUse.getUser())) {
897 LoadUse = RepValue;
898 continue;
899 }
900
901 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
902 // Replace the cmp X, 0 with a use of the bool value.
903 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
904 InitBoolUsed = true;
905 switch (ICI->getPredicate()) {
906 default: llvm_unreachable("Unknown ICmp Predicate!");
907 case ICmpInst::ICMP_ULT:
908 case ICmpInst::ICMP_SLT: // X < null -> always false
909 LV = ConstantInt::getFalse(GV->getContext());
910 break;
911 case ICmpInst::ICMP_ULE:
912 case ICmpInst::ICMP_SLE:
913 case ICmpInst::ICMP_EQ:
914 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
915 break;
916 case ICmpInst::ICMP_NE:
917 case ICmpInst::ICMP_UGE:
918 case ICmpInst::ICMP_SGE:
919 case ICmpInst::ICMP_UGT:
920 case ICmpInst::ICMP_SGT:
921 break; // no change.
922 }
923 ICI->replaceAllUsesWith(LV);
924 ICI->eraseFromParent();
925 }
926 LI->eraseFromParent();
927 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000928
929 // If the initialization boolean was used, insert it, otherwise delete it.
930 if (!InitBoolUsed) {
931 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000932 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000933 delete InitBool;
934 } else
935 GV->getParent()->getGlobalList().insert(GV, InitBool);
936
Chris Lattnera6874652010-02-25 22:33:52 +0000937 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000938 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000939 CI->eraseFromParent();
940
941 // To further other optimizations, loop over all users of NewGV and try to
942 // constant prop them. This will promote GEP instructions with constant
943 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000944 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000945 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000946 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000947
948 return NewGV;
949}
950
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000951/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
952/// to make sure that there are no complex uses of V. We permit simple things
953/// like dereferencing the pointer, but not storing through the address, unless
954/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000955static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
956 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000957 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000958 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000959 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000960 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000961
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000962 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
963 continue; // Fine, ignore.
964 }
965
Gabor Greif0b520db2010-04-06 18:58:22 +0000966 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000967 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
968 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000969 continue; // Otherwise, storing through it, or storing into GV... fine.
970 }
971
Chris Lattnera2fb2342010-04-10 18:19:22 +0000972 // Must index into the array and into the struct.
973 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000974 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000975 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000976 continue;
977 }
978
Gabor Greif0b520db2010-04-06 18:58:22 +0000979 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000980 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
981 // cycles.
982 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000983 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
984 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000985 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000986 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000987
Gabor Greif0b520db2010-04-06 18:58:22 +0000988 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000989 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
990 return false;
991 continue;
992 }
993
994 return false;
995 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000996 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000997}
998
Chris Lattner86395032006-09-30 23:32:09 +0000999/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1000/// somewhere. Transform all uses of the allocation into loads from the
1001/// global and uses of the resultant pointer. Further, delete the store into
1002/// GV. This assumes that these value pass the
1003/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1004static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1005 GlobalVariable *GV) {
1006 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001007 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1008 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001009 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1010 // If this is the store of the allocation into the global, remove it.
1011 if (SI->getOperand(1) == GV) {
1012 SI->eraseFromParent();
1013 continue;
1014 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001015 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1016 // Insert the load in the corresponding predecessor, not right before the
1017 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001018 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001019 } else if (isa<BitCastInst>(U)) {
1020 // Must be bitcast between the malloc and store to initialize the global.
1021 ReplaceUsesOfMallocWithGlobal(U, GV);
1022 U->eraseFromParent();
1023 continue;
1024 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1025 // If this is a "GEP bitcast" and the user is a store to the global, then
1026 // just process it as a bitcast.
1027 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1028 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1029 if (SI->getOperand(1) == GV) {
1030 // Must be bitcast GEP between the malloc and store to initialize
1031 // the global.
1032 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1033 GEPI->eraseFromParent();
1034 continue;
1035 }
Chris Lattner86395032006-09-30 23:32:09 +00001036 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001037
Chris Lattner86395032006-09-30 23:32:09 +00001038 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001039 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001040 U->replaceUsesOfWith(Alloc, NL);
1041 }
1042}
1043
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001044/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1045/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1046/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001047static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001048 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1049 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001050 // We permit two users of the load: setcc comparing against the null
1051 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001052 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1053 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001054 const Instruction *User = cast<Instruction>(*UI);
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001055
1056 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001057 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001058 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1059 return false;
1060 continue;
1061 }
1062
1063 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001064 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001065 // Must index into the array and into the struct.
1066 if (GEPI->getNumOperands() < 3)
1067 return false;
1068
1069 // Otherwise the GEP is ok.
1070 continue;
1071 }
1072
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001073 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001074 if (!LoadUsingPHIsPerLoad.insert(PN))
1075 // This means some phi nodes are dependent on each other.
1076 // Avoid infinite looping!
1077 return false;
1078 if (!LoadUsingPHIs.insert(PN))
1079 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001080 continue;
1081
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001082 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001083 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1084 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001085 return false;
1086
1087 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001088 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001089
1090 // Otherwise we don't know what this is, not ok.
1091 return false;
1092 }
1093
1094 return true;
1095}
1096
1097
1098/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1099/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001100static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001101 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001102 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1103 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001104 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1105 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001106 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001107 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1108 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001109 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001110 LoadUsingPHIsPerLoad.clear();
1111 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001112
1113 // If we reach here, we know that all uses of the loads and transitive uses
1114 // (through PHI nodes) are simple enough to transform. However, we don't know
1115 // that all inputs the to the PHI nodes are in the same equivalence sets.
1116 // Check to verify that all operands of the PHIs are either PHIS that can be
1117 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001118 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1119 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001120 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001121 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1122 Value *InVal = PN->getIncomingValue(op);
1123
1124 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001125 if (InVal == StoredVal) continue;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001126
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001127 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001128 // One of the PHIs in our set is (optimistically) ok.
1129 if (LoadUsingPHIs.count(InPN))
1130 continue;
1131 return false;
1132 }
1133
1134 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001135 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001136 if (LI->getOperand(0) == GV)
1137 continue;
1138
1139 // UNDEF? NULL?
1140
1141 // Anything else is rejected.
1142 return false;
1143 }
1144 }
1145
Chris Lattner86395032006-09-30 23:32:09 +00001146 return true;
1147}
1148
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001149static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1150 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001151 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001152 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1153
1154 if (FieldNo >= FieldVals.size())
1155 FieldVals.resize(FieldNo+1);
1156
1157 // If we already have this value, just reuse the previously scalarized
1158 // version.
1159 if (Value *FieldVal = FieldVals[FieldNo])
1160 return FieldVal;
1161
1162 // Depending on what instruction this is, we have several cases.
1163 Value *Result;
1164 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1165 // This is a scalarized version of the load from the global. Just create
1166 // a new Load of the scalarized global.
1167 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1168 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001169 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001170 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001171 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1172 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1173 // field.
1174 const StructType *ST =
1175 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1176
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001177 Result =
Owen Andersondebcb012009-07-29 22:17:13 +00001178 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001179 PN->getName()+".f"+Twine(FieldNo), PN);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001180 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1181 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001182 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001183 Result = 0;
1184 }
1185
1186 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001187}
1188
Chris Lattner330245e2007-09-13 17:29:05 +00001189/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1190/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001191static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1192 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001193 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001194 // If this is a comparison against null, handle it.
1195 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1196 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1197 // If we have a setcc of the loaded pointer, we can use a setcc of any
1198 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001199 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001200 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner330245e2007-09-13 17:29:05 +00001201
Owen Anderson333c4002009-07-09 23:48:35 +00001202 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Owen Andersona7235ea2009-07-31 20:28:14 +00001203 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001204 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001205 SCI->replaceAllUsesWith(New);
1206 SCI->eraseFromParent();
1207 return;
1208 }
1209
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001210 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001211 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1212 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1213 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001214
Chris Lattnera637a8b2007-09-13 18:00:31 +00001215 // Load the pointer for this field.
1216 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001217 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001218 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001219
1220 // Create the new GEP idx vector.
1221 SmallVector<Value*, 8> GEPIdx;
1222 GEPIdx.push_back(GEPI->getOperand(1));
1223 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1224
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001225 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1226 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001227 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001228 GEPI->replaceAllUsesWith(NGEPI);
1229 GEPI->eraseFromParent();
1230 return;
1231 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001232
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001233 // Recursively transform the users of PHI nodes. This will lazily create the
1234 // PHIs that are needed for individual elements. Keep track of what PHIs we
1235 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1236 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1237 // already been seen first by another load, so its uses have already been
1238 // processed.
1239 PHINode *PN = cast<PHINode>(LoadUser);
1240 bool Inserted;
1241 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1242 tie(InsertPos, Inserted) =
1243 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1244 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001245
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001246 // If this is the first time we've seen this PHI, recursively process all
1247 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001248 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1249 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001250 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001251 }
Chris Lattner330245e2007-09-13 17:29:05 +00001252}
1253
Chris Lattner86395032006-09-30 23:32:09 +00001254/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1255/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1256/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001257/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001258static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001259 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001260 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001261 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001262 UI != E; ) {
1263 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001264 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001265 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001266
1267 if (Load->use_empty()) {
1268 Load->eraseFromParent();
1269 InsertedScalarizedValues.erase(Load);
1270 }
Chris Lattner86395032006-09-30 23:32:09 +00001271}
1272
Victor Hernandez83d63912009-09-18 22:35:49 +00001273/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1274/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001275static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1276 Value* NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001277 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Victor Hernandez83d63912009-09-18 22:35:49 +00001278 const Type* MAT = getMallocAllocatedType(CI);
1279 const StructType *STy = cast<StructType>(MAT);
1280
1281 // There is guaranteed to be at least one use of the malloc (storing
1282 // it into GV). If there are other uses, change them to be uses of
1283 // the global to simplify later code. This also deletes the store
1284 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001285 ReplaceUsesOfMallocWithGlobal(CI, GV);
1286
Victor Hernandez83d63912009-09-18 22:35:49 +00001287 // Okay, at this point, there are no users of the malloc. Insert N
1288 // new mallocs at the same place as CI, and N globals.
1289 std::vector<Value*> FieldGlobals;
1290 std::vector<Value*> FieldMallocs;
1291
1292 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1293 const Type *FieldTy = STy->getElementType(FieldNo);
1294 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1295
1296 GlobalVariable *NGV =
1297 new GlobalVariable(*GV->getParent(),
1298 PFieldTy, false, GlobalValue::InternalLinkage,
1299 Constant::getNullValue(PFieldTy),
1300 GV->getName() + ".f" + Twine(FieldNo), GV,
1301 GV->isThreadLocal());
1302 FieldGlobals.push_back(NGV);
1303
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001304 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Victor Hernandez631f3c02009-11-07 00:41:19 +00001305 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001306 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez631f3c02009-11-07 00:41:19 +00001307 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001308 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1309 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001310 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001311 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001312 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001313 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001314 }
1315
1316 // The tricky aspect of this transformation is handling the case when malloc
1317 // fails. In the original code, malloc failing would set the result pointer
1318 // of malloc to null. In this case, some mallocs could succeed and others
1319 // could fail. As such, we emit code that looks like this:
1320 // F0 = malloc(field0)
1321 // F1 = malloc(field1)
1322 // F2 = malloc(field2)
1323 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1324 // if (F0) { free(F0); F0 = 0; }
1325 // if (F1) { free(F1); F1 = 0; }
1326 // if (F2) { free(F2); F2 = 0; }
1327 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001328 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001329 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1330 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001331 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001332 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001333 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1334 Constant::getNullValue(FieldMallocs[i]->getType()),
1335 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001336 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001337 }
1338
1339 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001340 BasicBlock *OrigBB = CI->getParent();
1341 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Victor Hernandez83d63912009-09-18 22:35:49 +00001342
1343 // Create the block to check the first condition. Put all these blocks at the
1344 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001345 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1346 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001347 OrigBB->getParent());
1348
1349 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1350 // branch on RunningOr.
1351 OrigBB->getTerminator()->eraseFromParent();
1352 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1353
1354 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1355 // pointer, because some may be null while others are not.
1356 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1357 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1358 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1359 Constant::getNullValue(GVVal->getType()),
1360 "tmp");
Chris Lattner7b550cc2009-11-06 04:27:31 +00001361 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001362 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001363 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001364 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001365 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1366 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001367
1368 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001369 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001370 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1371 FreeBlock);
1372 BranchInst::Create(NextBlock, FreeBlock);
1373
1374 NullPtrBlock = NextBlock;
1375 }
1376
1377 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001378
1379 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001380 CI->eraseFromParent();
1381
1382 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1383 /// update all uses of the load, keep track of what scalarized loads are
1384 /// inserted for a given load.
1385 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1386 InsertedScalarizedValues[GV] = FieldGlobals;
1387
1388 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1389
1390 // Okay, the malloc site is completely handled. All of the uses of GV are now
1391 // loads, and all uses of those loads are simple. Rewrite them to use loads
1392 // of the per-field globals instead.
1393 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1394 Instruction *User = cast<Instruction>(*UI++);
1395
1396 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001397 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001398 continue;
1399 }
1400
1401 // Must be a store of null.
1402 StoreInst *SI = cast<StoreInst>(User);
1403 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1404 "Unexpected heap-sra user!");
1405
1406 // Insert a store of null into each global.
1407 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1408 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1409 Constant *Null = Constant::getNullValue(PT->getElementType());
1410 new StoreInst(Null, FieldGlobals[i], SI);
1411 }
1412 // Erase the original store.
1413 SI->eraseFromParent();
1414 }
1415
1416 // While we have PHIs that are interesting to rewrite, do it.
1417 while (!PHIsToRewrite.empty()) {
1418 PHINode *PN = PHIsToRewrite.back().first;
1419 unsigned FieldNo = PHIsToRewrite.back().second;
1420 PHIsToRewrite.pop_back();
1421 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1422 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1423
1424 // Add all the incoming values. This can materialize more phis.
1425 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1426 Value *InVal = PN->getIncomingValue(i);
1427 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001428 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001429 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1430 }
1431 }
1432
1433 // Drop all inter-phi links and any loads that made it this far.
1434 for (DenseMap<Value*, std::vector<Value*> >::iterator
1435 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1436 I != E; ++I) {
1437 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1438 PN->dropAllReferences();
1439 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1440 LI->dropAllReferences();
1441 }
1442
1443 // Delete all the phis and loads now that inter-references are dead.
1444 for (DenseMap<Value*, std::vector<Value*> >::iterator
1445 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1446 I != E; ++I) {
1447 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1448 PN->eraseFromParent();
1449 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1450 LI->eraseFromParent();
1451 }
1452
1453 // The old global is now dead, remove it.
1454 GV->eraseFromParent();
1455
1456 ++NumHeapSRA;
1457 return cast<GlobalVariable>(FieldGlobals[0]);
1458}
1459
Chris Lattnere61d0a62008-12-15 21:02:25 +00001460/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1461/// pointer global variable with a single value stored it that is a malloc or
1462/// cast of malloc.
1463static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001464 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001465 const Type *AllocTy,
Victor Hernandez83d63912009-09-18 22:35:49 +00001466 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001467 TargetData *TD) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001468 if (!TD)
1469 return false;
1470
Victor Hernandez83d63912009-09-18 22:35:49 +00001471 // If this is a malloc of an abstract type, don't touch it.
1472 if (!AllocTy->isSized())
1473 return false;
1474
1475 // We can't optimize this global unless all uses of it are *known* to be
1476 // of the malloc value, not of the null initializer value (consider a use
1477 // that compares the global's value against zero to see if the malloc has
1478 // been reached). To do this, we check to see if all uses of the global
1479 // would trap if the global were null: this proves that they must all
1480 // happen after the malloc.
1481 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1482 return false;
1483
1484 // We can't optimize this if the malloc itself is used in a complex way,
1485 // for example, being stored into multiple globals. This allows the
1486 // malloc to be stored into the specified global, loaded setcc'd, and
1487 // GEP'd. These are all things we could transform to using the global
1488 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001489 SmallPtrSet<const PHINode*, 8> PHIs;
1490 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1491 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001492
1493 // If we have a global that is only initialized with a fixed size malloc,
1494 // transform the program to use global memory instead of malloc'd memory.
1495 // This eliminates dynamic allocation, avoids an indirection accessing the
1496 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001497 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001498 Value *NElems = getMallocArraySize(CI, TD, true);
1499 if (!NElems)
1500 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001501
Evan Cheng86cd4452010-04-14 20:52:55 +00001502 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1503 // Restrict this transformation to only working on small allocations
1504 // (2048 bytes currently), as we don't want to introduce a 16M global or
1505 // something.
1506 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1507 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1508 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001509 }
Evan Cheng86cd4452010-04-14 20:52:55 +00001510
1511 // If the allocation is an array of structures, consider transforming this
1512 // into multiple malloc'd arrays, one for each field. This is basically
1513 // SRoA for malloc'd memory.
1514
1515 // If this is an allocation of a fixed size array of structs, analyze as a
1516 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001517 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Evan Cheng86cd4452010-04-14 20:52:55 +00001518 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1519 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001520
Evan Cheng86cd4452010-04-14 20:52:55 +00001521 const StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1522 if (!AllocSTy)
1523 return false;
1524
1525 // This the structure has an unreasonable number of fields, leave it
1526 // alone.
1527 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1528 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1529
1530 // If this is a fixed size array, transform the Malloc to be an alloc of
1531 // structs. malloc [100 x struct],1 -> malloc struct, 100
1532 if (const ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1533 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1534 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1535 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1536 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1537 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1538 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001539 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001540 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1541 CI->replaceAllUsesWith(Cast);
1542 CI->eraseFromParent();
1543 CI = dyn_cast<BitCastInst>(Malloc) ?
1544 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1545 }
1546
1547 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1548 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001549 }
1550
1551 return false;
1552}
1553
Chris Lattner9b34a612004-10-09 21:48:45 +00001554// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1555// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001556static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001557 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001558 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001559 // Ignore no-op GEPs and bitcasts.
1560 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001561
Chris Lattner708148e2004-10-10 23:14:11 +00001562 // If we are dealing with a pointer global that is initialized to null and
1563 // only has one (non-null) value stored into it, then we can optimize any
1564 // users of the loaded value (often calls and loads) that would trap if the
1565 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001566 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001567 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001568 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1569 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001570 SOVC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001571 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001572
Chris Lattner708148e2004-10-10 23:14:11 +00001573 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001574 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001575 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001576 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001577 const Type* MallocType = getMallocAllocatedType(CI);
1578 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
1579 GVI, TD))
1580 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001581 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001582 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001583
Chris Lattner9b34a612004-10-09 21:48:45 +00001584 return false;
1585}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001586
Chris Lattner58e44f42008-01-14 01:17:44 +00001587/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1588/// two values ever stored into GV are its initializer and OtherVal. See if we
1589/// can shrink the global into a boolean and select between the two values
1590/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001591static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001592 const Type *GVElType = GV->getType()->getElementType();
1593
1594 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001595 // an FP value, pointer or vector, don't do this optimization because a select
1596 // between them is very expensive and unlikely to lead to later
1597 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1598 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001599 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001600 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001601 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001602 return false;
1603
1604 // Walk the use list of the global seeing if all the uses are load or store.
1605 // If there is anything else, bail out.
1606 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel771281f2009-03-06 01:39:36 +00001607 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattner58e44f42008-01-14 01:17:44 +00001608 return false;
1609
David Greene3215b0e2010-01-05 01:28:05 +00001610 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Chris Lattner58e44f42008-01-14 01:17:44 +00001611
Chris Lattner96a86b22004-12-12 05:53:50 +00001612 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001613 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1614 false,
1615 GlobalValue::InternalLinkage,
1616 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001617 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001618 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001619 GV->getParent()->getGlobalList().insert(GV, NewGV);
1620
1621 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001622 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001623 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001624
1625 // If initialized to zero and storing one into the global, we can use a cast
1626 // instead of a select to synthesize the desired value.
1627 bool IsOneZero = false;
1628 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001629 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001630
1631 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001632 Instruction *UI = cast<Instruction>(GV->use_back());
1633 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001634 // Change the store into a boolean store.
1635 bool StoringOther = SI->getOperand(0) == OtherVal;
1636 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001637 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001638 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001639 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1640 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001641 else {
1642 // Otherwise, we are storing a previously loaded copy. To do this,
1643 // change the copy from copying the original value to just copying the
1644 // bool.
1645 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1646
Gabor Greif9e4f2432010-06-24 14:42:01 +00001647 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001648 // select instruction. If not, it will be a load of the original
1649 // global.
1650 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1651 assert(LI->getOperand(0) == GV && "Not a copy!");
1652 // Insert a new load, to preserve the saved value.
1653 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1654 } else {
1655 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1656 "This is not a form that we understand!");
1657 StoreVal = StoredVal->getOperand(0);
1658 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1659 }
1660 }
1661 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001662 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001663 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001664 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001665 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001666 Value *NSI;
1667 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001668 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001669 else
Gabor Greif051a9502008-04-06 20:25:17 +00001670 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001671 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001672 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001673 }
1674 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001675 }
1676
1677 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001678 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001679}
1680
1681
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001682/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1683/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001684bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001685 Module::global_iterator &GVI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001686 SmallPtrSet<const PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001687 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001688 GV->removeDeadConstantUsers();
1689
1690 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001691 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001692 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001693 ++NumDeleted;
1694 return true;
1695 }
1696
1697 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001698#if 0
David Greene3215b0e2010-01-05 01:28:05 +00001699 DEBUG(dbgs() << "Global: " << *GV);
1700 DEBUG(dbgs() << " isLoaded = " << GS.isLoaded << "\n");
1701 DEBUG(dbgs() << " StoredType = ");
Chris Lattnercff16732006-09-30 19:40:30 +00001702 switch (GS.StoredType) {
David Greene3215b0e2010-01-05 01:28:05 +00001703 case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break;
1704 case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n");
Victor Hernandez631f3c02009-11-07 00:41:19 +00001705 break;
David Greene3215b0e2010-01-05 01:28:05 +00001706 case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break;
1707 case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break;
Chris Lattnercff16732006-09-30 19:40:30 +00001708 }
1709 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
David Greene3215b0e2010-01-05 01:28:05 +00001710 DEBUG(dbgs() << " StoredOnceValue = " << *GS.StoredOnceValue << "\n");
Chris Lattnercff16732006-09-30 19:40:30 +00001711 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Gabor Greif27236912010-04-07 18:59:26 +00001712 DEBUG(dbgs() << " AccessingFunction = "
1713 << GS.AccessingFunction->getName() << "\n");
David Greene3215b0e2010-01-05 01:28:05 +00001714 DEBUG(dbgs() << " HasMultipleAccessingFunctions = "
Victor Hernandez631f3c02009-11-07 00:41:19 +00001715 << GS.HasMultipleAccessingFunctions << "\n");
David Greene3215b0e2010-01-05 01:28:05 +00001716 DEBUG(dbgs() << " HasNonInstructionUser = "
Victor Hernandez631f3c02009-11-07 00:41:19 +00001717 << GS.HasNonInstructionUser<<"\n");
David Greene3215b0e2010-01-05 01:28:05 +00001718 DEBUG(dbgs() << "\n");
Chris Lattnercff16732006-09-30 19:40:30 +00001719#endif
1720
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001721 // If this is a first class global and has only one accessing function
1722 // and this function is main (which we know is not recursive we can make
1723 // this global a local variable) we replace the global with a local alloca
1724 // in this function.
1725 //
Dan Gohman399101a2008-05-23 00:17:26 +00001726 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001727 // are just replacing static memory to stack memory.
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001728 //
1729 // If the global is in different address space, don't bring it to stack.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001730 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001731 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001732 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001733 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001734 GS.AccessingFunction->hasExternalLinkage() &&
1735 GV->getType()->getAddressSpace() == 0) {
David Greene3215b0e2010-01-05 01:28:05 +00001736 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001737 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1738 ->getEntryBlock().begin());
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001739 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001740 // FIXME: Pass Global's alignment when globals have alignment
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001741 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001742 if (!isa<UndefValue>(GV->getInitializer()))
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001743 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001744
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001745 GV->replaceAllUsesWith(Alloca);
1746 GV->eraseFromParent();
1747 ++NumLocalized;
1748 return true;
1749 }
Chris Lattnercff16732006-09-30 19:40:30 +00001750
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001751 // If the global is never loaded (but may be stored to), it is dead.
1752 // Delete it now.
1753 if (!GS.isLoaded) {
David Greene3215b0e2010-01-05 01:28:05 +00001754 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattner930f4752004-10-09 03:32:52 +00001755
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001756 // Delete any stores we can find to the global. We may not be able to
1757 // make it completely dead though.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001758 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001759
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001760 // If the global is dead now, delete it.
1761 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001762 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001763 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001764 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001765 }
Chris Lattner930f4752004-10-09 03:32:52 +00001766 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001767
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001768 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
David Greene3215b0e2010-01-05 01:28:05 +00001769 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001770 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001771
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001772 // Clean up any obviously simplifiable users now.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001773 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001774
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001775 // If the global is dead now, just nuke it.
1776 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001777 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
Chris Lattnerbdff5482009-08-23 04:37:46 +00001778 << "all users and delete global!\n");
Chris Lattner7a7ed022004-10-16 18:09:00 +00001779 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001780 ++NumDeleted;
1781 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001782
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001783 ++NumMarked;
1784 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001785 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Dan Gohman7eb28f32009-08-14 00:11:03 +00001786 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
Chris Lattner7b550cc2009-11-06 04:27:31 +00001787 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
Dan Gohman7eb28f32009-08-14 00:11:03 +00001788 GVI = FirstNewGV; // Don't skip the newly produced globals!
1789 return true;
1790 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001791 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001792 // If the initial value for the global was an undef value, and if only
1793 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001794 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001795 // global. This allows us to mark it constant.
1796 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1797 if (isa<UndefValue>(GV->getInitializer())) {
1798 // Change the initial value here.
1799 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001800
Chris Lattner96a86b22004-12-12 05:53:50 +00001801 // Clean up any obviously simplifiable users now.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001802 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001803
Chris Lattner96a86b22004-12-12 05:53:50 +00001804 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001805 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Chris Lattnerbdff5482009-08-23 04:37:46 +00001806 << "simplify all users and delete global!\n");
Chris Lattner96a86b22004-12-12 05:53:50 +00001807 GV->eraseFromParent();
1808 ++NumDeleted;
1809 } else {
1810 GVI = GV;
1811 }
1812 ++NumSubstitute;
1813 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001814 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001815
Chris Lattner9b34a612004-10-09 21:48:45 +00001816 // Try to optimize globals based on the knowledge that only one value
1817 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001818 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001819 getAnalysisIfAvailable<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001820 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001821
1822 // Otherwise, if the global was not a boolean, we can shrink it to be a
1823 // boolean.
1824 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001825 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001826 ++NumShrunkToBool;
1827 return true;
1828 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001829 }
1830 }
1831 return false;
1832}
1833
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001834/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1835/// function, changing them to FastCC.
1836static void ChangeCalleesToFastCall(Function *F) {
1837 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001838 CallSite User(cast<Instruction>(*UI));
1839 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001840 }
1841}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001842
Devang Patel05988662008-09-25 21:00:45 +00001843static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001844 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001845 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001846 continue;
1847
Duncan Sands548448a2008-02-18 17:32:13 +00001848 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001849 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001850 }
1851
1852 return Attrs;
1853}
1854
1855static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001856 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001857 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001858 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001859 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001860 }
1861}
1862
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001863bool GlobalOpt::OptimizeFunctions(Module &M) {
1864 bool Changed = false;
1865 // Optimize functions.
1866 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1867 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001868 // Functions without names cannot be referenced outside this module.
1869 if (!F->hasName() && !F->isDeclaration())
1870 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001871 F->removeDeadConstantUsers();
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001872 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1873 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001874 Changed = true;
1875 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001876 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001877 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001878 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001879 // If this function has C calling conventions, is not a varargs
1880 // function, and is only called directly, promote it to use the Fast
1881 // calling convention.
1882 F->setCallingConv(CallingConv::Fast);
1883 ChangeCalleesToFastCall(F);
1884 ++NumFastCallFns;
1885 Changed = true;
1886 }
1887
Devang Patel05988662008-09-25 21:00:45 +00001888 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001889 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001890 // The function is not used by a trampoline intrinsic, so it is safe
1891 // to remove the 'nest' attribute.
1892 RemoveNestAttribute(F);
1893 ++NumNestRemoved;
1894 Changed = true;
1895 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001896 }
1897 }
1898 return Changed;
1899}
1900
1901bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1902 bool Changed = false;
1903 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1904 GVI != E; ) {
1905 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001906 // Global variables without names cannot be referenced outside this module.
1907 if (!GV->hasName() && !GV->isDeclaration())
1908 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001909 // Simplify the initializer.
1910 if (GV->hasInitializer())
1911 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohmanf860db22010-04-02 03:04:37 +00001912 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman01b97dd2009-11-23 16:22:21 +00001913 Constant *New = ConstantFoldConstantExpression(CE, TD);
1914 if (New && New != CE)
1915 GV->setInitializer(New);
1916 }
1917 // Do more involved optimizations if the global is internal.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001918 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001919 GV->hasInitializer())
1920 Changed |= ProcessInternalGlobal(GV, GVI);
1921 }
1922 return Changed;
1923}
1924
1925/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1926/// initializers have an init priority of 65535.
1927GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001928 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1929 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001930 if (I->getName() == "llvm.global_ctors") {
1931 // Found it, verify it's an array of { int, void()* }.
1932 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1933 if (!ATy) return 0;
1934 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1935 if (!STy || STy->getNumElements() != 2 ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001936 !STy->getElementType(0)->isIntegerTy(32)) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001937 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1938 if (!PFTy) return 0;
1939 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
Benjamin Kramerf0127052010-01-05 13:12:22 +00001940 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001941 FTy->isVarArg() || FTy->getNumParams() != 0)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001942 return 0;
1943
1944 // Verify that the initializer is simple enough for us to handle.
Dan Gohman82555732009-08-19 18:20:44 +00001945 if (!I->hasDefinitiveInitializer()) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001946 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1947 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001948 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1949 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001950 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1951 continue;
1952
1953 // Must have a function or null ptr.
1954 if (!isa<Function>(CS->getOperand(1)))
1955 return 0;
1956
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001957 // Init priority must be standard.
1958 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001959 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001960 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001961 } else {
1962 return 0;
1963 }
1964
1965 return I;
1966 }
1967 return 0;
1968}
1969
Chris Lattnerdb973e62005-09-26 02:31:18 +00001970/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1971/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001972static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1973 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1974 std::vector<Function*> Result;
1975 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001976 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1977 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001978 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1979 }
1980 return Result;
1981}
1982
Chris Lattnerdb973e62005-09-26 02:31:18 +00001983/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1984/// specified array, returning the new global to use.
1985static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001986 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001987 // If we made a change, reassemble the initializer list.
1988 std::vector<Constant*> CSVals;
Chris Lattner7b550cc2009-11-06 04:27:31 +00001989 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001990 CSVals.push_back(0);
1991
1992 // Create the new init list.
1993 std::vector<Constant*> CAList;
1994 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001995 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001996 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001997 } else {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001998 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
1999 false);
Owen Andersondebcb012009-07-29 22:17:13 +00002000 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002001 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002002 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2003 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002004 }
Chris Lattner7b550cc2009-11-06 04:27:31 +00002005 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002006 }
2007
2008 // Create the array initializer.
2009 const Type *StructTy =
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002010 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson1fd70962009-07-28 18:32:17 +00002011 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002012 CAList.size()), CAList);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002013
2014 // If we didn't change the number of elements, don't create a new GV.
2015 if (CA->getType() == GCL->getInitializer()->getType()) {
2016 GCL->setInitializer(CA);
2017 return GCL;
2018 }
2019
2020 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002021 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002022 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002023 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002024 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002025 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002026
2027 // Nuke the old list, replacing any uses with the new one.
2028 if (!GCL->use_empty()) {
2029 Constant *V = NGV;
2030 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002031 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002032 GCL->replaceAllUsesWith(V);
2033 }
2034 GCL->eraseFromParent();
2035
2036 if (Ctors.size())
2037 return NGV;
2038 else
2039 return 0;
2040}
Chris Lattner79c11012005-09-26 04:44:35 +00002041
2042
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002043static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00002044 Value *V) {
2045 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2046 Constant *R = ComputedValues[V];
2047 assert(R && "Reference to an uncomputed value!");
2048 return R;
2049}
2050
2051/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2052/// enough for us to understand. In particular, if it is a cast of something,
2053/// we punt. We basically just support direct accesses to globals and GEP's of
2054/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002055static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002056 // Conservatively, avoid aggregate types. This is because we don't
2057 // want to worry about them partially overlapping other stores.
2058 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2059 return false;
2060
Dan Gohmanfd54a892009-09-07 22:31:26 +00002061 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2062 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2063 // external globals.
2064 return GV->hasDefinitiveInitializer();
2065
Chris Lattner798b4d52005-09-26 06:52:44 +00002066 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2067 // Handle a constantexpr gep.
2068 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002069 isa<GlobalVariable>(CE->getOperand(0)) &&
2070 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002071 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohmanfd54a892009-09-07 22:31:26 +00002072 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2073 // external globals.
2074 if (!GV->hasDefinitiveInitializer())
2075 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002076
Dan Gohman80bdc962009-09-07 22:44:55 +00002077 // The first index must be zero.
Dan Gohmane6992f72009-09-10 23:37:55 +00002078 ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002079 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002080
2081 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002082 // notional bounds of the corresponding static array types.
2083 if (!CE->isGEPWithNoNotionalOverIndexing())
2084 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002085
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002086 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002087 }
Chris Lattner79c11012005-09-26 04:44:35 +00002088 return false;
2089}
2090
Chris Lattner798b4d52005-09-26 06:52:44 +00002091/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2092/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2093/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2094static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002095 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002096 // Base case of the recursion.
2097 if (OpNo == Addr->getNumOperands()) {
2098 assert(Val->getType() == Init->getType() && "Type mismatch!");
2099 return Val;
2100 }
2101
Chris Lattnera0e9a242010-01-07 01:16:21 +00002102 std::vector<Constant*> Elts;
Chris Lattner798b4d52005-09-26 06:52:44 +00002103 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002104
2105 // Break up the constant into its elements.
2106 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002107 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2108 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002109 } else if (isa<ConstantAggregateZero>(Init)) {
2110 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002111 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002112 } else if (isa<UndefValue>(Init)) {
2113 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002114 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002115 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002116 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002117 " ConstantFoldLoadThroughGEPConstantExpr");
2118 }
2119
2120 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002121 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2122 unsigned Idx = CU->getZExtValue();
2123 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002124 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00002125
2126 // Return the modified struct.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002127 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2128 STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002129 } else {
2130 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002131 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002132
Chris Lattnera0e9a242010-01-07 01:16:21 +00002133 uint64_t NumElts;
2134 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2135 NumElts = ATy->getNumElements();
2136 else
2137 NumElts = cast<VectorType>(InitTy)->getNumElements();
2138
2139
Chris Lattner798b4d52005-09-26 06:52:44 +00002140 // Break up the array into elements.
Chris Lattner798b4d52005-09-26 06:52:44 +00002141 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002142 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2143 Elts.push_back(cast<Constant>(*i));
Chris Lattner4039bd02010-01-07 01:20:20 +00002144 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2145 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2146 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002147 } else if (isa<ConstantAggregateZero>(Init)) {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002148 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002149 } else {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002150 assert(isa<UndefValue>(Init) && "This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002151 " ConstantFoldLoadThroughGEPConstantExpr");
Chris Lattnera0e9a242010-01-07 01:16:21 +00002152 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002153 }
2154
Chris Lattnera0e9a242010-01-07 01:16:21 +00002155 assert(CI->getZExtValue() < NumElts);
Reid Spencerb83eb642006-10-20 07:07:24 +00002156 Elts[CI->getZExtValue()] =
Chris Lattner7b550cc2009-11-06 04:27:31 +00002157 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnera0e9a242010-01-07 01:16:21 +00002158
Duncan Sands1df98592010-02-16 11:11:14 +00002159 if (Init->getType()->isArrayTy())
Chris Lattnera0e9a242010-01-07 01:16:21 +00002160 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2161 else
2162 return ConstantVector::get(&Elts[0], Elts.size());
Chris Lattner798b4d52005-09-26 06:52:44 +00002163 }
2164}
2165
Chris Lattner79c11012005-09-26 04:44:35 +00002166/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2167/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002168static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002169 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2170 assert(GV->hasInitializer());
2171 GV->setInitializer(Val);
2172 return;
2173 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002174
Chris Lattner798b4d52005-09-26 06:52:44 +00002175 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2176 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002177 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002178}
2179
Chris Lattner562a0552005-09-26 05:16:34 +00002180/// ComputeLoadResult - Return the value that would be computed by a load from
2181/// P after the stores reflected by 'memory' have been performed. If we can't
2182/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002183static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002184 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002185 // If this memory location has been recently stored, use the stored value: it
2186 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002187 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002188 if (I != Memory.end()) return I->second;
2189
2190 // Access it.
2191 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002192 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002193 return GV->getInitializer();
2194 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002195 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002196
2197 // Handle a constantexpr getelementptr.
2198 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2199 if (CE->getOpcode() == Instruction::GetElementPtr &&
2200 isa<GlobalVariable>(CE->getOperand(0))) {
2201 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002202 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002203 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002204 }
2205
2206 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002207}
2208
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002209/// EvaluateFunction - Evaluate a call to function F, returning true if
2210/// successful, false if we can't evaluate it. ActualArgs contains the formal
2211/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002212static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002213 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002214 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002215 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002216 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002217 // Check to see if this function is already executing (recursion). If so,
2218 // bail out. TODO: we might want to accept limited recursion.
2219 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2220 return false;
2221
2222 CallStack.push_back(F);
2223
Chris Lattner79c11012005-09-26 04:44:35 +00002224 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002225 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002226
2227 // Initialize arguments to the incoming values specified.
2228 unsigned ArgNo = 0;
2229 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2230 ++AI, ++ArgNo)
2231 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002232
Chris Lattnercdf98be2005-09-26 04:57:38 +00002233 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2234 /// we can only evaluate any one basic block at most once. This set keeps
2235 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002236 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002237
Chris Lattner79c11012005-09-26 04:44:35 +00002238 // CurInst - The current instruction we're evaluating.
2239 BasicBlock::iterator CurInst = F->begin()->begin();
2240
2241 // This is the main evaluation loop.
2242 while (1) {
2243 Constant *InstResult = 0;
2244
2245 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002246 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002247 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002248 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002249 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002250 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002251 Constant *Val = getVal(Values, SI->getOperand(0));
2252 MutatedMemory[Ptr] = Val;
2253 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002254 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002255 getVal(Values, BO->getOperand(0)),
2256 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002257 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002258 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002259 getVal(Values, CI->getOperand(0)),
2260 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002261 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002262 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002263 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002264 CI->getType());
2265 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +00002266 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Eric Christopher551754c2010-04-16 23:37:20 +00002267 getVal(Values, SI->getOperand(1)),
2268 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002269 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2270 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002271 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002272 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2273 i != e; ++i)
2274 GEPOps.push_back(getVal(Values, *i));
Dan Gohman4a7e6b72009-09-07 22:34:43 +00002275 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2276 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2277 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002278 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002279 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002280 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002281 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002282 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002283 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002284 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002285 const Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002286 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002287 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002288 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002289 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002290 InstResult = AllocaTmps.back();
2291 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002292
2293 // Debug info can safely be ignored here.
2294 if (isa<DbgInfoIntrinsic>(CI)) {
2295 ++CurInst;
2296 continue;
2297 }
2298
Chris Lattner7cd580f2006-07-07 21:37:01 +00002299 // Cannot handle inline asm.
Gabor Greifa9b23132010-04-20 13:13:04 +00002300 if (isa<InlineAsm>(CI->getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002301
Chris Lattnercd271422005-09-27 04:45:34 +00002302 // Resolve function pointers.
Gabor Greifa9b23132010-04-20 13:13:04 +00002303 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getCalledValue()));
Chris Lattnercd271422005-09-27 04:45:34 +00002304 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002305
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002306 SmallVector<Constant*, 8> Formals;
Gabor Greif9e4f2432010-06-24 14:42:01 +00002307 CallSite CS(CI);
2308 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
Gabor Greif5e463212008-05-29 01:59:18 +00002309 i != e; ++i)
2310 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002311
Reid Spencer5cbf9852007-01-30 20:08:39 +00002312 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002313 // If this is a function we can constant fold, do it.
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002314 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
Chris Lattner6c1f5652007-01-30 23:14:52 +00002315 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002316 InstResult = C;
2317 } else {
2318 return false;
2319 }
2320 } else {
2321 if (Callee->getFunctionType()->isVarArg())
2322 return false;
2323
2324 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002325 // Execute the call, if successful, use the return value.
2326 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2327 MutatedMemory, AllocaTmps))
2328 return false;
2329 InstResult = RetVal;
2330 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002331 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002332 BasicBlock *NewBB = 0;
2333 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2334 if (BI->isUnconditional()) {
2335 NewBB = BI->getSuccessor(0);
2336 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002337 ConstantInt *Cond =
2338 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002339 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002340
Reid Spencer579dca12007-01-12 04:24:46 +00002341 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002342 }
2343 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2344 ConstantInt *Val =
2345 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002346 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002347 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002348 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2349 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2350 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2351 NewBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002352 else
2353 return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002354 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002355 if (RI->getNumOperands())
2356 RetVal = getVal(Values, RI->getOperand(0));
2357
2358 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002359 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002360 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002361 // invoke, unwind, unreachable.
2362 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002363 }
2364
2365 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002366 // executed the new block before. If so, we have a looping function,
2367 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002368 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002369 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002370
2371 // Okay, we have never been in this block before. Check to see if there
2372 // are any PHI nodes. If so, evaluate them with information about where
2373 // we came from.
2374 BasicBlock *OldBB = CurInst->getParent();
2375 CurInst = NewBB->begin();
2376 PHINode *PN;
2377 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2378 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2379
2380 // Do NOT increment CurInst. We know that the terminator had no value.
2381 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002382 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002383 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002384 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002385 }
2386
2387 if (!CurInst->use_empty())
2388 Values[CurInst] = InstResult;
2389
2390 // Advance program counter.
2391 ++CurInst;
2392 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002393}
2394
2395/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2396/// we can. Return true if we can, false otherwise.
2397static bool EvaluateStaticConstructor(Function *F) {
2398 /// MutatedMemory - For each store we execute, we update this map. Loads
2399 /// check this to get the most up-to-date value. If evaluation is successful,
2400 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002401 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002402
2403 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2404 /// to represent its body. This vector is needed so we can delete the
2405 /// temporary globals when we are done.
2406 std::vector<GlobalVariable*> AllocaTmps;
2407
2408 /// CallStack - This is used to detect recursion. In pathological situations
2409 /// we could hit exponential behavior, but at least there is nothing
2410 /// unbounded.
2411 std::vector<Function*> CallStack;
2412
2413 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002414 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002415 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2416 SmallVector<Constant*, 0>(), CallStack,
2417 MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002418 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002419 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002420 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002421 << F->getName() << "' to " << MutatedMemory.size()
2422 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002423 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002424 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002425 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002426 }
Chris Lattner79c11012005-09-26 04:44:35 +00002427
Chris Lattnera22fdb02005-09-26 17:07:09 +00002428 // At this point, we are done interpreting. If we created any 'alloca'
2429 // temporaries, release them now.
2430 while (!AllocaTmps.empty()) {
2431 GlobalVariable *Tmp = AllocaTmps.back();
2432 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002433
Chris Lattnera22fdb02005-09-26 17:07:09 +00002434 // If there are still users of the alloca, the program is doing something
2435 // silly, e.g. storing the address of the alloca somewhere and using it
2436 // later. Since this is undefined, we'll just make it be null.
2437 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002438 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002439 delete Tmp;
2440 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002441
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002442 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002443}
2444
Chris Lattnerdb973e62005-09-26 02:31:18 +00002445
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002446
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002447/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2448/// Return true if anything changed.
2449bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2450 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2451 bool MadeChange = false;
2452 if (Ctors.empty()) return false;
2453
2454 // Loop over global ctors, optimizing them when we can.
2455 for (unsigned i = 0; i != Ctors.size(); ++i) {
2456 Function *F = Ctors[i];
2457 // Found a null terminator in the middle of the list, prune off the rest of
2458 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002459 if (F == 0) {
2460 if (i != Ctors.size()-1) {
2461 Ctors.resize(i+1);
2462 MadeChange = true;
2463 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002464 break;
2465 }
2466
Chris Lattner79c11012005-09-26 04:44:35 +00002467 // We cannot simplify external ctor functions.
2468 if (F->empty()) continue;
2469
2470 // If we can evaluate the ctor at compile time, do.
2471 if (EvaluateStaticConstructor(F)) {
2472 Ctors.erase(Ctors.begin()+i);
2473 MadeChange = true;
2474 --i;
2475 ++NumCtorsEvaluated;
2476 continue;
2477 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002478 }
2479
2480 if (!MadeChange) return false;
2481
Chris Lattner7b550cc2009-11-06 04:27:31 +00002482 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002483 return true;
2484}
2485
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002486bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002487 bool Changed = false;
2488
Duncan Sands177d84e2009-01-07 20:01:06 +00002489 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002490 I != E;) {
2491 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002492 // Aliases without names cannot be referenced outside this module.
2493 if (!J->hasName() && !J->isDeclaration())
2494 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002495 // If the aliasee may change at link time, nothing can be done - bail out.
2496 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002497 continue;
2498
Duncan Sands4782b302009-02-15 09:56:08 +00002499 Constant *Aliasee = J->getAliasee();
2500 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002501 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002502 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2503
2504 // Make all users of the alias use the aliasee instead.
2505 if (!J->use_empty()) {
2506 J->replaceAllUsesWith(Aliasee);
2507 ++NumAliasesResolved;
2508 Changed = true;
2509 }
2510
Duncan Sands7a154cf2009-12-08 10:10:20 +00002511 // If the alias is externally visible, we may still be able to simplify it.
2512 if (!J->hasLocalLinkage()) {
2513 // If the aliasee has internal linkage, give it the name and linkage
2514 // of the alias, and delete the alias. This turns:
2515 // define internal ... @f(...)
2516 // @a = alias ... @f
2517 // into:
2518 // define ... @a(...)
2519 if (!Target->hasLocalLinkage())
2520 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002521
Duncan Sands7a154cf2009-12-08 10:10:20 +00002522 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002523 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002524 // and other attributes of the aliasee with those of the alias.
2525 if (!hasOneUse)
2526 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002527
Duncan Sands7a154cf2009-12-08 10:10:20 +00002528 // Give the aliasee the name, linkage and other attributes of the alias.
2529 Target->takeName(J);
2530 Target->setLinkage(J->getLinkage());
2531 Target->GlobalValue::copyAttributesFrom(J);
2532 }
Duncan Sands4782b302009-02-15 09:56:08 +00002533
2534 // Delete the alias.
2535 M.getAliasList().erase(J);
2536 ++NumAliasesRemoved;
2537 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002538 }
2539
2540 return Changed;
2541}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002542
Chris Lattner7a90b682004-10-07 04:16:33 +00002543bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002544 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002545
2546 // Try to find the llvm.globalctors list.
2547 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002548
Chris Lattner7a90b682004-10-07 04:16:33 +00002549 bool LocalChange = true;
2550 while (LocalChange) {
2551 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002552
2553 // Delete functions that are trivially dead, ccc -> fastcc
2554 LocalChange |= OptimizeFunctions(M);
2555
2556 // Optimize global_ctors list.
2557 if (GlobalCtors)
2558 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2559
2560 // Optimize non-address-taken globals.
2561 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002562
2563 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002564 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002565 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002566 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002567
2568 // TODO: Move all global ctors functions to the end of the module for code
2569 // layout.
2570
Chris Lattner079236d2004-02-25 21:34:36 +00002571 return Changed;
2572}