blob: c55ee563baf9be40049e6f4dd9ceadbe3a5c4b6e [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
Owen Anderson081c34b2010-10-19 17:21:58 +000062 GlobalOpt() : ModulePass(ID) {
63 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
64 }
Misha Brukmanfd939082005-04-21 23:48:37 +000065
Chris Lattnerb12914b2004-09-20 04:48:05 +000066 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000067
68 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000069 GlobalVariable *FindGlobalCtors(Module &M);
70 bool OptimizeFunctions(Module &M);
71 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000072 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000073 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000074 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000075 };
Chris Lattner079236d2004-02-25 21:34:36 +000076}
77
Dan Gohman844731a2008-05-13 00:00:25 +000078char GlobalOpt::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000079INITIALIZE_PASS(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000080 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000081
Chris Lattner7a90b682004-10-07 04:16:33 +000082ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000083
Dan Gohman844731a2008-05-13 00:00:25 +000084namespace {
85
Chris Lattner7a90b682004-10-07 04:16:33 +000086/// GlobalStatus - As we analyze each global, keep track of some information
87/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000088/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000089struct GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000090 /// isLoaded - True if the global is ever loaded. If the global isn't ever
91 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000092 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000093
94 /// StoredType - Keep track of what stores to the global look like.
95 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000096 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000097 /// NotStored - There is no store to this global. It can thus be marked
98 /// constant.
99 NotStored,
100
101 /// isInitializerStored - This global is stored to, but the only thing
102 /// stored is the constant it was initialized with. This is only tracked
103 /// for scalar globals.
104 isInitializerStored,
105
106 /// isStoredOnce - This global is stored to, but only its initializer and
107 /// one other value is ever stored to it. If this global isStoredOnce, we
108 /// track the value stored to it in StoredOnceValue below. This is only
109 /// tracked for scalar globals.
110 isStoredOnce,
111
112 /// isStored - This global is stored to by multiple values or something else
113 /// that we cannot track.
114 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000115 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000116
117 /// StoredOnceValue - If only one value (besides the initializer constant) is
118 /// ever stored to this global, keep track of what value it is.
119 Value *StoredOnceValue;
120
Chris Lattner25de4e52006-11-01 18:03:33 +0000121 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
122 /// null/false. When the first accessing function is noticed, it is recorded.
123 /// When a second different accessing function is noticed,
124 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000125 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000126 bool HasMultipleAccessingFunctions;
127
Chris Lattner25de4e52006-11-01 18:03:33 +0000128 /// HasNonInstructionUser - Set to true if this global has a user that is not
129 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000130 bool HasNonInstructionUser;
131
Chris Lattner25de4e52006-11-01 18:03:33 +0000132 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
133 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000134
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000135 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000136 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner6a93fc02008-01-14 01:32:52 +0000137 HasNonInstructionUser(false), HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000138};
Chris Lattnere47ba742004-10-06 20:57:02 +0000139
Dan Gohman844731a2008-05-13 00:00:25 +0000140}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000141
Jay Foade3acf152009-06-09 21:37:11 +0000142// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
143// by constants itself. Note that constants cannot be cyclic, so this test is
144// pretty easy to implement recursively.
145//
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000146static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000147 if (isa<GlobalValue>(C)) return false;
148
Gabor Greif27236912010-04-07 18:59:26 +0000149 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
150 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000151 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000152 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000153 } else
154 return false;
155 return true;
156}
157
158
Chris Lattner7a90b682004-10-07 04:16:33 +0000159/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
160/// structure. If the global has its address taken, return true to indicate we
161/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000162///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000163static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
164 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000165 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000166 ++UI) {
167 const User *U = *UI;
168 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000169 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000170
171 // If the result of the constantexpr isn't pointer type, then we won't
172 // know to expect it in various places. Just reject early.
173 if (!isa<PointerType>(CE->getType())) return true;
174
Chris Lattner7a90b682004-10-07 04:16:33 +0000175 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000176 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000177 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000178 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000179 if (GS.AccessingFunction == 0)
180 GS.AccessingFunction = F;
181 else if (GS.AccessingFunction != F)
182 GS.HasMultipleAccessingFunctions = true;
183 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000184 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000185 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000186 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000187 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000188 // Don't allow a store OF the address, only stores TO the address.
189 if (SI->getOperand(0) == V) return true;
190
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000191 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
192
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000193 // If this is a direct store to the global (i.e., the global is a scalar
194 // value, not an aggregate), keep more specific information about
195 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000196 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000197 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
198 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000199 Value *StoredVal = SI->getOperand(0);
200 if (StoredVal == GV->getInitializer()) {
201 if (GS.StoredType < GlobalStatus::isInitializerStored)
202 GS.StoredType = GlobalStatus::isInitializerStored;
203 } else if (isa<LoadInst>(StoredVal) &&
204 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000205 if (GS.StoredType < GlobalStatus::isInitializerStored)
206 GS.StoredType = GlobalStatus::isInitializerStored;
207 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
208 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000209 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000210 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000211 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000212 // noop.
213 } else {
214 GS.StoredType = GlobalStatus::isStored;
215 }
216 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000217 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000218 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000219 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000220 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000221 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000222 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000223 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000224 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000225 // PHI nodes we can check just like select or GEP instructions, but we
226 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000227 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000228 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000229 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000230 } else if (isa<CmpInst>(I)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +0000231 // Nothing to analyse.
Chris Lattner8e108442009-03-08 03:37:35 +0000232 } else if (isa<MemTransferInst>(I)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +0000233 const MemTransferInst *MTI = cast<MemTransferInst>(I);
234 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000235 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000236 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000237 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000238 } else if (isa<MemSetInst>(I)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +0000239 assert(cast<MemSetInst>(I)->getArgOperand(0) == V &&
240 "Memset only takes one pointer!");
Chris Lattner35c81b02005-02-27 18:58:52 +0000241 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000242 } else {
243 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000244 }
Gabor Greife6642672010-07-09 16:51:20 +0000245 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000246 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000247 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000248 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000249 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000250 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000251 GS.HasNonInstructionUser = true;
252 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000253 return true;
254 }
Gabor Greife6642672010-07-09 16:51:20 +0000255 }
Chris Lattner079236d2004-02-25 21:34:36 +0000256
257 return false;
258}
259
Chris Lattner7b550cc2009-11-06 04:27:31 +0000260static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
Chris Lattner670c8892004-10-08 17:32:09 +0000261 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
262 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000263 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000264
Chris Lattner670c8892004-10-08 17:32:09 +0000265 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
266 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
267 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
268 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000269 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000270 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000271 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000272 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
273 if (IdxV < STy->getNumElements())
Owen Andersona7235ea2009-07-31 20:28:14 +0000274 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000275 } else if (const SequentialType *STy =
276 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000277 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000278 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000279 } else if (isa<UndefValue>(Agg)) {
280 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
281 if (IdxV < STy->getNumElements())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000282 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000283 } else if (const SequentialType *STy =
284 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000285 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000286 }
Chris Lattner670c8892004-10-08 17:32:09 +0000287 }
288 return 0;
289}
Chris Lattner7a90b682004-10-07 04:16:33 +0000290
Chris Lattner7a90b682004-10-07 04:16:33 +0000291
Chris Lattnere47ba742004-10-06 20:57:02 +0000292/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
293/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000294/// quick scan over the use list to clean up the easy and obvious cruft. This
295/// returns true if it made a change.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000296static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000297 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000298 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
299 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000300
Chris Lattner7a90b682004-10-07 04:16:33 +0000301 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000302 if (Init) {
303 // Replace the load with the initializer.
304 LI->replaceAllUsesWith(Init);
305 LI->eraseFromParent();
306 Changed = true;
307 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000308 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000309 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000310 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000311 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000312 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
313 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000314 Constant *SubInit = 0;
315 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000316 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000317 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000318 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000319 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000320 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000321 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000322 }
323
324 if (CE->use_empty()) {
325 CE->destroyConstant();
326 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000327 }
328 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000329 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
330 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
331 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000332 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000333 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000334 ConstantExpr *CE =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000335 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000336 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000337 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000338 }
Chris Lattner7b550cc2009-11-06 04:27:31 +0000339 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000340
Chris Lattner031955d2004-10-10 16:43:46 +0000341 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000342 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000343 Changed = true;
344 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000345 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
346 if (MI->getRawDest() == V) {
347 MI->eraseFromParent();
348 Changed = true;
349 }
350
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000351 } else if (Constant *C = dyn_cast<Constant>(U)) {
352 // If we have a chain of dead constantexprs or other things dangling from
353 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000354 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000355 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000356 // This could have invalidated UI, start over from scratch.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000357 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000358 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000359 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000360 }
361 }
Chris Lattner031955d2004-10-10 16:43:46 +0000362 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000363}
364
Chris Lattner941db492008-01-14 02:09:12 +0000365/// isSafeSROAElementUse - Return true if the specified instruction is a safe
366/// user of a derived expression from a global that we want to SROA.
367static bool isSafeSROAElementUse(Value *V) {
368 // We might have a dead and dangling constant hanging off of here.
369 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000370 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000371
Chris Lattner941db492008-01-14 02:09:12 +0000372 Instruction *I = dyn_cast<Instruction>(V);
373 if (!I) return false;
374
375 // Loads are ok.
376 if (isa<LoadInst>(I)) return true;
377
378 // Stores *to* the pointer are ok.
379 if (StoreInst *SI = dyn_cast<StoreInst>(I))
380 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000381
Chris Lattner941db492008-01-14 02:09:12 +0000382 // Otherwise, it must be a GEP.
383 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
384 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000385
Chris Lattner941db492008-01-14 02:09:12 +0000386 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
387 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
388 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000389
Chris Lattner941db492008-01-14 02:09:12 +0000390 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
391 I != E; ++I)
392 if (!isSafeSROAElementUse(*I))
393 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000394 return true;
395}
396
Chris Lattner941db492008-01-14 02:09:12 +0000397
398/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
399/// Look at it and its uses and decide whether it is safe to SROA this global.
400///
401static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
402 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000403 if (!isa<GetElementPtrInst>(U) &&
404 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000405 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
406 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000407
Chris Lattner941db492008-01-14 02:09:12 +0000408 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
409 // don't like < 3 operand CE's, and we don't like non-constant integer
410 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
411 // value of C.
412 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
413 !cast<Constant>(U->getOperand(1))->isNullValue() ||
414 !isa<ConstantInt>(U->getOperand(2)))
415 return false;
416
417 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
418 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000419
Chris Lattner941db492008-01-14 02:09:12 +0000420 // If this is a use of an array allocation, do a bit more checking for sanity.
421 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
422 uint64_t NumElements = AT->getNumElements();
423 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000424
Chris Lattner941db492008-01-14 02:09:12 +0000425 // Check to make sure that index falls within the array. If not,
426 // something funny is going on, so we won't do the optimization.
427 //
428 if (Idx->getZExtValue() >= NumElements)
429 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000430
Chris Lattner941db492008-01-14 02:09:12 +0000431 // We cannot scalar repl this level of the array unless any array
432 // sub-indices are in-range constants. In particular, consider:
433 // A[0][i]. We cannot know that the user isn't doing invalid things like
434 // allowing i to index an out-of-range subscript that accesses A[1].
435 //
436 // Scalar replacing *just* the outer index of the array is probably not
437 // going to be a win anyway, so just give up.
438 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000439 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000440 ++GEPI) {
441 uint64_t NumElements;
442 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
443 NumElements = SubArrayTy->getNumElements();
Dan Gohman6874a2a2009-08-18 14:58:19 +0000444 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
445 NumElements = SubVectorTy->getNumElements();
446 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000447 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000448 "Indexed GEP type is not array, vector, or struct!");
449 continue;
450 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000451
Chris Lattner941db492008-01-14 02:09:12 +0000452 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
453 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
454 return false;
455 }
456 }
457
458 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
459 if (!isSafeSROAElementUse(*I))
460 return false;
461 return true;
462}
463
464/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
465/// is safe for us to perform this transformation.
466///
467static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
468 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
469 UI != E; ++UI) {
470 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
471 return false;
472 }
473 return true;
474}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000475
Chris Lattner941db492008-01-14 02:09:12 +0000476
Chris Lattner670c8892004-10-08 17:32:09 +0000477/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
478/// variable. This opens the door for other optimizations by exposing the
479/// behavior of the program in a more fine-grained way. We have determined that
480/// this transformation is safe already. We return the first global variable we
481/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000482static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000483 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000484 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000485 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000486
Rafael Espindolabb46f522009-01-15 20:18:42 +0000487 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000488 Constant *Init = GV->getInitializer();
489 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000490
Chris Lattner670c8892004-10-08 17:32:09 +0000491 std::vector<GlobalVariable*> NewGlobals;
492 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
493
Chris Lattner998182b2008-04-26 07:40:11 +0000494 // Get the alignment of the global, either explicit or target-specific.
495 unsigned StartAlignment = GV->getAlignment();
496 if (StartAlignment == 0)
497 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000498
Chris Lattner670c8892004-10-08 17:32:09 +0000499 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
500 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000501 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000502 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
503 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000504 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000505 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000506 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000507 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000508 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000509 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000510 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000511 Globals.insert(GV, NGV);
512 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000513
Chris Lattner998182b2008-04-26 07:40:11 +0000514 // Calculate the known alignment of the field. If the original aggregate
515 // had 256 byte alignment for example, something might depend on that:
516 // propagate info to each field.
517 uint64_t FieldOffset = Layout.getElementOffset(i);
518 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
519 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
520 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000521 }
522 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
523 unsigned NumElements = 0;
524 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
525 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000526 else
Chris Lattner998182b2008-04-26 07:40:11 +0000527 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000528
Chris Lattner1f21ef12005-02-23 16:53:04 +0000529 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000530 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000531 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000532
Duncan Sands777d2302009-05-09 07:06:46 +0000533 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000534 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000535 for (unsigned i = 0, e = NumElements; i != e; ++i) {
536 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000537 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000538 assert(In && "Couldn't get element of initializer?");
539
Chris Lattner7b550cc2009-11-06 04:27:31 +0000540 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000541 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000542 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000543 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000544 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000545 Globals.insert(GV, NGV);
546 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000547
Chris Lattner998182b2008-04-26 07:40:11 +0000548 // Calculate the known alignment of the field. If the original aggregate
549 // had 256 byte alignment for example, something might depend on that:
550 // propagate info to each field.
551 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
552 if (NewAlign > EltAlign)
553 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000554 }
555 }
556
557 if (NewGlobals.empty())
558 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000559
David Greene3215b0e2010-01-05 01:28:05 +0000560 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000561
Chris Lattner7b550cc2009-11-06 04:27:31 +0000562 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000563
564 // Loop over all of the uses of the global, replacing the constantexpr geps,
565 // with smaller constantexpr geps or direct references.
566 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000567 User *GEP = GV->use_back();
568 assert(((isa<ConstantExpr>(GEP) &&
569 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
570 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000571
Chris Lattner670c8892004-10-08 17:32:09 +0000572 // Ignore the 1th operand, which has to be zero or else the program is quite
573 // broken (undefined). Get the 2nd operand, which is the structure or array
574 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000575 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000576 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
577
Chris Lattner30ba5692004-10-11 05:54:41 +0000578 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000579
580 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000581 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000582 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000583 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000584 Idxs.push_back(NullInt);
585 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
586 Idxs.push_back(CE->getOperand(i));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000587 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000588 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000589 } else {
590 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000591 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000592 Idxs.push_back(NullInt);
593 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
594 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000595 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000596 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000597 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000598 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000599 GEP->replaceAllUsesWith(NewPtr);
600
601 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000602 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000603 else
604 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000605 }
606
Chris Lattnere40e2d12004-10-08 20:25:55 +0000607 // Delete the old global, now that it is dead.
608 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000609 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000610
611 // Loop over the new globals array deleting any globals that are obviously
612 // dead. This can arise due to scalarization of a structure or an array that
613 // has elements that are dead.
614 unsigned FirstGlobal = 0;
615 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
616 if (NewGlobals[i]->use_empty()) {
617 Globals.erase(NewGlobals[i]);
618 if (FirstGlobal == i) ++FirstGlobal;
619 }
620
621 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000622}
623
Chris Lattner9b34a612004-10-09 21:48:45 +0000624/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000625/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000626/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000627static bool AllUsesOfValueWillTrapIfNull(const Value *V,
628 SmallPtrSet<const PHINode*, 8> &PHIs) {
629 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000630 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000631 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000632
633 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000634 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000635 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000636 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000637 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000638 return false; // Storing the value.
639 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000640 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000641 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000642 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000643 return false; // Not calling the ptr
644 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000645 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000646 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000647 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000648 return false; // Not calling the ptr
649 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000650 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000651 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000652 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000653 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000654 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000655 // If we've already seen this phi node, ignore it, it has already been
656 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000657 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
658 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000659 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000660 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000661 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000662 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000663 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000664 return false;
665 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000666 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000667 return true;
668}
669
670/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000671/// from GV will trap if the loaded value is null. Note that this also permits
672/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000673static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
674 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000675 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000676 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000677
Gabor Greif6ce02b52010-04-06 19:24:18 +0000678 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
679 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000680 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000681 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000682 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000683 // Ignore stores to the global.
684 } else {
685 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000686 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000687 return false;
688 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000689 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000690 return true;
691}
692
Chris Lattner7b550cc2009-11-06 04:27:31 +0000693static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000694 bool Changed = false;
695 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
696 Instruction *I = cast<Instruction>(*UI++);
697 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
698 LI->setOperand(0, NewV);
699 Changed = true;
700 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
701 if (SI->getOperand(1) == V) {
702 SI->setOperand(1, NewV);
703 Changed = true;
704 }
705 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000706 CallSite CS(I);
707 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000708 // Calling through the pointer! Turn into a direct call, but be careful
709 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000710 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000711 Changed = true;
712 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000713 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
714 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000715 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000716 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000717 }
718
719 if (PassedAsArg) {
720 // Being passed as an argument also. Be careful to not invalidate UI!
721 UI = V->use_begin();
722 }
723 }
724 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
725 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000726 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000727 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000728 if (CI->use_empty()) {
729 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000730 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000731 }
732 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
733 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000734 SmallVector<Constant*, 8> Idxs;
735 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000736 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
737 i != e; ++i)
738 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000739 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000740 else
741 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000742 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000743 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000744 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Chris Lattner7b550cc2009-11-06 04:27:31 +0000745 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000746 if (GEPI->use_empty()) {
747 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000748 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000749 }
750 }
751 }
752
753 return Changed;
754}
755
756
757/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
758/// value stored into it. If there are uses of the loaded value that would trap
759/// if the loaded value is dynamically null, then we know that they cannot be
760/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000761static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000762 bool Changed = false;
763
Chris Lattner92c6bd22009-01-14 00:12:58 +0000764 // Keep track of whether we are able to remove all the uses of the global
765 // other than the store that defines it.
766 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000767
Chris Lattner708148e2004-10-10 23:14:11 +0000768 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000769 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
770 User *GlobalUser = *GUI++;
771 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000772 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000773 // If we were able to delete all uses of the loads
774 if (LI->use_empty()) {
775 LI->eraseFromParent();
776 Changed = true;
777 } else {
778 AllNonStoreUsesGone = false;
779 }
780 } else if (isa<StoreInst>(GlobalUser)) {
781 // Ignore the store that stores "LV" to the global.
782 assert(GlobalUser->getOperand(1) == GV &&
783 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000784 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000785 AllNonStoreUsesGone = false;
786
787 // If we get here we could have other crazy uses that are transitively
788 // loaded.
789 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
790 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000791 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000792 }
Chris Lattner708148e2004-10-10 23:14:11 +0000793
794 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000795 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000796 ++NumGlobUses;
797 }
798
Chris Lattner708148e2004-10-10 23:14:11 +0000799 // If we nuked all of the loads, then none of the stores are needed either,
800 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000801 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000802 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000803 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000804 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000805 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000806 ++NumDeleted;
807 }
808 Changed = true;
809 }
810 return Changed;
811}
812
Chris Lattner30ba5692004-10-11 05:54:41 +0000813/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
814/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000815static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000816 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
817 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chris Lattner7b550cc2009-11-06 04:27:31 +0000818 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000819 I->replaceAllUsesWith(NewC);
820
Chris Lattnerd514d822005-02-01 01:23:31 +0000821 // Advance UI to the next non-I use to avoid invalidating it!
822 // Instructions could multiply use V.
823 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000824 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000825 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000826 }
827}
828
829/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
830/// variable, and transforms the program as if it always contained the result of
831/// the specified malloc. Because it is always the result of the specified
832/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000833/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000834static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000835 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000836 const Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000837 ConstantInt *NElements,
Victor Hernandez83d63912009-09-18 22:35:49 +0000838 TargetData* TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000839 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000840
Chris Lattnera6874652010-02-25 22:33:52 +0000841 const Type *GlobalType;
842 if (NElements->getZExtValue() == 1)
843 GlobalType = AllocTy;
844 else
845 // If we have an array allocation, the global variable is of an array.
846 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000847
848 // Create the new global variable. The contents of the malloc'd memory is
849 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000850 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000851 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000852 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000853 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000854 GV->getName()+".body",
855 GV,
856 GV->isThreadLocal());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000857
Chris Lattnera6874652010-02-25 22:33:52 +0000858 // If there are bitcast users of the malloc (which is typical, usually we have
859 // a malloc + bitcast) then replace them with uses of the new global. Update
860 // other users to use the global as well.
861 BitCastInst *TheBC = 0;
862 while (!CI->use_empty()) {
863 Instruction *User = cast<Instruction>(CI->use_back());
864 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
865 if (BCI->getType() == NewGV->getType()) {
866 BCI->replaceAllUsesWith(NewGV);
867 BCI->eraseFromParent();
868 } else {
869 BCI->setOperand(0, NewGV);
870 }
871 } else {
872 if (TheBC == 0)
873 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
874 User->replaceUsesOfWith(CI, TheBC);
875 }
876 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000877
Victor Hernandez83d63912009-09-18 22:35:49 +0000878 Constant *RepValue = NewGV;
879 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000880 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000881 GV->getType()->getElementType());
882
883 // If there is a comparison against null, we will insert a global bool to
884 // keep track of whether the global was initialized yet or not.
885 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000886 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000887 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000888 ConstantInt::getFalse(GV->getContext()),
889 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000890 bool InitBoolUsed = false;
891
892 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000893 while (!GV->use_empty()) {
894 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000895 // The global is initialized when the store to it occurs.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000896 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000897 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000898 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000899 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000900
Chris Lattnera6874652010-02-25 22:33:52 +0000901 LoadInst *LI = cast<LoadInst>(GV->use_back());
902 while (!LI->use_empty()) {
903 Use &LoadUse = LI->use_begin().getUse();
904 if (!isa<ICmpInst>(LoadUse.getUser())) {
905 LoadUse = RepValue;
906 continue;
907 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000908
Chris Lattnera6874652010-02-25 22:33:52 +0000909 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
910 // Replace the cmp X, 0 with a use of the bool value.
911 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
912 InitBoolUsed = true;
913 switch (ICI->getPredicate()) {
914 default: llvm_unreachable("Unknown ICmp Predicate!");
915 case ICmpInst::ICMP_ULT:
916 case ICmpInst::ICMP_SLT: // X < null -> always false
917 LV = ConstantInt::getFalse(GV->getContext());
918 break;
919 case ICmpInst::ICMP_ULE:
920 case ICmpInst::ICMP_SLE:
921 case ICmpInst::ICMP_EQ:
922 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
923 break;
924 case ICmpInst::ICMP_NE:
925 case ICmpInst::ICMP_UGE:
926 case ICmpInst::ICMP_SGE:
927 case ICmpInst::ICMP_UGT:
928 case ICmpInst::ICMP_SGT:
929 break; // no change.
930 }
931 ICI->replaceAllUsesWith(LV);
932 ICI->eraseFromParent();
933 }
934 LI->eraseFromParent();
935 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000936
937 // If the initialization boolean was used, insert it, otherwise delete it.
938 if (!InitBoolUsed) {
939 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000940 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000941 delete InitBool;
942 } else
943 GV->getParent()->getGlobalList().insert(GV, InitBool);
944
Chris Lattnera6874652010-02-25 22:33:52 +0000945 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000946 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000947 CI->eraseFromParent();
948
949 // To further other optimizations, loop over all users of NewGV and try to
950 // constant prop them. This will promote GEP instructions with constant
951 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000952 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000953 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000954 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000955
956 return NewGV;
957}
958
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000959/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
960/// to make sure that there are no complex uses of V. We permit simple things
961/// like dereferencing the pointer, but not storing through the address, unless
962/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000963static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
964 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000965 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000966 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000967 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000968 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000969
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000970 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
971 continue; // Fine, ignore.
972 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000973
Gabor Greif0b520db2010-04-06 18:58:22 +0000974 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000975 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
976 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000977 continue; // Otherwise, storing through it, or storing into GV... fine.
978 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000979
Chris Lattnera2fb2342010-04-10 18:19:22 +0000980 // Must index into the array and into the struct.
981 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000982 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000983 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000984 continue;
985 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000986
Gabor Greif0b520db2010-04-06 18:58:22 +0000987 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000988 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
989 // cycles.
990 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000991 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
992 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000993 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000994 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000995
Gabor Greif0b520db2010-04-06 18:58:22 +0000996 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000997 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
998 return false;
999 continue;
1000 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001001
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001002 return false;
1003 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001004 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001005}
1006
Chris Lattner86395032006-09-30 23:32:09 +00001007/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1008/// somewhere. Transform all uses of the allocation into loads from the
1009/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001010/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001011/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001012static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001013 GlobalVariable *GV) {
1014 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001015 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1016 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001017 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1018 // If this is the store of the allocation into the global, remove it.
1019 if (SI->getOperand(1) == GV) {
1020 SI->eraseFromParent();
1021 continue;
1022 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001023 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1024 // Insert the load in the corresponding predecessor, not right before the
1025 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001026 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001027 } else if (isa<BitCastInst>(U)) {
1028 // Must be bitcast between the malloc and store to initialize the global.
1029 ReplaceUsesOfMallocWithGlobal(U, GV);
1030 U->eraseFromParent();
1031 continue;
1032 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1033 // If this is a "GEP bitcast" and the user is a store to the global, then
1034 // just process it as a bitcast.
1035 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1036 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1037 if (SI->getOperand(1) == GV) {
1038 // Must be bitcast GEP between the malloc and store to initialize
1039 // the global.
1040 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1041 GEPI->eraseFromParent();
1042 continue;
1043 }
Chris Lattner86395032006-09-30 23:32:09 +00001044 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001045
Chris Lattner86395032006-09-30 23:32:09 +00001046 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001047 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001048 U->replaceUsesOfWith(Alloc, NL);
1049 }
1050}
1051
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001052/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1053/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1054/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001055static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001056 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1057 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001058 // We permit two users of the load: setcc comparing against the null
1059 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001060 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1061 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001062 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001063
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001064 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001065 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001066 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1067 return false;
1068 continue;
1069 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001070
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001071 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001072 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001073 // Must index into the array and into the struct.
1074 if (GEPI->getNumOperands() < 3)
1075 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001076
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001077 // Otherwise the GEP is ok.
1078 continue;
1079 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001080
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001081 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001082 if (!LoadUsingPHIsPerLoad.insert(PN))
1083 // This means some phi nodes are dependent on each other.
1084 // Avoid infinite looping!
1085 return false;
1086 if (!LoadUsingPHIs.insert(PN))
1087 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001088 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001089
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001090 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001091 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1092 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001093 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001094
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001095 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001096 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001097
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001098 // Otherwise we don't know what this is, not ok.
1099 return false;
1100 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001101
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001102 return true;
1103}
1104
1105
1106/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1107/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001108static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001109 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001110 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1111 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001112 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1113 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001114 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001115 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1116 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001117 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001118 LoadUsingPHIsPerLoad.clear();
1119 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001120
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001121 // If we reach here, we know that all uses of the loads and transitive uses
1122 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001123 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001124 // Check to verify that all operands of the PHIs are either PHIS that can be
1125 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001126 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1127 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001128 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001129 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1130 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001131
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001132 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001133 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001134
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001135 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001136 // One of the PHIs in our set is (optimistically) ok.
1137 if (LoadUsingPHIs.count(InPN))
1138 continue;
1139 return false;
1140 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001141
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001142 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001143 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001144 if (LI->getOperand(0) == GV)
1145 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001146
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001147 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001148
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001149 // Anything else is rejected.
1150 return false;
1151 }
1152 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001153
Chris Lattner86395032006-09-30 23:32:09 +00001154 return true;
1155}
1156
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001157static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1158 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001159 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001160 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001161
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001162 if (FieldNo >= FieldVals.size())
1163 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001164
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001165 // If we already have this value, just reuse the previously scalarized
1166 // version.
1167 if (Value *FieldVal = FieldVals[FieldNo])
1168 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001169
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001170 // Depending on what instruction this is, we have several cases.
1171 Value *Result;
1172 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1173 // This is a scalarized version of the load from the global. Just create
1174 // a new Load of the scalarized global.
1175 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1176 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001177 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001178 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001179 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1180 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1181 // field.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001182 const StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001183 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001184
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001185 Result =
Owen Andersondebcb012009-07-29 22:17:13 +00001186 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001187 PN->getName()+".f"+Twine(FieldNo), PN);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001188 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1189 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001190 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001191 Result = 0;
1192 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001193
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001194 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001195}
1196
Chris Lattner330245e2007-09-13 17:29:05 +00001197/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1198/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001199static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001200 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001201 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001202 // If this is a comparison against null, handle it.
1203 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1204 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1205 // If we have a setcc of the loaded pointer, we can use a setcc of any
1206 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001207 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001208 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001209
Owen Anderson333c4002009-07-09 23:48:35 +00001210 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001211 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001212 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001213 SCI->replaceAllUsesWith(New);
1214 SCI->eraseFromParent();
1215 return;
1216 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001217
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001218 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001219 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1220 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1221 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001222
Chris Lattnera637a8b2007-09-13 18:00:31 +00001223 // Load the pointer for this field.
1224 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001225 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001226 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001227
Chris Lattnera637a8b2007-09-13 18:00:31 +00001228 // Create the new GEP idx vector.
1229 SmallVector<Value*, 8> GEPIdx;
1230 GEPIdx.push_back(GEPI->getOperand(1));
1231 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001232
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001233 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1234 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001235 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001236 GEPI->replaceAllUsesWith(NGEPI);
1237 GEPI->eraseFromParent();
1238 return;
1239 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001240
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001241 // Recursively transform the users of PHI nodes. This will lazily create the
1242 // PHIs that are needed for individual elements. Keep track of what PHIs we
1243 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1244 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1245 // already been seen first by another load, so its uses have already been
1246 // processed.
1247 PHINode *PN = cast<PHINode>(LoadUser);
1248 bool Inserted;
1249 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1250 tie(InsertPos, Inserted) =
1251 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1252 if (!Inserted) return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001253
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001254 // If this is the first time we've seen this PHI, recursively process all
1255 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001256 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1257 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001258 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001259 }
Chris Lattner330245e2007-09-13 17:29:05 +00001260}
1261
Chris Lattner86395032006-09-30 23:32:09 +00001262/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1263/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1264/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001265/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001266static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001267 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001268 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001269 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001270 UI != E; ) {
1271 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001272 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001273 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001274
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001275 if (Load->use_empty()) {
1276 Load->eraseFromParent();
1277 InsertedScalarizedValues.erase(Load);
1278 }
Chris Lattner86395032006-09-30 23:32:09 +00001279}
1280
Victor Hernandez83d63912009-09-18 22:35:49 +00001281/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1282/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001283static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1284 Value* NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001285 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Victor Hernandez83d63912009-09-18 22:35:49 +00001286 const Type* MAT = getMallocAllocatedType(CI);
1287 const StructType *STy = cast<StructType>(MAT);
1288
1289 // There is guaranteed to be at least one use of the malloc (storing
1290 // it into GV). If there are other uses, change them to be uses of
1291 // the global to simplify later code. This also deletes the store
1292 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001293 ReplaceUsesOfMallocWithGlobal(CI, GV);
1294
Victor Hernandez83d63912009-09-18 22:35:49 +00001295 // Okay, at this point, there are no users of the malloc. Insert N
1296 // new mallocs at the same place as CI, and N globals.
1297 std::vector<Value*> FieldGlobals;
1298 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001299
Victor Hernandez83d63912009-09-18 22:35:49 +00001300 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1301 const Type *FieldTy = STy->getElementType(FieldNo);
1302 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001303
Victor Hernandez83d63912009-09-18 22:35:49 +00001304 GlobalVariable *NGV =
1305 new GlobalVariable(*GV->getParent(),
1306 PFieldTy, false, GlobalValue::InternalLinkage,
1307 Constant::getNullValue(PFieldTy),
1308 GV->getName() + ".f" + Twine(FieldNo), GV,
1309 GV->isThreadLocal());
1310 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001311
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001312 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Victor Hernandez631f3c02009-11-07 00:41:19 +00001313 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001314 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez631f3c02009-11-07 00:41:19 +00001315 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001316 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1317 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001318 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001319 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001320 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001321 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001322 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001323
Victor Hernandez83d63912009-09-18 22:35:49 +00001324 // The tricky aspect of this transformation is handling the case when malloc
1325 // fails. In the original code, malloc failing would set the result pointer
1326 // of malloc to null. In this case, some mallocs could succeed and others
1327 // could fail. As such, we emit code that looks like this:
1328 // F0 = malloc(field0)
1329 // F1 = malloc(field1)
1330 // F2 = malloc(field2)
1331 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1332 // if (F0) { free(F0); F0 = 0; }
1333 // if (F1) { free(F1); F1 = 0; }
1334 // if (F2) { free(F2); F2 = 0; }
1335 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001336 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001337 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1338 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001339 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001340 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001341 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1342 Constant::getNullValue(FieldMallocs[i]->getType()),
1343 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001344 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001345 }
1346
1347 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001348 BasicBlock *OrigBB = CI->getParent();
1349 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001350
Victor Hernandez83d63912009-09-18 22:35:49 +00001351 // Create the block to check the first condition. Put all these blocks at the
1352 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001353 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1354 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001355 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001356
Victor Hernandez83d63912009-09-18 22:35:49 +00001357 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1358 // branch on RunningOr.
1359 OrigBB->getTerminator()->eraseFromParent();
1360 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001361
Victor Hernandez83d63912009-09-18 22:35:49 +00001362 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1363 // pointer, because some may be null while others are not.
1364 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1365 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001366 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Victor Hernandez83d63912009-09-18 22:35:49 +00001367 Constant::getNullValue(GVVal->getType()),
1368 "tmp");
Chris Lattner7b550cc2009-11-06 04:27:31 +00001369 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001370 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001371 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001372 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001373 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1374 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001375
1376 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001377 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001378 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1379 FreeBlock);
1380 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001381
Victor Hernandez83d63912009-09-18 22:35:49 +00001382 NullPtrBlock = NextBlock;
1383 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001384
Victor Hernandez83d63912009-09-18 22:35:49 +00001385 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001386
1387 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001388 CI->eraseFromParent();
1389
1390 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1391 /// update all uses of the load, keep track of what scalarized loads are
1392 /// inserted for a given load.
1393 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1394 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001395
Victor Hernandez83d63912009-09-18 22:35:49 +00001396 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001397
Victor Hernandez83d63912009-09-18 22:35:49 +00001398 // Okay, the malloc site is completely handled. All of the uses of GV are now
1399 // loads, and all uses of those loads are simple. Rewrite them to use loads
1400 // of the per-field globals instead.
1401 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1402 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001403
Victor Hernandez83d63912009-09-18 22:35:49 +00001404 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001405 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001406 continue;
1407 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001408
Victor Hernandez83d63912009-09-18 22:35:49 +00001409 // Must be a store of null.
1410 StoreInst *SI = cast<StoreInst>(User);
1411 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1412 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001413
Victor Hernandez83d63912009-09-18 22:35:49 +00001414 // Insert a store of null into each global.
1415 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1416 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1417 Constant *Null = Constant::getNullValue(PT->getElementType());
1418 new StoreInst(Null, FieldGlobals[i], SI);
1419 }
1420 // Erase the original store.
1421 SI->eraseFromParent();
1422 }
1423
1424 // While we have PHIs that are interesting to rewrite, do it.
1425 while (!PHIsToRewrite.empty()) {
1426 PHINode *PN = PHIsToRewrite.back().first;
1427 unsigned FieldNo = PHIsToRewrite.back().second;
1428 PHIsToRewrite.pop_back();
1429 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1430 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1431
1432 // Add all the incoming values. This can materialize more phis.
1433 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1434 Value *InVal = PN->getIncomingValue(i);
1435 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001436 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001437 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1438 }
1439 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001440
Victor Hernandez83d63912009-09-18 22:35:49 +00001441 // Drop all inter-phi links and any loads that made it this far.
1442 for (DenseMap<Value*, std::vector<Value*> >::iterator
1443 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1444 I != E; ++I) {
1445 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1446 PN->dropAllReferences();
1447 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1448 LI->dropAllReferences();
1449 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001450
Victor Hernandez83d63912009-09-18 22:35:49 +00001451 // Delete all the phis and loads now that inter-references are dead.
1452 for (DenseMap<Value*, std::vector<Value*> >::iterator
1453 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1454 I != E; ++I) {
1455 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1456 PN->eraseFromParent();
1457 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1458 LI->eraseFromParent();
1459 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001460
Victor Hernandez83d63912009-09-18 22:35:49 +00001461 // The old global is now dead, remove it.
1462 GV->eraseFromParent();
1463
1464 ++NumHeapSRA;
1465 return cast<GlobalVariable>(FieldGlobals[0]);
1466}
1467
Chris Lattnere61d0a62008-12-15 21:02:25 +00001468/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1469/// pointer global variable with a single value stored it that is a malloc or
1470/// cast of malloc.
1471static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001472 CallInst *CI,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001473 const Type *AllocTy,
Victor Hernandez83d63912009-09-18 22:35:49 +00001474 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001475 TargetData *TD) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001476 if (!TD)
1477 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001478
Victor Hernandez83d63912009-09-18 22:35:49 +00001479 // If this is a malloc of an abstract type, don't touch it.
1480 if (!AllocTy->isSized())
1481 return false;
1482
1483 // We can't optimize this global unless all uses of it are *known* to be
1484 // of the malloc value, not of the null initializer value (consider a use
1485 // that compares the global's value against zero to see if the malloc has
1486 // been reached). To do this, we check to see if all uses of the global
1487 // would trap if the global were null: this proves that they must all
1488 // happen after the malloc.
1489 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1490 return false;
1491
1492 // We can't optimize this if the malloc itself is used in a complex way,
1493 // for example, being stored into multiple globals. This allows the
1494 // malloc to be stored into the specified global, loaded setcc'd, and
1495 // GEP'd. These are all things we could transform to using the global
1496 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001497 SmallPtrSet<const PHINode*, 8> PHIs;
1498 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1499 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001500
1501 // If we have a global that is only initialized with a fixed size malloc,
1502 // transform the program to use global memory instead of malloc'd memory.
1503 // This eliminates dynamic allocation, avoids an indirection accessing the
1504 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001505 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001506 Value *NElems = getMallocArraySize(CI, TD, true);
1507 if (!NElems)
1508 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001509
Evan Cheng86cd4452010-04-14 20:52:55 +00001510 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1511 // Restrict this transformation to only working on small allocations
1512 // (2048 bytes currently), as we don't want to introduce a 16M global or
1513 // something.
1514 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1515 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1516 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001517 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001518
Evan Cheng86cd4452010-04-14 20:52:55 +00001519 // If the allocation is an array of structures, consider transforming this
1520 // into multiple malloc'd arrays, one for each field. This is basically
1521 // SRoA for malloc'd memory.
1522
1523 // If this is an allocation of a fixed size array of structs, analyze as a
1524 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001525 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Evan Cheng86cd4452010-04-14 20:52:55 +00001526 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1527 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001528
Evan Cheng86cd4452010-04-14 20:52:55 +00001529 const StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1530 if (!AllocSTy)
1531 return false;
1532
1533 // This the structure has an unreasonable number of fields, leave it
1534 // alone.
1535 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1536 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1537
1538 // If this is a fixed size array, transform the Malloc to be an alloc of
1539 // structs. malloc [100 x struct],1 -> malloc struct, 100
1540 if (const ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1541 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1542 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1543 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1544 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1545 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1546 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001547 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001548 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1549 CI->replaceAllUsesWith(Cast);
1550 CI->eraseFromParent();
1551 CI = dyn_cast<BitCastInst>(Malloc) ?
1552 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1553 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001554
Evan Cheng86cd4452010-04-14 20:52:55 +00001555 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1556 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001557 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001558
Victor Hernandez83d63912009-09-18 22:35:49 +00001559 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001560}
Victor Hernandez83d63912009-09-18 22:35:49 +00001561
Chris Lattner9b34a612004-10-09 21:48:45 +00001562// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1563// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001564static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001565 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001566 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001567 // Ignore no-op GEPs and bitcasts.
1568 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001569
Chris Lattner708148e2004-10-10 23:14:11 +00001570 // If we are dealing with a pointer global that is initialized to null and
1571 // only has one (non-null) value stored into it, then we can optimize any
1572 // users of the loaded value (often calls and loads) that would trap if the
1573 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001574 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001575 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001576 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1577 if (GV->getInitializer()->getType() != SOVC->getType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001578 SOVC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001579 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001580
Chris Lattner708148e2004-10-10 23:14:11 +00001581 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001582 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001583 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001584 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001585 const Type* MallocType = getMallocAllocatedType(CI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001586 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001587 GVI, TD))
1588 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001589 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001590 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001591
Chris Lattner9b34a612004-10-09 21:48:45 +00001592 return false;
1593}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001594
Chris Lattner58e44f42008-01-14 01:17:44 +00001595/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1596/// two values ever stored into GV are its initializer and OtherVal. See if we
1597/// can shrink the global into a boolean and select between the two values
1598/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001599static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001600 const Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001601
Chris Lattner58e44f42008-01-14 01:17:44 +00001602 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001603 // an FP value, pointer or vector, don't do this optimization because a select
1604 // between them is very expensive and unlikely to lead to later
1605 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1606 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001607 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001608 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001609 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001610 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001611
Chris Lattner58e44f42008-01-14 01:17:44 +00001612 // Walk the use list of the global seeing if all the uses are load or store.
1613 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001614 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1615 User *U = *I;
1616 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001617 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001618 }
1619
David Greene3215b0e2010-01-05 01:28:05 +00001620 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001621
Chris Lattner96a86b22004-12-12 05:53:50 +00001622 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001623 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1624 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001625 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001626 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001627 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001628 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001629 GV->getParent()->getGlobalList().insert(GV, NewGV);
1630
1631 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001632 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001633 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001634
1635 // If initialized to zero and storing one into the global, we can use a cast
1636 // instead of a select to synthesize the desired value.
1637 bool IsOneZero = false;
1638 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001639 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001640
1641 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001642 Instruction *UI = cast<Instruction>(GV->use_back());
1643 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001644 // Change the store into a boolean store.
1645 bool StoringOther = SI->getOperand(0) == OtherVal;
1646 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001647 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001648 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001649 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1650 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001651 else {
1652 // Otherwise, we are storing a previously loaded copy. To do this,
1653 // change the copy from copying the original value to just copying the
1654 // bool.
1655 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1656
Gabor Greif9e4f2432010-06-24 14:42:01 +00001657 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001658 // select instruction. If not, it will be a load of the original
1659 // global.
1660 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1661 assert(LI->getOperand(0) == GV && "Not a copy!");
1662 // Insert a new load, to preserve the saved value.
1663 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1664 } else {
1665 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1666 "This is not a form that we understand!");
1667 StoreVal = StoredVal->getOperand(0);
1668 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1669 }
1670 }
1671 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001672 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001673 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001674 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001675 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001676 Value *NSI;
1677 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001678 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001679 else
Gabor Greif051a9502008-04-06 20:25:17 +00001680 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001681 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001682 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001683 }
1684 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001685 }
1686
1687 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001688 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001689}
1690
1691
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001692/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1693/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001694bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001695 Module::global_iterator &GVI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001696 SmallPtrSet<const PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001697 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001698 GV->removeDeadConstantUsers();
1699
1700 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001701 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001702 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001703 ++NumDeleted;
1704 return true;
1705 }
1706
1707 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001708#if 0
David Greene3215b0e2010-01-05 01:28:05 +00001709 DEBUG(dbgs() << "Global: " << *GV);
1710 DEBUG(dbgs() << " isLoaded = " << GS.isLoaded << "\n");
1711 DEBUG(dbgs() << " StoredType = ");
Chris Lattnercff16732006-09-30 19:40:30 +00001712 switch (GS.StoredType) {
David Greene3215b0e2010-01-05 01:28:05 +00001713 case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break;
1714 case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n");
Victor Hernandez631f3c02009-11-07 00:41:19 +00001715 break;
David Greene3215b0e2010-01-05 01:28:05 +00001716 case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break;
1717 case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break;
Chris Lattnercff16732006-09-30 19:40:30 +00001718 }
1719 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
David Greene3215b0e2010-01-05 01:28:05 +00001720 DEBUG(dbgs() << " StoredOnceValue = " << *GS.StoredOnceValue << "\n");
Chris Lattnercff16732006-09-30 19:40:30 +00001721 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Gabor Greif27236912010-04-07 18:59:26 +00001722 DEBUG(dbgs() << " AccessingFunction = "
1723 << GS.AccessingFunction->getName() << "\n");
David Greene3215b0e2010-01-05 01:28:05 +00001724 DEBUG(dbgs() << " HasMultipleAccessingFunctions = "
Victor Hernandez631f3c02009-11-07 00:41:19 +00001725 << GS.HasMultipleAccessingFunctions << "\n");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001726 DEBUG(dbgs() << " HasNonInstructionUser = "
Victor Hernandez631f3c02009-11-07 00:41:19 +00001727 << GS.HasNonInstructionUser<<"\n");
David Greene3215b0e2010-01-05 01:28:05 +00001728 DEBUG(dbgs() << "\n");
Chris Lattnercff16732006-09-30 19:40:30 +00001729#endif
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001730
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001731 // If this is a first class global and has only one accessing function
1732 // and this function is main (which we know is not recursive we can make
1733 // this global a local variable) we replace the global with a local alloca
1734 // in this function.
1735 //
Dan Gohman399101a2008-05-23 00:17:26 +00001736 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001737 // are just replacing static memory to stack memory.
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001738 //
1739 // If the global is in different address space, don't bring it to stack.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001740 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001741 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001742 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001743 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001744 GS.AccessingFunction->hasExternalLinkage() &&
1745 GV->getType()->getAddressSpace() == 0) {
David Greene3215b0e2010-01-05 01:28:05 +00001746 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001747 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1748 ->getEntryBlock().begin());
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001749 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001750 // FIXME: Pass Global's alignment when globals have alignment
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001751 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001752 if (!isa<UndefValue>(GV->getInitializer()))
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001753 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001754
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001755 GV->replaceAllUsesWith(Alloca);
1756 GV->eraseFromParent();
1757 ++NumLocalized;
1758 return true;
1759 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001760
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001761 // If the global is never loaded (but may be stored to), it is dead.
1762 // Delete it now.
1763 if (!GS.isLoaded) {
David Greene3215b0e2010-01-05 01:28:05 +00001764 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattner930f4752004-10-09 03:32:52 +00001765
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001766 // Delete any stores we can find to the global. We may not be able to
1767 // make it completely dead though.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001768 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001769
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001770 // If the global is dead now, delete it.
1771 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001772 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001773 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001774 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001775 }
Chris Lattner930f4752004-10-09 03:32:52 +00001776 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001777
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001778 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
David Greene3215b0e2010-01-05 01:28:05 +00001779 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001780 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001781
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001782 // Clean up any obviously simplifiable users now.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001783 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001784
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001785 // If the global is dead now, just nuke it.
1786 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001787 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
Chris Lattnerbdff5482009-08-23 04:37:46 +00001788 << "all users and delete global!\n");
Chris Lattner7a7ed022004-10-16 18:09:00 +00001789 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001790 ++NumDeleted;
1791 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001792
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001793 ++NumMarked;
1794 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001795 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Dan Gohman7eb28f32009-08-14 00:11:03 +00001796 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
Chris Lattner7b550cc2009-11-06 04:27:31 +00001797 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
Dan Gohman7eb28f32009-08-14 00:11:03 +00001798 GVI = FirstNewGV; // Don't skip the newly produced globals!
1799 return true;
1800 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001801 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001802 // If the initial value for the global was an undef value, and if only
1803 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001804 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001805 // global. This allows us to mark it constant.
1806 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1807 if (isa<UndefValue>(GV->getInitializer())) {
1808 // Change the initial value here.
1809 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001810
Chris Lattner96a86b22004-12-12 05:53:50 +00001811 // Clean up any obviously simplifiable users now.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001812 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001813
Chris Lattner96a86b22004-12-12 05:53:50 +00001814 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001815 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Chris Lattnerbdff5482009-08-23 04:37:46 +00001816 << "simplify all users and delete global!\n");
Chris Lattner96a86b22004-12-12 05:53:50 +00001817 GV->eraseFromParent();
1818 ++NumDeleted;
1819 } else {
1820 GVI = GV;
1821 }
1822 ++NumSubstitute;
1823 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001824 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001825
Chris Lattner9b34a612004-10-09 21:48:45 +00001826 // Try to optimize globals based on the knowledge that only one value
1827 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001828 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001829 getAnalysisIfAvailable<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001830 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001831
1832 // Otherwise, if the global was not a boolean, we can shrink it to be a
1833 // boolean.
1834 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001835 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001836 ++NumShrunkToBool;
1837 return true;
1838 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001839 }
1840 }
1841 return false;
1842}
1843
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001844/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1845/// function, changing them to FastCC.
1846static void ChangeCalleesToFastCall(Function *F) {
1847 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001848 CallSite User(cast<Instruction>(*UI));
1849 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001850 }
1851}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001852
Devang Patel05988662008-09-25 21:00:45 +00001853static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001854 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001855 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001856 continue;
1857
Duncan Sands548448a2008-02-18 17:32:13 +00001858 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001859 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001860 }
1861
1862 return Attrs;
1863}
1864
1865static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001866 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001867 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001868 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001869 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001870 }
1871}
1872
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001873bool GlobalOpt::OptimizeFunctions(Module &M) {
1874 bool Changed = false;
1875 // Optimize functions.
1876 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1877 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001878 // Functions without names cannot be referenced outside this module.
1879 if (!F->hasName() && !F->isDeclaration())
1880 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001881 F->removeDeadConstantUsers();
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001882 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1883 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001884 Changed = true;
1885 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001886 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001887 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001888 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001889 // If this function has C calling conventions, is not a varargs
1890 // function, and is only called directly, promote it to use the Fast
1891 // calling convention.
1892 F->setCallingConv(CallingConv::Fast);
1893 ChangeCalleesToFastCall(F);
1894 ++NumFastCallFns;
1895 Changed = true;
1896 }
1897
Devang Patel05988662008-09-25 21:00:45 +00001898 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001899 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001900 // The function is not used by a trampoline intrinsic, so it is safe
1901 // to remove the 'nest' attribute.
1902 RemoveNestAttribute(F);
1903 ++NumNestRemoved;
1904 Changed = true;
1905 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001906 }
1907 }
1908 return Changed;
1909}
1910
1911bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1912 bool Changed = false;
1913 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1914 GVI != E; ) {
1915 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001916 // Global variables without names cannot be referenced outside this module.
1917 if (!GV->hasName() && !GV->isDeclaration())
1918 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001919 // Simplify the initializer.
1920 if (GV->hasInitializer())
1921 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohmanf860db22010-04-02 03:04:37 +00001922 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman01b97dd2009-11-23 16:22:21 +00001923 Constant *New = ConstantFoldConstantExpression(CE, TD);
1924 if (New && New != CE)
1925 GV->setInitializer(New);
1926 }
1927 // Do more involved optimizations if the global is internal.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001928 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001929 GV->hasInitializer())
1930 Changed |= ProcessInternalGlobal(GV, GVI);
1931 }
1932 return Changed;
1933}
1934
1935/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1936/// initializers have an init priority of 65535.
1937GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001938 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1939 if (GV == 0) return 0;
1940
1941 // Found it, verify it's an array of { int, void()* }.
1942 const ArrayType *ATy =dyn_cast<ArrayType>(GV->getType()->getElementType());
1943 if (!ATy) return 0;
1944 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1945 if (!STy || STy->getNumElements() != 2 ||
1946 !STy->getElementType(0)->isIntegerTy(32)) return 0;
1947 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1948 if (!PFTy) return 0;
1949 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1950 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
1951 FTy->isVarArg() || FTy->getNumParams() != 0)
1952 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001953
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001954 // Verify that the initializer is simple enough for us to handle. We are
1955 // only allowed to optimize the initializer if it is unique.
1956 if (!GV->hasUniqueInitializer()) return 0;
1957
1958 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1959 if (!CA) return 0;
1960
1961 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1962 ConstantStruct *CS = dyn_cast<ConstantStruct>(*i);
1963 if (CS == 0) return 0;
1964
1965 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1966 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001967
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001968 // Must have a function or null ptr.
1969 if (!isa<Function>(CS->getOperand(1)))
1970 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001971
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001972 // Init priority must be standard.
1973 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1974 if (!CI || CI->getZExtValue() != 65535)
1975 return 0;
1976 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001977
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001978 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001979}
1980
Chris Lattnerdb973e62005-09-26 02:31:18 +00001981/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1982/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001983static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1984 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1985 std::vector<Function*> Result;
1986 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001987 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1988 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001989 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1990 }
1991 return Result;
1992}
1993
Chris Lattnerdb973e62005-09-26 02:31:18 +00001994/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1995/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001996static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001997 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001998 // If we made a change, reassemble the initializer list.
1999 std::vector<Constant*> CSVals;
Chris Lattner7b550cc2009-11-06 04:27:31 +00002000 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002001 CSVals.push_back(0);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002002
Chris Lattnerdb973e62005-09-26 02:31:18 +00002003 // Create the new init list.
2004 std::vector<Constant*> CAList;
2005 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002006 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002007 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002008 } else {
Chris Lattner7b550cc2009-11-06 04:27:31 +00002009 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
2010 false);
Owen Andersondebcb012009-07-29 22:17:13 +00002011 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002012 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002013 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2014 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002015 }
Chris Lattner7b550cc2009-11-06 04:27:31 +00002016 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002017 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002018
Chris Lattnerdb973e62005-09-26 02:31:18 +00002019 // Create the array initializer.
2020 const Type *StructTy =
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002021 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002022 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002023 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002024
Chris Lattnerdb973e62005-09-26 02:31:18 +00002025 // If we didn't change the number of elements, don't create a new GV.
2026 if (CA->getType() == GCL->getInitializer()->getType()) {
2027 GCL->setInitializer(CA);
2028 return GCL;
2029 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002030
Chris Lattnerdb973e62005-09-26 02:31:18 +00002031 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002032 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002033 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002034 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002035 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002036 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002037
Chris Lattnerdb973e62005-09-26 02:31:18 +00002038 // Nuke the old list, replacing any uses with the new one.
2039 if (!GCL->use_empty()) {
2040 Constant *V = NGV;
2041 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002042 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002043 GCL->replaceAllUsesWith(V);
2044 }
2045 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002046
Chris Lattnerdb973e62005-09-26 02:31:18 +00002047 if (Ctors.size())
2048 return NGV;
2049 else
2050 return 0;
2051}
Chris Lattner79c11012005-09-26 04:44:35 +00002052
2053
Chris Lattner1945d582010-12-07 04:33:29 +00002054static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
Chris Lattner79c11012005-09-26 04:44:35 +00002055 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2056 Constant *R = ComputedValues[V];
2057 assert(R && "Reference to an uncomputed value!");
2058 return R;
2059}
2060
Chris Lattner1945d582010-12-07 04:33:29 +00002061static inline bool
2062isSimpleEnoughValueToCommit(Constant *C,
2063 SmallPtrSet<Constant*, 8> &SimpleConstants);
2064
2065
2066/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2067/// handled by the code generator. We don't want to generate something like:
2068/// void *X = &X/42;
2069/// because the code generator doesn't have a relocation that can handle that.
2070///
2071/// This function should be called if C was not found (but just got inserted)
2072/// in SimpleConstants to avoid having to rescan the same constants all the
2073/// time.
2074static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2075 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2076 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2077 // all supported.
2078 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2079 isa<GlobalValue>(C))
2080 return true;
2081
2082 // Aggregate values are safe if all their elements are.
2083 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2084 isa<ConstantVector>(C)) {
2085 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2086 Constant *Op = cast<Constant>(C->getOperand(i));
2087 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants))
2088 return false;
2089 }
2090 return true;
2091 }
2092
2093 // We don't know exactly what relocations are allowed in constant expressions,
2094 // so we allow &global+constantoffset, which is safe and uniformly supported
2095 // across targets.
2096 ConstantExpr *CE = cast<ConstantExpr>(C);
2097 switch (CE->getOpcode()) {
2098 case Instruction::BitCast:
2099 case Instruction::IntToPtr:
2100 case Instruction::PtrToInt:
2101 // These casts are always fine if the casted value is.
2102 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2103
2104 // GEP is fine if it is simple + constant offset.
2105 case Instruction::GetElementPtr:
2106 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2107 if (!isa<ConstantInt>(CE->getOperand(i)))
2108 return false;
2109 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2110
2111 case Instruction::Add:
2112 // We allow simple+cst.
2113 if (!isa<ConstantInt>(CE->getOperand(1)))
2114 return false;
2115 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2116 }
2117 return false;
2118}
2119
2120static inline bool
2121isSimpleEnoughValueToCommit(Constant *C,
2122 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2123 // If we already checked this constant, we win.
2124 if (!SimpleConstants.insert(C)) return true;
2125 // Check the constant.
2126 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants);
2127}
2128
2129
Chris Lattner79c11012005-09-26 04:44:35 +00002130/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2131/// enough for us to understand. In particular, if it is a cast of something,
2132/// we punt. We basically just support direct accesses to globals and GEP's of
2133/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002134static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002135 // Conservatively, avoid aggregate types. This is because we don't
2136 // want to worry about them partially overlapping other stores.
2137 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2138 return false;
2139
Dan Gohmanfd54a892009-09-07 22:31:26 +00002140 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002141 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002142 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002143 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002144
Chris Lattner798b4d52005-09-26 06:52:44 +00002145 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2146 // Handle a constantexpr gep.
2147 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002148 isa<GlobalVariable>(CE->getOperand(0)) &&
2149 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002150 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002151 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002152 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002153 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002154 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002155
Dan Gohman80bdc962009-09-07 22:44:55 +00002156 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002157 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002158 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002159
2160 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002161 // notional bounds of the corresponding static array types.
2162 if (!CE->isGEPWithNoNotionalOverIndexing())
2163 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002164
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002165 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002166 }
Chris Lattner79c11012005-09-26 04:44:35 +00002167 return false;
2168}
2169
Chris Lattner798b4d52005-09-26 06:52:44 +00002170/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2171/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2172/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2173static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002174 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002175 // Base case of the recursion.
2176 if (OpNo == Addr->getNumOperands()) {
2177 assert(Val->getType() == Init->getType() && "Type mismatch!");
2178 return Val;
2179 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002180
Chris Lattnera0e9a242010-01-07 01:16:21 +00002181 std::vector<Constant*> Elts;
Chris Lattner798b4d52005-09-26 06:52:44 +00002182 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002183
2184 // Break up the constant into its elements.
2185 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002186 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2187 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002188 } else if (isa<ConstantAggregateZero>(Init)) {
2189 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002190 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002191 } else if (isa<UndefValue>(Init)) {
2192 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002193 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002194 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002195 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002196 " ConstantFoldLoadThroughGEPConstantExpr");
2197 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002198
Chris Lattner798b4d52005-09-26 06:52:44 +00002199 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002200 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2201 unsigned Idx = CU->getZExtValue();
2202 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002203 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002204
Chris Lattner798b4d52005-09-26 06:52:44 +00002205 // Return the modified struct.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002206 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2207 STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002208 } else {
2209 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002210 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002211
Chris Lattnera0e9a242010-01-07 01:16:21 +00002212 uint64_t NumElts;
2213 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2214 NumElts = ATy->getNumElements();
2215 else
2216 NumElts = cast<VectorType>(InitTy)->getNumElements();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002217
2218
Chris Lattner798b4d52005-09-26 06:52:44 +00002219 // Break up the array into elements.
Chris Lattner798b4d52005-09-26 06:52:44 +00002220 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002221 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2222 Elts.push_back(cast<Constant>(*i));
Chris Lattner4039bd02010-01-07 01:20:20 +00002223 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2224 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2225 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002226 } else if (isa<ConstantAggregateZero>(Init)) {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002227 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002228 } else {
Chris Lattnera0e9a242010-01-07 01:16:21 +00002229 assert(isa<UndefValue>(Init) && "This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002230 " ConstantFoldLoadThroughGEPConstantExpr");
Chris Lattnera0e9a242010-01-07 01:16:21 +00002231 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
Chris Lattner798b4d52005-09-26 06:52:44 +00002232 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002233
Chris Lattnera0e9a242010-01-07 01:16:21 +00002234 assert(CI->getZExtValue() < NumElts);
Reid Spencerb83eb642006-10-20 07:07:24 +00002235 Elts[CI->getZExtValue()] =
Chris Lattner7b550cc2009-11-06 04:27:31 +00002236 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002237
Duncan Sands1df98592010-02-16 11:11:14 +00002238 if (Init->getType()->isArrayTy())
Chris Lattnera0e9a242010-01-07 01:16:21 +00002239 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2240 else
2241 return ConstantVector::get(&Elts[0], Elts.size());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002242 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002243}
2244
Chris Lattner79c11012005-09-26 04:44:35 +00002245/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2246/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002247static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002248 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2249 assert(GV->hasInitializer());
2250 GV->setInitializer(Val);
2251 return;
2252 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002253
Chris Lattner798b4d52005-09-26 06:52:44 +00002254 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2255 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002256 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002257}
2258
Chris Lattner562a0552005-09-26 05:16:34 +00002259/// ComputeLoadResult - Return the value that would be computed by a load from
2260/// P after the stores reflected by 'memory' have been performed. If we can't
2261/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002262static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002263 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002264 // If this memory location has been recently stored, use the stored value: it
2265 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002266 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002267 if (I != Memory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002268
Chris Lattner04de1cf2005-09-26 05:15:37 +00002269 // Access it.
2270 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002271 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002272 return GV->getInitializer();
2273 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002274 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002275
Chris Lattner798b4d52005-09-26 06:52:44 +00002276 // Handle a constantexpr getelementptr.
2277 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2278 if (CE->getOpcode() == Instruction::GetElementPtr &&
2279 isa<GlobalVariable>(CE->getOperand(0))) {
2280 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002281 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002282 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002283 }
2284
2285 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002286}
2287
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002288/// EvaluateFunction - Evaluate a call to function F, returning true if
2289/// successful, false if we can't evaluate it. ActualArgs contains the formal
2290/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002291static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002292 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002293 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002294 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner1945d582010-12-07 04:33:29 +00002295 std::vector<GlobalVariable*> &AllocaTmps,
2296 SmallPtrSet<Constant*, 8> &SimpleConstants,
2297 const TargetData *TD) {
Chris Lattnercd271422005-09-27 04:45:34 +00002298 // Check to see if this function is already executing (recursion). If so,
2299 // bail out. TODO: we might want to accept limited recursion.
2300 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2301 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002302
Chris Lattnercd271422005-09-27 04:45:34 +00002303 CallStack.push_back(F);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002304
Chris Lattner79c11012005-09-26 04:44:35 +00002305 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002306 DenseMap<Value*, Constant*> Values;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002307
Chris Lattnercd271422005-09-27 04:45:34 +00002308 // Initialize arguments to the incoming values specified.
2309 unsigned ArgNo = 0;
2310 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2311 ++AI, ++ArgNo)
2312 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002313
Chris Lattnercdf98be2005-09-26 04:57:38 +00002314 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2315 /// we can only evaluate any one basic block at most once. This set keeps
2316 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002317 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002318
Chris Lattner79c11012005-09-26 04:44:35 +00002319 // CurInst - The current instruction we're evaluating.
2320 BasicBlock::iterator CurInst = F->begin()->begin();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002321
Chris Lattner79c11012005-09-26 04:44:35 +00002322 // This is the main evaluation loop.
2323 while (1) {
2324 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002325
Chris Lattner79c11012005-09-26 04:44:35 +00002326 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002327 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002328 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002329 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002330 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002331 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002332
Chris Lattner79c11012005-09-26 04:44:35 +00002333 Constant *Val = getVal(Values, SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002334
2335 // If this might be too difficult for the backend to handle (e.g. the addr
2336 // of one global variable divided by another) then we can't commit it.
2337 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants))
2338 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002339 MutatedMemory[Ptr] = Val;
2340 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002341 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002342 getVal(Values, BO->getOperand(0)),
2343 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002344 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002345 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002346 getVal(Values, CI->getOperand(0)),
2347 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002348 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002349 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002350 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002351 CI->getType());
2352 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +00002353 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Eric Christopher551754c2010-04-16 23:37:20 +00002354 getVal(Values, SI->getOperand(1)),
2355 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002356 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2357 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002358 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002359 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2360 i != e; ++i)
2361 GEPOps.push_back(getVal(Values, *i));
Dan Gohman4a7e6b72009-09-07 22:34:43 +00002362 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2363 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2364 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002365 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002366 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002367 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002368 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002369 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002370 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002371 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002372 const Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002373 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002374 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002375 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002376 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002377 InstResult = AllocaTmps.back();
Chris Lattnercd271422005-09-27 04:45:34 +00002378 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002379
2380 // Debug info can safely be ignored here.
2381 if (isa<DbgInfoIntrinsic>(CI)) {
2382 ++CurInst;
2383 continue;
2384 }
2385
Chris Lattner7cd580f2006-07-07 21:37:01 +00002386 // Cannot handle inline asm.
Gabor Greifa9b23132010-04-20 13:13:04 +00002387 if (isa<InlineAsm>(CI->getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002388
Chris Lattnercd271422005-09-27 04:45:34 +00002389 // Resolve function pointers.
Gabor Greifa3997812010-07-22 10:37:47 +00002390 Function *Callee = dyn_cast<Function>(getVal(Values,
2391 CI->getCalledValue()));
Chris Lattnercd271422005-09-27 04:45:34 +00002392 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002393
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002394 SmallVector<Constant*, 8> Formals;
Gabor Greif9e4f2432010-06-24 14:42:01 +00002395 CallSite CS(CI);
2396 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
Gabor Greif5e463212008-05-29 01:59:18 +00002397 i != e; ++i)
2398 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002399
Reid Spencer5cbf9852007-01-30 20:08:39 +00002400 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002401 // If this is a function we can constant fold, do it.
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002402 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
Chris Lattner6c1f5652007-01-30 23:14:52 +00002403 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002404 InstResult = C;
2405 } else {
2406 return false;
2407 }
2408 } else {
2409 if (Callee->getFunctionType()->isVarArg())
2410 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002411
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002412 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002413 // Execute the call, if successful, use the return value.
2414 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002415 MutatedMemory, AllocaTmps, SimpleConstants, TD))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002416 return false;
2417 InstResult = RetVal;
2418 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002419 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002420 BasicBlock *NewBB = 0;
2421 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2422 if (BI->isUnconditional()) {
2423 NewBB = BI->getSuccessor(0);
2424 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002425 ConstantInt *Cond =
2426 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002427 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002428
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002429 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002430 }
2431 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2432 ConstantInt *Val =
2433 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002434 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002435 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002436 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2437 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2438 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2439 NewBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002440 else
2441 return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002442 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002443 if (RI->getNumOperands())
2444 RetVal = getVal(Values, RI->getOperand(0));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002445
Chris Lattnercd271422005-09-27 04:45:34 +00002446 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002447 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002448 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002449 // invoke, unwind, unreachable.
2450 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002451 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002452
Chris Lattnercdf98be2005-09-26 04:57:38 +00002453 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002454 // executed the new block before. If so, we have a looping function,
2455 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002456 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002457 return false; // looped!
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002458
Chris Lattnercdf98be2005-09-26 04:57:38 +00002459 // Okay, we have never been in this block before. Check to see if there
2460 // are any PHI nodes. If so, evaluate them with information about where
2461 // we came from.
2462 BasicBlock *OldBB = CurInst->getParent();
2463 CurInst = NewBB->begin();
2464 PHINode *PN;
2465 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2466 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2467
2468 // Do NOT increment CurInst. We know that the terminator had no value.
2469 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002470 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002471 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002472 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002473 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002474
Chris Lattner1945d582010-12-07 04:33:29 +00002475 if (!CurInst->use_empty()) {
2476 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2477 InstResult = ConstantFoldConstantExpression(CE, TD);
2478
Chris Lattner79c11012005-09-26 04:44:35 +00002479 Values[CurInst] = InstResult;
Chris Lattner1945d582010-12-07 04:33:29 +00002480 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002481
Chris Lattner79c11012005-09-26 04:44:35 +00002482 // Advance program counter.
2483 ++CurInst;
2484 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002485}
2486
2487/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2488/// we can. Return true if we can, false otherwise.
Chris Lattner1945d582010-12-07 04:33:29 +00002489static bool EvaluateStaticConstructor(Function *F, const TargetData *TD) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002490 /// MutatedMemory - For each store we execute, we update this map. Loads
2491 /// check this to get the most up-to-date value. If evaluation is successful,
2492 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002493 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002494
2495 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2496 /// to represent its body. This vector is needed so we can delete the
2497 /// temporary globals when we are done.
2498 std::vector<GlobalVariable*> AllocaTmps;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002499
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002500 /// CallStack - This is used to detect recursion. In pathological situations
2501 /// we could hit exponential behavior, but at least there is nothing
2502 /// unbounded.
2503 std::vector<Function*> CallStack;
2504
Chris Lattner1945d582010-12-07 04:33:29 +00002505 /// SimpleConstants - These are constants we have checked and know to be
2506 /// simple enough to live in a static initializer of a global.
2507 SmallPtrSet<Constant*, 8> SimpleConstants;
2508
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002509 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002510 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002511 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2512 SmallVector<Constant*, 0>(), CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002513 MutatedMemory, AllocaTmps,
2514 SimpleConstants, TD);
2515
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002516 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002517 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002518 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002519 << F->getName() << "' to " << MutatedMemory.size()
2520 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002521 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002522 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002523 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002524 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002525
Chris Lattnera22fdb02005-09-26 17:07:09 +00002526 // At this point, we are done interpreting. If we created any 'alloca'
2527 // temporaries, release them now.
2528 while (!AllocaTmps.empty()) {
2529 GlobalVariable *Tmp = AllocaTmps.back();
2530 AllocaTmps.pop_back();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002531
Chris Lattnera22fdb02005-09-26 17:07:09 +00002532 // If there are still users of the alloca, the program is doing something
2533 // silly, e.g. storing the address of the alloca somewhere and using it
2534 // later. Since this is undefined, we'll just make it be null.
2535 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002536 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002537 delete Tmp;
2538 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002539
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002540 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002541}
2542
Chris Lattnerdb973e62005-09-26 02:31:18 +00002543
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002544
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002545/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2546/// Return true if anything changed.
2547bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2548 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2549 bool MadeChange = false;
2550 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002551
Chris Lattner1945d582010-12-07 04:33:29 +00002552 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002553 // Loop over global ctors, optimizing them when we can.
2554 for (unsigned i = 0; i != Ctors.size(); ++i) {
2555 Function *F = Ctors[i];
2556 // Found a null terminator in the middle of the list, prune off the rest of
2557 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002558 if (F == 0) {
2559 if (i != Ctors.size()-1) {
2560 Ctors.resize(i+1);
2561 MadeChange = true;
2562 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002563 break;
2564 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002565
Chris Lattner79c11012005-09-26 04:44:35 +00002566 // We cannot simplify external ctor functions.
2567 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002568
Chris Lattner79c11012005-09-26 04:44:35 +00002569 // If we can evaluate the ctor at compile time, do.
Chris Lattner1945d582010-12-07 04:33:29 +00002570 if (EvaluateStaticConstructor(F, TD)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002571 Ctors.erase(Ctors.begin()+i);
2572 MadeChange = true;
2573 --i;
2574 ++NumCtorsEvaluated;
2575 continue;
2576 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002577 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002578
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002579 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002580
Chris Lattner7b550cc2009-11-06 04:27:31 +00002581 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002582 return true;
2583}
2584
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002585bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002586 bool Changed = false;
2587
Duncan Sands177d84e2009-01-07 20:01:06 +00002588 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002589 I != E;) {
2590 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002591 // Aliases without names cannot be referenced outside this module.
2592 if (!J->hasName() && !J->isDeclaration())
2593 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002594 // If the aliasee may change at link time, nothing can be done - bail out.
2595 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002596 continue;
2597
Duncan Sands4782b302009-02-15 09:56:08 +00002598 Constant *Aliasee = J->getAliasee();
2599 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002600 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002601 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2602
2603 // Make all users of the alias use the aliasee instead.
2604 if (!J->use_empty()) {
2605 J->replaceAllUsesWith(Aliasee);
2606 ++NumAliasesResolved;
2607 Changed = true;
2608 }
2609
Duncan Sands7a154cf2009-12-08 10:10:20 +00002610 // If the alias is externally visible, we may still be able to simplify it.
2611 if (!J->hasLocalLinkage()) {
2612 // If the aliasee has internal linkage, give it the name and linkage
2613 // of the alias, and delete the alias. This turns:
2614 // define internal ... @f(...)
2615 // @a = alias ... @f
2616 // into:
2617 // define ... @a(...)
2618 if (!Target->hasLocalLinkage())
2619 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002620
Duncan Sands7a154cf2009-12-08 10:10:20 +00002621 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002622 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002623 // and other attributes of the aliasee with those of the alias.
2624 if (!hasOneUse)
2625 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002626
Duncan Sands7a154cf2009-12-08 10:10:20 +00002627 // Give the aliasee the name, linkage and other attributes of the alias.
2628 Target->takeName(J);
2629 Target->setLinkage(J->getLinkage());
2630 Target->GlobalValue::copyAttributesFrom(J);
2631 }
Duncan Sands4782b302009-02-15 09:56:08 +00002632
2633 // Delete the alias.
2634 M.getAliasList().erase(J);
2635 ++NumAliasesRemoved;
2636 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002637 }
2638
2639 return Changed;
2640}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002641
Chris Lattner7a90b682004-10-07 04:16:33 +00002642bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002643 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002644
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002645 // Try to find the llvm.globalctors list.
2646 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002647
Chris Lattner7a90b682004-10-07 04:16:33 +00002648 bool LocalChange = true;
2649 while (LocalChange) {
2650 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002651
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002652 // Delete functions that are trivially dead, ccc -> fastcc
2653 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002654
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002655 // Optimize global_ctors list.
2656 if (GlobalCtors)
2657 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002658
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002659 // Optimize non-address-taken globals.
2660 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002661
2662 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002663 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002664 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002665 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002666
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002667 // TODO: Move all global ctors functions to the end of the module for code
2668 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002669
Chris Lattner079236d2004-02-25 21:34:36 +00002670 return Changed;
2671}