blob: 46ff307c755d5e6bd7d40a1ea63f8c26f7f74730 [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"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000023#include "llvm/LLVMContext.h"
Chris Lattner079236d2004-02-25 21:34:36 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.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"
Reid Spencer9133fe22007-02-05 23:32:05 +000029#include "llvm/Support/Compiler.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000030#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000033#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000035#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000036#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000037#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000039#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000040#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000041using namespace llvm;
42
Chris Lattner86453c52006-12-19 22:09:18 +000043STATISTIC(NumMarked , "Number of globals marked constant");
44STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
45STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
46STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
47STATISTIC(NumDeleted , "Number of globals deleted");
48STATISTIC(NumFnDeleted , "Number of functions deleted");
49STATISTIC(NumGlobUses , "Number of global uses devirtualized");
50STATISTIC(NumLocalized , "Number of globals localized");
51STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
52STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
53STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000054STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000055STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
56STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Chris Lattner079236d2004-02-25 21:34:36 +000057
Chris Lattner86453c52006-12-19 22:09:18 +000058namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000059 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000060 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner30ba5692004-10-11 05:54:41 +000061 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000062 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000063 GlobalOpt() : ModulePass(&ID) {}
Misha Brukmanfd939082005-04-21 23:48:37 +000064
Chris Lattnerb12914b2004-09-20 04:48:05 +000065 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000066
67 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000068 GlobalVariable *FindGlobalCtors(Module &M);
69 bool OptimizeFunctions(Module &M);
70 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000071 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000072 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000073 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000074 };
Chris Lattner079236d2004-02-25 21:34:36 +000075}
76
Dan Gohman844731a2008-05-13 00:00:25 +000077char GlobalOpt::ID = 0;
78static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
79
Chris Lattner7a90b682004-10-07 04:16:33 +000080ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000081
Dan Gohman844731a2008-05-13 00:00:25 +000082namespace {
83
Chris Lattner7a90b682004-10-07 04:16:33 +000084/// GlobalStatus - As we analyze each global, keep track of some information
85/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000086/// this info will be accurate.
Reid Spencer9133fe22007-02-05 23:32:05 +000087struct VISIBILITY_HIDDEN GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000088 /// isLoaded - True if the global is ever loaded. If the global isn't ever
89 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000090 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000091
92 /// StoredType - Keep track of what stores to the global look like.
93 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000094 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000095 /// NotStored - There is no store to this global. It can thus be marked
96 /// constant.
97 NotStored,
98
99 /// isInitializerStored - This global is stored to, but the only thing
100 /// stored is the constant it was initialized with. This is only tracked
101 /// for scalar globals.
102 isInitializerStored,
103
104 /// isStoredOnce - This global is stored to, but only its initializer and
105 /// one other value is ever stored to it. If this global isStoredOnce, we
106 /// track the value stored to it in StoredOnceValue below. This is only
107 /// tracked for scalar globals.
108 isStoredOnce,
109
110 /// isStored - This global is stored to by multiple values or something else
111 /// that we cannot track.
112 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000113 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000114
115 /// StoredOnceValue - If only one value (besides the initializer constant) is
116 /// ever stored to this global, keep track of what value it is.
117 Value *StoredOnceValue;
118
Chris Lattner25de4e52006-11-01 18:03:33 +0000119 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
120 /// null/false. When the first accessing function is noticed, it is recorded.
121 /// When a second different accessing function is noticed,
122 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000123 Function *AccessingFunction;
124 bool HasMultipleAccessingFunctions;
125
Chris Lattner25de4e52006-11-01 18:03:33 +0000126 /// HasNonInstructionUser - Set to true if this global has a user that is not
127 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000128 bool HasNonInstructionUser;
129
Chris Lattner25de4e52006-11-01 18:03:33 +0000130 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
131 bool HasPHIUser;
132
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000133 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000134 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner6a93fc02008-01-14 01:32:52 +0000135 HasNonInstructionUser(false), HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000136};
Chris Lattnere47ba742004-10-06 20:57:02 +0000137
Dan Gohman844731a2008-05-13 00:00:25 +0000138}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000139
Jay Foade3acf152009-06-09 21:37:11 +0000140// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
141// by constants itself. Note that constants cannot be cyclic, so this test is
142// pretty easy to implement recursively.
143//
144static bool SafeToDestroyConstant(Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000145 if (isa<GlobalValue>(C)) return false;
146
Devang Patel743cdf82009-03-06 01:37:41 +0000147 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
148 if (Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000149 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000150 } else
151 return false;
152 return true;
153}
154
155
Chris Lattner7a90b682004-10-07 04:16:33 +0000156/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
157/// structure. If the global has its address taken, return true to indicate we
158/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000159///
Chris Lattner7a90b682004-10-07 04:16:33 +0000160static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000161 SmallPtrSet<PHINode*, 16> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000162 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000163 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000164 GS.HasNonInstructionUser = true;
165
Chris Lattner7a90b682004-10-07 04:16:33 +0000166 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Chris Lattner670c8892004-10-08 17:32:09 +0000167
Chris Lattner079236d2004-02-25 21:34:36 +0000168 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000169 if (!GS.HasMultipleAccessingFunctions) {
170 Function *F = I->getParent()->getParent();
171 if (GS.AccessingFunction == 0)
172 GS.AccessingFunction = F;
173 else if (GS.AccessingFunction != F)
174 GS.HasMultipleAccessingFunctions = true;
175 }
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000176 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000177 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000178 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Chris Lattner7a90b682004-10-07 04:16:33 +0000179 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000180 // Don't allow a store OF the address, only stores TO the address.
181 if (SI->getOperand(0) == V) return true;
182
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000183 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
184
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000185 // If this is a direct store to the global (i.e., the global is a scalar
186 // value, not an aggregate), keep more specific information about
187 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000188 if (GS.StoredType != GlobalStatus::isStored) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000189 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000190 Value *StoredVal = SI->getOperand(0);
191 if (StoredVal == GV->getInitializer()) {
192 if (GS.StoredType < GlobalStatus::isInitializerStored)
193 GS.StoredType = GlobalStatus::isInitializerStored;
194 } else if (isa<LoadInst>(StoredVal) &&
195 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
196 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000197 if (GS.StoredType < GlobalStatus::isInitializerStored)
198 GS.StoredType = GlobalStatus::isInitializerStored;
199 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
200 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000201 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000202 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000203 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000204 // noop.
205 } else {
206 GS.StoredType = GlobalStatus::isStored;
207 }
208 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000209 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000210 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000211 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000212 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000214 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000215 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000216 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
217 // PHI nodes we can check just like select or GEP instructions, but we
218 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000219 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000220 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000221 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000222 } else if (isa<CmpInst>(I)) {
Chris Lattner8e108442009-03-08 03:37:35 +0000223 } else if (isa<MemTransferInst>(I)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000224 if (I->getOperand(1) == V)
225 GS.StoredType = GlobalStatus::isStored;
226 if (I->getOperand(2) == V)
227 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000228 } else if (isa<MemSetInst>(I)) {
229 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
230 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000231 } else {
232 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000233 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000234 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000235 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000236 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000237 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000238 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000239 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000240 GS.HasNonInstructionUser = true;
241 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000242 return true;
243 }
244
245 return false;
246}
247
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000248static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx,
Owen Andersone922c022009-07-22 00:24:57 +0000249 LLVMContext &Context) {
Chris Lattner670c8892004-10-08 17:32:09 +0000250 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
251 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000252 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000253
Chris Lattner670c8892004-10-08 17:32:09 +0000254 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
255 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
256 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
257 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000258 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000259 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000260 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000261 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
262 if (IdxV < STy->getNumElements())
Owen Andersona7235ea2009-07-31 20:28:14 +0000263 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000264 } else if (const SequentialType *STy =
265 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000266 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000267 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000268 } else if (isa<UndefValue>(Agg)) {
269 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
270 if (IdxV < STy->getNumElements())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000271 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000272 } else if (const SequentialType *STy =
273 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000274 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000275 }
Chris Lattner670c8892004-10-08 17:32:09 +0000276 }
277 return 0;
278}
Chris Lattner7a90b682004-10-07 04:16:33 +0000279
Chris Lattner7a90b682004-10-07 04:16:33 +0000280
Chris Lattnere47ba742004-10-06 20:57:02 +0000281/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
282/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000283/// quick scan over the use list to clean up the easy and obvious cruft. This
284/// returns true if it made a change.
Owen Anderson50895512009-07-06 18:42:36 +0000285static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Owen Andersone922c022009-07-22 00:24:57 +0000286 LLVMContext &Context) {
Chris Lattner031955d2004-10-10 16:43:46 +0000287 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000288 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
289 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000290
Chris Lattner7a90b682004-10-07 04:16:33 +0000291 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000292 if (Init) {
293 // Replace the load with the initializer.
294 LI->replaceAllUsesWith(Init);
295 LI->eraseFromParent();
296 Changed = true;
297 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000298 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000299 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000300 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000301 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000302 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
303 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000304 Constant *SubInit = 0;
305 if (Init)
Owen Anderson50895512009-07-06 18:42:36 +0000306 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
307 Changed |= CleanupConstantGlobalUsers(CE, SubInit, Context);
Reid Spencer3da59db2006-11-27 01:05:10 +0000308 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000309 isa<PointerType>(CE->getType())) {
310 // Pointer cast, delete any stores and memsets to the global.
Owen Anderson50895512009-07-06 18:42:36 +0000311 Changed |= CleanupConstantGlobalUsers(CE, 0, Context);
Chris Lattner35c81b02005-02-27 18:58:52 +0000312 }
313
314 if (CE->use_empty()) {
315 CE->destroyConstant();
316 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000317 }
318 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000319 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
320 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
321 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000322 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000323 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
324 ConstantExpr *CE =
Owen Anderson50895512009-07-06 18:42:36 +0000325 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, Context));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000326 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Owen Anderson50895512009-07-06 18:42:36 +0000327 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000328 }
Owen Anderson50895512009-07-06 18:42:36 +0000329 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, Context);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000330
Chris Lattner031955d2004-10-10 16:43:46 +0000331 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000332 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000333 Changed = true;
334 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000335 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
336 if (MI->getRawDest() == V) {
337 MI->eraseFromParent();
338 Changed = true;
339 }
340
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000341 } else if (Constant *C = dyn_cast<Constant>(U)) {
342 // If we have a chain of dead constantexprs or other things dangling from
343 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000344 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000345 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000346 // This could have invalidated UI, start over from scratch.
Owen Anderson50895512009-07-06 18:42:36 +0000347 CleanupConstantGlobalUsers(V, Init, Context);
Chris Lattner031955d2004-10-10 16:43:46 +0000348 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000349 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000350 }
351 }
Chris Lattner031955d2004-10-10 16:43:46 +0000352 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000353}
354
Chris Lattner941db492008-01-14 02:09:12 +0000355/// isSafeSROAElementUse - Return true if the specified instruction is a safe
356/// user of a derived expression from a global that we want to SROA.
357static bool isSafeSROAElementUse(Value *V) {
358 // We might have a dead and dangling constant hanging off of here.
359 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000360 return SafeToDestroyConstant(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000361
Chris Lattner941db492008-01-14 02:09:12 +0000362 Instruction *I = dyn_cast<Instruction>(V);
363 if (!I) return false;
364
365 // Loads are ok.
366 if (isa<LoadInst>(I)) return true;
367
368 // Stores *to* the pointer are ok.
369 if (StoreInst *SI = dyn_cast<StoreInst>(I))
370 return SI->getOperand(0) != V;
371
372 // Otherwise, it must be a GEP.
373 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
374 if (GEPI == 0) return false;
375
376 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
377 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
378 return false;
379
380 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
381 I != E; ++I)
382 if (!isSafeSROAElementUse(*I))
383 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000384 return true;
385}
386
Chris Lattner941db492008-01-14 02:09:12 +0000387
388/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
389/// Look at it and its uses and decide whether it is safe to SROA this global.
390///
391static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
392 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
393 if (!isa<GetElementPtrInst>(U) &&
394 (!isa<ConstantExpr>(U) ||
395 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
396 return false;
397
398 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
399 // don't like < 3 operand CE's, and we don't like non-constant integer
400 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
401 // value of C.
402 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
403 !cast<Constant>(U->getOperand(1))->isNullValue() ||
404 !isa<ConstantInt>(U->getOperand(2)))
405 return false;
406
407 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
408 ++GEPI; // Skip over the pointer index.
409
410 // If this is a use of an array allocation, do a bit more checking for sanity.
411 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
412 uint64_t NumElements = AT->getNumElements();
413 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
414
415 // Check to make sure that index falls within the array. If not,
416 // something funny is going on, so we won't do the optimization.
417 //
418 if (Idx->getZExtValue() >= NumElements)
419 return false;
420
421 // We cannot scalar repl this level of the array unless any array
422 // sub-indices are in-range constants. In particular, consider:
423 // A[0][i]. We cannot know that the user isn't doing invalid things like
424 // allowing i to index an out-of-range subscript that accesses A[1].
425 //
426 // Scalar replacing *just* the outer index of the array is probably not
427 // going to be a win anyway, so just give up.
428 for (++GEPI; // Skip array index.
429 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
430 ++GEPI) {
431 uint64_t NumElements;
432 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
433 NumElements = SubArrayTy->getNumElements();
434 else
435 NumElements = cast<VectorType>(*GEPI)->getNumElements();
436
437 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
438 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
439 return false;
440 }
441 }
442
443 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
444 if (!isSafeSROAElementUse(*I))
445 return false;
446 return true;
447}
448
449/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
450/// is safe for us to perform this transformation.
451///
452static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
453 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
454 UI != E; ++UI) {
455 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
456 return false;
457 }
458 return true;
459}
460
461
Chris Lattner670c8892004-10-08 17:32:09 +0000462/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
463/// variable. This opens the door for other optimizations by exposing the
464/// behavior of the program in a more fine-grained way. We have determined that
465/// this transformation is safe already. We return the first global variable we
466/// insert so that the caller can reprocess it.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000467static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +0000468 LLVMContext &Context) {
Chris Lattner727c2102008-01-14 01:31:05 +0000469 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000470 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000471 return 0;
472
Rafael Espindolabb46f522009-01-15 20:18:42 +0000473 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000474 Constant *Init = GV->getInitializer();
475 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000476
Chris Lattner670c8892004-10-08 17:32:09 +0000477 std::vector<GlobalVariable*> NewGlobals;
478 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
479
Chris Lattner998182b2008-04-26 07:40:11 +0000480 // Get the alignment of the global, either explicit or target-specific.
481 unsigned StartAlignment = GV->getAlignment();
482 if (StartAlignment == 0)
483 StartAlignment = TD.getABITypeAlignment(GV->getType());
484
Chris Lattner670c8892004-10-08 17:32:09 +0000485 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
486 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000487 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000488 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
489 Constant *In = getAggregateConstantElement(Init,
Owen Anderson1d0be152009-08-13 21:58:54 +0000490 ConstantInt::get(Type::getInt32Ty(Context), i),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000491 Context);
Chris Lattner670c8892004-10-08 17:32:09 +0000492 assert(In && "Couldn't get element of initializer?");
Owen Andersone922c022009-07-22 00:24:57 +0000493 GlobalVariable *NGV = new GlobalVariable(Context,
Owen Andersone9b11b42009-07-08 19:03:57 +0000494 STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000495 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000496 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000497 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000498 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000499 Globals.insert(GV, NGV);
500 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000501
502 // Calculate the known alignment of the field. If the original aggregate
503 // had 256 byte alignment for example, something might depend on that:
504 // propagate info to each field.
505 uint64_t FieldOffset = Layout.getElementOffset(i);
506 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
507 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
508 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000509 }
510 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
511 unsigned NumElements = 0;
512 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
513 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000514 else
Chris Lattner998182b2008-04-26 07:40:11 +0000515 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000516
Chris Lattner1f21ef12005-02-23 16:53:04 +0000517 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000518 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000519 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000520
Duncan Sands777d2302009-05-09 07:06:46 +0000521 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000522 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000523 for (unsigned i = 0, e = NumElements; i != e; ++i) {
524 Constant *In = getAggregateConstantElement(Init,
Owen Anderson1d0be152009-08-13 21:58:54 +0000525 ConstantInt::get(Type::getInt32Ty(Context), i),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000526 Context);
Chris Lattner670c8892004-10-08 17:32:09 +0000527 assert(In && "Couldn't get element of initializer?");
528
Owen Andersone922c022009-07-22 00:24:57 +0000529 GlobalVariable *NGV = new GlobalVariable(Context,
Owen Andersone9b11b42009-07-08 19:03:57 +0000530 STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000531 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000532 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000533 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000534 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000535 Globals.insert(GV, NGV);
536 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000537
538 // Calculate the known alignment of the field. If the original aggregate
539 // had 256 byte alignment for example, something might depend on that:
540 // propagate info to each field.
541 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
542 if (NewAlign > EltAlign)
543 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000544 }
545 }
546
547 if (NewGlobals.empty())
548 return 0;
549
Bill Wendling0a81aac2006-11-26 10:02:32 +0000550 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000551
Owen Anderson1d0be152009-08-13 21:58:54 +0000552 Constant *NullInt = Constant::getNullValue(Type::getInt32Ty(Context));
Chris Lattner670c8892004-10-08 17:32:09 +0000553
554 // Loop over all of the uses of the global, replacing the constantexpr geps,
555 // with smaller constantexpr geps or direct references.
556 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000557 User *GEP = GV->use_back();
558 assert(((isa<ConstantExpr>(GEP) &&
559 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
560 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000561
Chris Lattner670c8892004-10-08 17:32:09 +0000562 // Ignore the 1th operand, which has to be zero or else the program is quite
563 // broken (undefined). Get the 2nd operand, which is the structure or array
564 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000565 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000566 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
567
Chris Lattner30ba5692004-10-11 05:54:41 +0000568 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000569
570 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000571 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000573 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000574 Idxs.push_back(NullInt);
575 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
576 Idxs.push_back(CE->getOperand(i));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000577 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000578 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000579 } else {
580 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000581 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000582 Idxs.push_back(NullInt);
583 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
584 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000585 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000586 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000587 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000588 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000589 GEP->replaceAllUsesWith(NewPtr);
590
591 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000592 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000593 else
594 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000595 }
596
Chris Lattnere40e2d12004-10-08 20:25:55 +0000597 // Delete the old global, now that it is dead.
598 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000599 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000600
601 // Loop over the new globals array deleting any globals that are obviously
602 // dead. This can arise due to scalarization of a structure or an array that
603 // has elements that are dead.
604 unsigned FirstGlobal = 0;
605 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
606 if (NewGlobals[i]->use_empty()) {
607 Globals.erase(NewGlobals[i]);
608 if (FirstGlobal == i) ++FirstGlobal;
609 }
610
611 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000612}
613
Chris Lattner9b34a612004-10-09 21:48:45 +0000614/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000615/// value will trap if the value is dynamically null. PHIs keeps track of any
616/// phi nodes we've seen to avoid reprocessing them.
617static bool AllUsesOfValueWillTrapIfNull(Value *V,
618 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000619 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
620 if (isa<LoadInst>(*UI)) {
621 // Will trap.
622 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
623 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000624 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000625 return false; // Storing the value.
626 }
627 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
628 if (CI->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000629 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000630 return false; // Not calling the ptr
631 }
632 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
633 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000634 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000635 return false; // Not calling the ptr
636 }
Chris Lattner81686182007-09-13 16:30:19 +0000637 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
638 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000639 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000640 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
641 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
642 // If we've already seen this phi node, ignore it, it has already been
643 // checked.
644 if (PHIs.insert(PN))
645 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000646 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000647 isa<ConstantPointerNull>(UI->getOperand(1))) {
648 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000649 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000650 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000651 return false;
652 }
653 return true;
654}
655
656/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000657/// from GV will trap if the loaded value is null. Note that this also permits
658/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000659static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
660 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
661 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000662 SmallPtrSet<PHINode*, 8> PHIs;
663 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000664 return false;
665 } else if (isa<StoreInst>(*UI)) {
666 // Ignore stores to the global.
667 } else {
668 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000669 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000670 return false;
671 }
672
673 return true;
674}
675
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000676static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
Owen Andersone922c022009-07-22 00:24:57 +0000677 LLVMContext &Context) {
Chris Lattner708148e2004-10-10 23:14:11 +0000678 bool Changed = false;
679 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
680 Instruction *I = cast<Instruction>(*UI++);
681 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
682 LI->setOperand(0, NewV);
683 Changed = true;
684 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
685 if (SI->getOperand(1) == V) {
686 SI->setOperand(1, NewV);
687 Changed = true;
688 }
689 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
690 if (I->getOperand(0) == V) {
691 // Calling through the pointer! Turn into a direct call, but be careful
692 // that the pointer is not also being passed as an argument.
693 I->setOperand(0, NewV);
694 Changed = true;
695 bool PassedAsArg = false;
696 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
697 if (I->getOperand(i) == V) {
698 PassedAsArg = true;
699 I->setOperand(i, NewV);
700 }
701
702 if (PassedAsArg) {
703 // Being passed as an argument also. Be careful to not invalidate UI!
704 UI = V->use_begin();
705 }
706 }
707 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
708 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000709 ConstantExpr::getCast(CI->getOpcode(),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000710 NewV, CI->getType()), Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000711 if (CI->use_empty()) {
712 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000713 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000714 }
715 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
716 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000717 SmallVector<Constant*, 8> Idxs;
718 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000719 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
720 i != e; ++i)
721 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000722 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000723 else
724 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000725 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000726 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000727 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000728 Idxs.size()), Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000729 if (GEPI->use_empty()) {
730 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000731 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000732 }
733 }
734 }
735
736 return Changed;
737}
738
739
740/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
741/// value stored into it. If there are uses of the loaded value that would trap
742/// if the loaded value is dynamically null, then we know that they cannot be
743/// reachable with a null optimize away the load.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000744static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Owen Andersone922c022009-07-22 00:24:57 +0000745 LLVMContext &Context) {
Chris Lattner708148e2004-10-10 23:14:11 +0000746 bool Changed = false;
747
Chris Lattner92c6bd22009-01-14 00:12:58 +0000748 // Keep track of whether we are able to remove all the uses of the global
749 // other than the store that defines it.
750 bool AllNonStoreUsesGone = true;
751
Chris Lattner708148e2004-10-10 23:14:11 +0000752 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000753 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
754 User *GlobalUser = *GUI++;
755 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000756 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000757 // If we were able to delete all uses of the loads
758 if (LI->use_empty()) {
759 LI->eraseFromParent();
760 Changed = true;
761 } else {
762 AllNonStoreUsesGone = false;
763 }
764 } else if (isa<StoreInst>(GlobalUser)) {
765 // Ignore the store that stores "LV" to the global.
766 assert(GlobalUser->getOperand(1) == GV &&
767 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000768 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000769 AllNonStoreUsesGone = false;
770
771 // If we get here we could have other crazy uses that are transitively
772 // loaded.
773 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
774 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000775 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000776 }
Chris Lattner708148e2004-10-10 23:14:11 +0000777
778 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000779 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000780 ++NumGlobUses;
781 }
782
Chris Lattner708148e2004-10-10 23:14:11 +0000783 // If we nuked all of the loads, then none of the stores are needed either,
784 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000785 if (AllNonStoreUsesGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000786 DOUT << " *** GLOBAL NOW DEAD!\n";
Owen Anderson50895512009-07-06 18:42:36 +0000787 CleanupConstantGlobalUsers(GV, 0, Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000788 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000789 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000790 ++NumDeleted;
791 }
792 Changed = true;
793 }
794 return Changed;
795}
796
Chris Lattner30ba5692004-10-11 05:54:41 +0000797/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
798/// instructions that are foldable.
Owen Andersone922c022009-07-22 00:24:57 +0000799static void ConstantPropUsersOf(Value *V, LLVMContext &Context) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000800 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
801 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Owen Anderson50895512009-07-06 18:42:36 +0000802 if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000803 I->replaceAllUsesWith(NewC);
804
Chris Lattnerd514d822005-02-01 01:23:31 +0000805 // Advance UI to the next non-I use to avoid invalidating it!
806 // Instructions could multiply use V.
807 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000808 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000809 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000810 }
811}
812
813/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
814/// variable, and transforms the program as if it always contained the result of
815/// the specified malloc. Because it is always the result of the specified
816/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000817/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000818static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000819 MallocInst *MI,
Owen Andersone922c022009-07-22 00:24:57 +0000820 LLVMContext &Context) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000821 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000822 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
823
Reid Spencerb83eb642006-10-20 07:07:24 +0000824 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000825 // If we have an array allocation, transform it to a single element
826 // allocation to make the code below simpler.
Owen Andersondebcb012009-07-29 22:17:13 +0000827 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000828 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000829 MallocInst *NewMI =
Owen Anderson1d0be152009-08-13 21:58:54 +0000830 new MallocInst(NewTy, Constant::getNullValue(Type::getInt32Ty(Context)),
Nate Begeman14b05292005-11-05 09:21:28 +0000831 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000832 Value* Indices[2];
Owen Anderson1d0be152009-08-13 21:58:54 +0000833 Indices[0] = Indices[1] = Constant::getNullValue(Type::getInt32Ty(Context));
Gabor Greif051a9502008-04-06 20:25:17 +0000834 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
835 NewMI->getName()+".el0", MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000836 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000837 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000838 MI = NewMI;
839 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000840
Chris Lattner7a7ed022004-10-16 18:09:00 +0000841 // Create the new global variable. The contents of the malloc'd memory is
842 // undefined, so initialize with an undef value.
Chris Lattner998182b2008-04-26 07:40:11 +0000843 // FIXME: This new global should have the alignment returned by malloc. Code
844 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
845 // this would only guarantee some lower alignment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000846 Constant *Init = UndefValue::get(MI->getAllocatedType());
Owen Andersone9b11b42009-07-08 19:03:57 +0000847 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
848 MI->getAllocatedType(), false,
849 GlobalValue::InternalLinkage, Init,
850 GV->getName()+".body",
851 GV,
852 GV->isThreadLocal());
853
Chris Lattner30ba5692004-10-11 05:54:41 +0000854 // Anything that used the malloc now uses the global directly.
855 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000856
857 Constant *RepValue = NewGV;
858 if (NewGV->getType() != GV->getType()->getElementType())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000859 RepValue = ConstantExpr::getBitCast(RepValue,
Reid Spencerd977d862006-12-12 23:36:14 +0000860 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000861
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000862 // If there is a comparison against null, we will insert a global bool to
863 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000864 GlobalVariable *InitBool =
Owen Anderson1d0be152009-08-13 21:58:54 +0000865 new GlobalVariable(Context, Type::getInt1Ty(Context), false,
Owen Anderson3d29df32009-07-08 01:26:06 +0000866 GlobalValue::InternalLinkage,
Owen Anderson5defacc2009-07-31 17:39:07 +0000867 ConstantInt::getFalse(Context), GV->getName()+".init",
Owen Andersone9b11b42009-07-08 19:03:57 +0000868 GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000869 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000870
Chris Lattner30ba5692004-10-11 05:54:41 +0000871 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000872 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000873 while (!GV->use_empty())
874 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000875 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000876 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000877 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000878 LoadUse = RepValue;
879 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000880 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
881 // Replace the cmp X, 0 with a use of the bool value.
882 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000883 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000884 switch (CI->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000885 default: llvm_unreachable("Unknown ICmp Predicate!");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000886 case ICmpInst::ICMP_ULT:
887 case ICmpInst::ICMP_SLT:
Owen Anderson5defacc2009-07-31 17:39:07 +0000888 LV = ConstantInt::getFalse(Context); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000889 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000890 case ICmpInst::ICMP_ULE:
891 case ICmpInst::ICMP_SLE:
892 case ICmpInst::ICMP_EQ:
Dan Gohman4ae51262009-08-12 16:23:25 +0000893 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000894 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000895 case ICmpInst::ICMP_NE:
896 case ICmpInst::ICMP_UGE:
897 case ICmpInst::ICMP_SGE:
898 case ICmpInst::ICMP_UGT:
899 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000900 break; // no change.
901 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000902 CI->replaceAllUsesWith(LV);
903 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000904 }
905 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000906 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000907 } else {
908 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000909 // The global is initialized when the store to it occurs.
Owen Anderson5defacc2009-07-31 17:39:07 +0000910 new StoreInst(ConstantInt::getTrue(Context), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000911 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000912 }
913
Chris Lattnerbc965b92004-12-02 06:25:58 +0000914 // If the initialization boolean was used, insert it, otherwise delete it.
915 if (!InitBoolUsed) {
916 while (!InitBool->use_empty()) // Delete initializations
917 cast<Instruction>(InitBool->use_back())->eraseFromParent();
918 delete InitBool;
919 } else
920 GV->getParent()->getGlobalList().insert(GV, InitBool);
921
922
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000923 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000924 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000925 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000926
927 // To further other optimizations, loop over all users of NewGV and try to
928 // constant prop them. This will promote GEP instructions with constant
929 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Owen Anderson50895512009-07-06 18:42:36 +0000930 ConstantPropUsersOf(NewGV, Context);
Chris Lattner30ba5692004-10-11 05:54:41 +0000931 if (RepValue != NewGV)
Owen Anderson50895512009-07-06 18:42:36 +0000932 ConstantPropUsersOf(RepValue, Context);
Chris Lattner30ba5692004-10-11 05:54:41 +0000933
934 return NewGV;
935}
Chris Lattner708148e2004-10-10 23:14:11 +0000936
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000937/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
938/// to make sure that there are no complex uses of V. We permit simple things
939/// like dereferencing the pointer, but not storing through the address, unless
940/// it is to the specified global.
941static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000942 GlobalVariable *GV,
943 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000944 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foad0906b1b2009-06-06 17:49:35 +0000945 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000946
947 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
948 continue; // Fine, ignore.
949 }
950
951 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000952 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
953 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000954 continue; // Otherwise, storing through it, or storing into GV... fine.
955 }
956
957 if (isa<GetElementPtrInst>(Inst)) {
958 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000959 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000960 continue;
961 }
962
963 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000964 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
965 // cycles.
966 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000967 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
968 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000969 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000970 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000971
972 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
973 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
974 return false;
975 continue;
976 }
977
978 return false;
979 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000980 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000981}
982
Chris Lattner86395032006-09-30 23:32:09 +0000983/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
984/// somewhere. Transform all uses of the allocation into loads from the
985/// global and uses of the resultant pointer. Further, delete the store into
986/// GV. This assumes that these value pass the
987/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
988static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
989 GlobalVariable *GV) {
990 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000991 Instruction *U = cast<Instruction>(*Alloc->use_begin());
992 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +0000993 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
994 // If this is the store of the allocation into the global, remove it.
995 if (SI->getOperand(1) == GV) {
996 SI->eraseFromParent();
997 continue;
998 }
Chris Lattnera637a8b2007-09-13 18:00:31 +0000999 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1000 // Insert the load in the corresponding predecessor, not right before the
1001 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001002 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001003 } else if (isa<BitCastInst>(U)) {
1004 // Must be bitcast between the malloc and store to initialize the global.
1005 ReplaceUsesOfMallocWithGlobal(U, GV);
1006 U->eraseFromParent();
1007 continue;
1008 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1009 // If this is a "GEP bitcast" and the user is a store to the global, then
1010 // just process it as a bitcast.
1011 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1012 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1013 if (SI->getOperand(1) == GV) {
1014 // Must be bitcast GEP between the malloc and store to initialize
1015 // the global.
1016 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1017 GEPI->eraseFromParent();
1018 continue;
1019 }
Chris Lattner86395032006-09-30 23:32:09 +00001020 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001021
Chris Lattner86395032006-09-30 23:32:09 +00001022 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001023 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001024 U->replaceUsesOfWith(Alloc, NL);
1025 }
1026}
1027
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001028/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1029/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1030/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001031static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Cheng5d163962009-06-02 00:56:07 +00001032 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1033 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001034 // We permit two users of the load: setcc comparing against the null
1035 // pointer, and a getelementptr of a specific form.
1036 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1037 Instruction *User = cast<Instruction>(*UI);
1038
1039 // Comparison against null is ok.
1040 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1041 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1042 return false;
1043 continue;
1044 }
1045
1046 // getelementptr is also ok, but only a simple form.
1047 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1048 // Must index into the array and into the struct.
1049 if (GEPI->getNumOperands() < 3)
1050 return false;
1051
1052 // Otherwise the GEP is ok.
1053 continue;
1054 }
1055
1056 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001057 if (!LoadUsingPHIsPerLoad.insert(PN))
1058 // This means some phi nodes are dependent on each other.
1059 // Avoid infinite looping!
1060 return false;
1061 if (!LoadUsingPHIs.insert(PN))
1062 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001063 continue;
1064
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001065 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001066 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1067 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001068 return false;
1069
1070 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001071 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001072
1073 // Otherwise we don't know what this is, not ok.
1074 return false;
1075 }
1076
1077 return true;
1078}
1079
1080
1081/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1082/// GV are simple enough to perform HeapSRA, return true.
1083static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1084 MallocInst *MI) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001085 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Cheng5d163962009-06-02 00:56:07 +00001086 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001087 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1088 ++UI)
Evan Cheng5d163962009-06-02 00:56:07 +00001089 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1090 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1091 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001092 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001093 LoadUsingPHIsPerLoad.clear();
1094 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001095
1096 // If we reach here, we know that all uses of the loads and transitive uses
1097 // (through PHI nodes) are simple enough to transform. However, we don't know
1098 // that all inputs the to the PHI nodes are in the same equivalence sets.
1099 // Check to verify that all operands of the PHIs are either PHIS that can be
1100 // transformed, loads from GV, or MI itself.
1101 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1102 E = LoadUsingPHIs.end(); I != E; ++I) {
1103 PHINode *PN = *I;
1104 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1105 Value *InVal = PN->getIncomingValue(op);
1106
1107 // PHI of the stored value itself is ok.
1108 if (InVal == MI) continue;
1109
1110 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1111 // One of the PHIs in our set is (optimistically) ok.
1112 if (LoadUsingPHIs.count(InPN))
1113 continue;
1114 return false;
1115 }
1116
1117 // Load from GV is ok.
1118 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1119 if (LI->getOperand(0) == GV)
1120 continue;
1121
1122 // UNDEF? NULL?
1123
1124 // Anything else is rejected.
1125 return false;
1126 }
1127 }
1128
Chris Lattner86395032006-09-30 23:32:09 +00001129 return true;
1130}
1131
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001132static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1133 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001134 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Andersone922c022009-07-22 00:24:57 +00001135 LLVMContext &Context) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001136 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1137
1138 if (FieldNo >= FieldVals.size())
1139 FieldVals.resize(FieldNo+1);
1140
1141 // If we already have this value, just reuse the previously scalarized
1142 // version.
1143 if (Value *FieldVal = FieldVals[FieldNo])
1144 return FieldVal;
1145
1146 // Depending on what instruction this is, we have several cases.
1147 Value *Result;
1148 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1149 // This is a scalarized version of the load from the global. Just create
1150 // a new Load of the scalarized global.
1151 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1152 InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001153 PHIsToRewrite, Context),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001154 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001155 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1156 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1157 // field.
1158 const StructType *ST =
1159 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1160
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001161 Result =
Owen Andersondebcb012009-07-29 22:17:13 +00001162 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001163 PN->getName()+".f"+Twine(FieldNo), PN);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001164 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1165 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001166 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001167 Result = 0;
1168 }
1169
1170 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001171}
1172
Chris Lattner330245e2007-09-13 17:29:05 +00001173/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1174/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001175static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1176 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001177 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Andersone922c022009-07-22 00:24:57 +00001178 LLVMContext &Context) {
Chris Lattner330245e2007-09-13 17:29:05 +00001179 // If this is a comparison against null, handle it.
1180 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1181 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1182 // If we have a setcc of the loaded pointer, we can use a setcc of any
1183 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001184 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001185 InsertedScalarizedValues, PHIsToRewrite,
1186 Context);
Chris Lattner330245e2007-09-13 17:29:05 +00001187
Owen Anderson333c4002009-07-09 23:48:35 +00001188 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Owen Andersona7235ea2009-07-31 20:28:14 +00001189 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001190 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001191 SCI->replaceAllUsesWith(New);
1192 SCI->eraseFromParent();
1193 return;
1194 }
1195
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001196 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001197 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1198 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1199 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001200
Chris Lattnera637a8b2007-09-13 18:00:31 +00001201 // Load the pointer for this field.
1202 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001203 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001204 InsertedScalarizedValues, PHIsToRewrite,
1205 Context);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001206
1207 // Create the new GEP idx vector.
1208 SmallVector<Value*, 8> GEPIdx;
1209 GEPIdx.push_back(GEPI->getOperand(1));
1210 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1211
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001212 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1213 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001214 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001215 GEPI->replaceAllUsesWith(NGEPI);
1216 GEPI->eraseFromParent();
1217 return;
1218 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001219
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001220 // Recursively transform the users of PHI nodes. This will lazily create the
1221 // PHIs that are needed for individual elements. Keep track of what PHIs we
1222 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1223 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1224 // already been seen first by another load, so its uses have already been
1225 // processed.
1226 PHINode *PN = cast<PHINode>(LoadUser);
1227 bool Inserted;
1228 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1229 tie(InsertPos, Inserted) =
1230 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1231 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001232
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001233 // If this is the first time we've seen this PHI, recursively process all
1234 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001235 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1236 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001237 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1238 Context);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001239 }
Chris Lattner330245e2007-09-13 17:29:05 +00001240}
1241
Chris Lattner86395032006-09-30 23:32:09 +00001242/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1243/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1244/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001245/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001246static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001247 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001248 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Andersone922c022009-07-22 00:24:57 +00001249 LLVMContext &Context) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001250 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001251 UI != E; ) {
1252 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001253 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1254 Context);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001255 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001256
1257 if (Load->use_empty()) {
1258 Load->eraseFromParent();
1259 InsertedScalarizedValues.erase(Load);
1260 }
Chris Lattner86395032006-09-30 23:32:09 +00001261}
1262
1263/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1264/// it up into multiple allocations of arrays of the fields.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001265static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI,
Owen Andersone922c022009-07-22 00:24:57 +00001266 LLVMContext &Context){
Bill Wendling0a81aac2006-11-26 10:02:32 +00001267 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +00001268 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1269
1270 // There is guaranteed to be at least one use of the malloc (storing
1271 // it into GV). If there are other uses, change them to be uses of
1272 // the global to simplify later code. This also deletes the store
1273 // into GV.
1274 ReplaceUsesOfMallocWithGlobal(MI, GV);
1275
1276 // Okay, at this point, there are no users of the malloc. Insert N
1277 // new mallocs at the same place as MI, and N globals.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001278 std::vector<Value*> FieldGlobals;
Chris Lattner86395032006-09-30 23:32:09 +00001279 std::vector<MallocInst*> FieldMallocs;
1280
1281 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1282 const Type *FieldTy = STy->getElementType(FieldNo);
Owen Andersondebcb012009-07-29 22:17:13 +00001283 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001284
1285 GlobalVariable *NGV =
Owen Andersone9b11b42009-07-08 19:03:57 +00001286 new GlobalVariable(*GV->getParent(),
1287 PFieldTy, false, GlobalValue::InternalLinkage,
Owen Andersona7235ea2009-07-31 20:28:14 +00001288 Constant::getNullValue(PFieldTy),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001289 GV->getName() + ".f" + Twine(FieldNo), GV,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001290 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001291 FieldGlobals.push_back(NGV);
1292
Owen Anderson50dead02009-07-15 23:53:25 +00001293 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001294 MI->getName() + ".f" + Twine(FieldNo), MI);
Chris Lattner86395032006-09-30 23:32:09 +00001295 FieldMallocs.push_back(NMI);
1296 new StoreInst(NMI, NGV, MI);
1297 }
1298
1299 // The tricky aspect of this transformation is handling the case when malloc
1300 // fails. In the original code, malloc failing would set the result pointer
1301 // of malloc to null. In this case, some mallocs could succeed and others
1302 // could fail. As such, we emit code that looks like this:
1303 // F0 = malloc(field0)
1304 // F1 = malloc(field1)
1305 // F2 = malloc(field2)
1306 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1307 // if (F0) { free(F0); F0 = 0; }
1308 // if (F1) { free(F1); F1 = 0; }
1309 // if (F2) { free(F2); F2 = 0; }
1310 // }
1311 Value *RunningOr = 0;
1312 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Owen Anderson333c4002009-07-09 23:48:35 +00001313 Value *Cond = new ICmpInst(MI, ICmpInst::ICMP_EQ, FieldMallocs[i],
Owen Andersona7235ea2009-07-31 20:28:14 +00001314 Constant::getNullValue(FieldMallocs[i]->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001315 "isnull");
Chris Lattner86395032006-09-30 23:32:09 +00001316 if (!RunningOr)
1317 RunningOr = Cond; // First seteq
1318 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001319 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Chris Lattner86395032006-09-30 23:32:09 +00001320 }
1321
1322 // Split the basic block at the old malloc.
1323 BasicBlock *OrigBB = MI->getParent();
1324 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1325
1326 // Create the block to check the first condition. Put all these blocks at the
1327 // end of the function as they are unlikely to be executed.
Owen Anderson1d0be152009-08-13 21:58:54 +00001328 BasicBlock *NullPtrBlock = BasicBlock::Create(Context, "malloc_ret_null",
Gabor Greif051a9502008-04-06 20:25:17 +00001329 OrigBB->getParent());
Chris Lattner86395032006-09-30 23:32:09 +00001330
1331 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1332 // branch on RunningOr.
1333 OrigBB->getTerminator()->eraseFromParent();
Gabor Greif051a9502008-04-06 20:25:17 +00001334 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Chris Lattner86395032006-09-30 23:32:09 +00001335
1336 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1337 // pointer, because some may be null while others are not.
1338 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1339 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Owen Anderson333c4002009-07-09 23:48:35 +00001340 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00001341 Constant::getNullValue(GVVal->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001342 "tmp");
Owen Anderson1d0be152009-08-13 21:58:54 +00001343 BasicBlock *FreeBlock = BasicBlock::Create(Context, "free_it",
1344 OrigBB->getParent());
1345 BasicBlock *NextBlock = BasicBlock::Create(Context, "next",
1346 OrigBB->getParent());
Gabor Greif051a9502008-04-06 20:25:17 +00001347 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001348
1349 // Fill in FreeBlock.
1350 new FreeInst(GVVal, FreeBlock);
Owen Andersona7235ea2009-07-31 20:28:14 +00001351 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
Chris Lattner86395032006-09-30 23:32:09 +00001352 FreeBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001353 BranchInst::Create(NextBlock, FreeBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001354
1355 NullPtrBlock = NextBlock;
1356 }
1357
Gabor Greif051a9502008-04-06 20:25:17 +00001358 BranchInst::Create(ContBB, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001359
1360 // MI is no longer needed, remove it.
1361 MI->eraseFromParent();
1362
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001363 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1364 /// update all uses of the load, keep track of what scalarized loads are
1365 /// inserted for a given load.
1366 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1367 InsertedScalarizedValues[GV] = FieldGlobals;
1368
1369 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Chris Lattner86395032006-09-30 23:32:09 +00001370
1371 // Okay, the malloc site is completely handled. All of the uses of GV are now
1372 // loads, and all uses of those loads are simple. Rewrite them to use loads
1373 // of the per-field globals instead.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001374 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1375 Instruction *User = cast<Instruction>(*UI++);
1376
1377 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001378 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1379 Context);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001380 continue;
Chris Lattner39ff1e22007-01-09 23:29:37 +00001381 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001382
1383 // Must be a store of null.
1384 StoreInst *SI = cast<StoreInst>(User);
1385 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1386 "Unexpected heap-sra user!");
1387
1388 // Insert a store of null into each global.
1389 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1390 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Owen Andersona7235ea2009-07-31 20:28:14 +00001391 Constant *Null = Constant::getNullValue(PT->getElementType());
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001392 new StoreInst(Null, FieldGlobals[i], SI);
1393 }
1394 // Erase the original store.
1395 SI->eraseFromParent();
Chris Lattner86395032006-09-30 23:32:09 +00001396 }
1397
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001398 // While we have PHIs that are interesting to rewrite, do it.
1399 while (!PHIsToRewrite.empty()) {
1400 PHINode *PN = PHIsToRewrite.back().first;
1401 unsigned FieldNo = PHIsToRewrite.back().second;
1402 PHIsToRewrite.pop_back();
1403 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1404 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1405
1406 // Add all the incoming values. This can materialize more phis.
1407 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1408 Value *InVal = PN->getIncomingValue(i);
1409 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001410 PHIsToRewrite, Context);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001411 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1412 }
1413 }
1414
1415 // Drop all inter-phi links and any loads that made it this far.
1416 for (DenseMap<Value*, std::vector<Value*> >::iterator
1417 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1418 I != E; ++I) {
1419 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1420 PN->dropAllReferences();
1421 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1422 LI->dropAllReferences();
1423 }
1424
1425 // Delete all the phis and loads now that inter-references are dead.
1426 for (DenseMap<Value*, std::vector<Value*> >::iterator
1427 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1428 I != E; ++I) {
1429 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1430 PN->eraseFromParent();
1431 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1432 LI->eraseFromParent();
1433 }
1434
Chris Lattner86395032006-09-30 23:32:09 +00001435 // The old global is now dead, remove it.
1436 GV->eraseFromParent();
1437
1438 ++NumHeapSRA;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001439 return cast<GlobalVariable>(FieldGlobals[0]);
Chris Lattner86395032006-09-30 23:32:09 +00001440}
1441
Chris Lattnere61d0a62008-12-15 21:02:25 +00001442/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1443/// pointer global variable with a single value stored it that is a malloc or
1444/// cast of malloc.
1445static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1446 MallocInst *MI,
1447 Module::global_iterator &GVI,
Dan Gohman7eb28f32009-08-14 00:11:03 +00001448 TargetData *TD,
Owen Andersone922c022009-07-22 00:24:57 +00001449 LLVMContext &Context) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001450 // If this is a malloc of an abstract type, don't touch it.
1451 if (!MI->getAllocatedType()->isSized())
1452 return false;
1453
1454 // We can't optimize this global unless all uses of it are *known* to be
1455 // of the malloc value, not of the null initializer value (consider a use
1456 // that compares the global's value against zero to see if the malloc has
1457 // been reached). To do this, we check to see if all uses of the global
1458 // would trap if the global were null: this proves that they must all
1459 // happen after the malloc.
1460 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1461 return false;
1462
1463 // We can't optimize this if the malloc itself is used in a complex way,
1464 // for example, being stored into multiple globals. This allows the
1465 // malloc to be stored into the specified global, loaded setcc'd, and
1466 // GEP'd. These are all things we could transform to using the global
1467 // for.
1468 {
1469 SmallPtrSet<PHINode*, 8> PHIs;
1470 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1471 return false;
1472 }
1473
1474
1475 // If we have a global that is only initialized with a fixed size malloc,
1476 // transform the program to use global memory instead of malloc'd memory.
1477 // This eliminates dynamic allocation, avoids an indirection accessing the
1478 // data, and exposes the resultant global to further GlobalOpt.
1479 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1480 // Restrict this transformation to only working on small allocations
1481 // (2048 bytes currently), as we don't want to introduce a 16M global or
1482 // something.
Dan Gohman7eb28f32009-08-14 00:11:03 +00001483 if (TD &&
1484 NElements->getZExtValue()*
1485 TD->getTypeAllocSize(MI->getAllocatedType()) < 2048) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001486 GVI = OptimizeGlobalAddressOfMalloc(GV, MI, Context);
Chris Lattnere61d0a62008-12-15 21:02:25 +00001487 return true;
1488 }
1489 }
1490
1491 // If the allocation is an array of structures, consider transforming this
1492 // into multiple malloc'd arrays, one for each field. This is basically
1493 // SRoA for malloc'd memory.
Chris Lattner101f44e2008-12-15 21:44:34 +00001494 const Type *AllocTy = MI->getAllocatedType();
1495
1496 // If this is an allocation of a fixed size array of structs, analyze as a
1497 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1498 if (!MI->isArrayAllocation())
1499 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1500 AllocTy = AT->getElementType();
1501
1502 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001503 // This the structure has an unreasonable number of fields, leave it
1504 // alone.
Chris Lattner101f44e2008-12-15 21:44:34 +00001505 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001506 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner101f44e2008-12-15 21:44:34 +00001507
1508 // If this is a fixed size array, transform the Malloc to be an alloc of
1509 // structs. malloc [100 x struct],1 -> malloc struct, 100
1510 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1511 MallocInst *NewMI =
Owen Anderson50dead02009-07-15 23:53:25 +00001512 new MallocInst(AllocSTy,
Owen Anderson1d0be152009-08-13 21:58:54 +00001513 ConstantInt::get(Type::getInt32Ty(Context),
1514 AT->getNumElements()),
Chris Lattner101f44e2008-12-15 21:44:34 +00001515 "", MI);
1516 NewMI->takeName(MI);
1517 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1518 MI->replaceAllUsesWith(Cast);
1519 MI->eraseFromParent();
1520 MI = NewMI;
1521 }
1522
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001523 GVI = PerformHeapAllocSRoA(GV, MI, Context);
Chris Lattnere61d0a62008-12-15 21:02:25 +00001524 return true;
1525 }
1526 }
1527
1528 return false;
1529}
Chris Lattner86395032006-09-30 23:32:09 +00001530
Chris Lattner9b34a612004-10-09 21:48:45 +00001531// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1532// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001533static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001534 Module::global_iterator &GVI,
Dan Gohman7eb28f32009-08-14 00:11:03 +00001535 TargetData *TD, LLVMContext &Context) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001536 // Ignore no-op GEPs and bitcasts.
1537 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001538
Chris Lattner708148e2004-10-10 23:14:11 +00001539 // If we are dealing with a pointer global that is initialized to null and
1540 // only has one (non-null) value stored into it, then we can optimize any
1541 // users of the loaded value (often calls and loads) that would trap if the
1542 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001543 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1544 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001545 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1546 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001547 SOVC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001548 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001549
Chris Lattner708148e2004-10-10 23:14:11 +00001550 // Optimize away any trapping uses of the loaded value.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001551 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
Chris Lattner8be80122004-10-10 17:07:12 +00001552 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001553 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001554 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD, Context))
Chris Lattnere61d0a62008-12-15 21:02:25 +00001555 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001556 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001557 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001558
Chris Lattner9b34a612004-10-09 21:48:45 +00001559 return false;
1560}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001561
Chris Lattner58e44f42008-01-14 01:17:44 +00001562/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1563/// two values ever stored into GV are its initializer and OtherVal. See if we
1564/// can shrink the global into a boolean and select between the two values
1565/// whenever it is used. This exposes the values to other scalar optimizations.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001566static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
Owen Andersone922c022009-07-22 00:24:57 +00001567 LLVMContext &Context) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001568 const Type *GVElType = GV->getType()->getElementType();
1569
1570 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001571 // an FP value, pointer or vector, don't do this optimization because a select
1572 // between them is very expensive and unlikely to lead to later
1573 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1574 // where v1 and v2 both require constant pool loads, a big loss.
Owen Anderson1d0be152009-08-13 21:58:54 +00001575 if (GVElType == Type::getInt1Ty(Context) || GVElType->isFloatingPoint() ||
Chris Lattner6f6923f2009-03-07 23:32:02 +00001576 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
Chris Lattner58e44f42008-01-14 01:17:44 +00001577 return false;
1578
1579 // Walk the use list of the global seeing if all the uses are load or store.
1580 // If there is anything else, bail out.
1581 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel771281f2009-03-06 01:39:36 +00001582 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattner58e44f42008-01-14 01:17:44 +00001583 return false;
1584
1585 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1586
Chris Lattner96a86b22004-12-12 05:53:50 +00001587 // Create the new global, initializing it to false.
Owen Anderson1d0be152009-08-13 21:58:54 +00001588 GlobalVariable *NewGV = new GlobalVariable(Context,
1589 Type::getInt1Ty(Context), false,
Owen Anderson5defacc2009-07-31 17:39:07 +00001590 GlobalValue::InternalLinkage, ConstantInt::getFalse(Context),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001591 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001592 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001593 GV->getParent()->getGlobalList().insert(GV, NewGV);
1594
1595 Constant *InitVal = GV->getInitializer();
Owen Anderson1d0be152009-08-13 21:58:54 +00001596 assert(InitVal->getType() != Type::getInt1Ty(Context) &&
1597 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001598
1599 // If initialized to zero and storing one into the global, we can use a cast
1600 // instead of a select to synthesize the desired value.
1601 bool IsOneZero = false;
1602 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001603 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001604
1605 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001606 Instruction *UI = cast<Instruction>(GV->use_back());
1607 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001608 // Change the store into a boolean store.
1609 bool StoringOther = SI->getOperand(0) == OtherVal;
1610 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001611 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001612 if (StoringOther || SI->getOperand(0) == InitVal)
Owen Anderson1d0be152009-08-13 21:58:54 +00001613 StoreVal = ConstantInt::get(Type::getInt1Ty(Context), StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001614 else {
1615 // Otherwise, we are storing a previously loaded copy. To do this,
1616 // change the copy from copying the original value to just copying the
1617 // bool.
1618 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1619
1620 // If we're already replaced the input, StoredVal will be a cast or
1621 // select instruction. If not, it will be a load of the original
1622 // global.
1623 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1624 assert(LI->getOperand(0) == GV && "Not a copy!");
1625 // Insert a new load, to preserve the saved value.
1626 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1627 } else {
1628 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1629 "This is not a form that we understand!");
1630 StoreVal = StoredVal->getOperand(0);
1631 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1632 }
1633 }
1634 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001635 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001636 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001637 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001638 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001639 Value *NSI;
1640 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001641 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001642 else
Gabor Greif051a9502008-04-06 20:25:17 +00001643 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001644 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001645 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001646 }
1647 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001648 }
1649
1650 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001651 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001652}
1653
1654
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001655/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1656/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001657bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001658 Module::global_iterator &GVI) {
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001659 SmallPtrSet<PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001660 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001661 GV->removeDeadConstantUsers();
1662
1663 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001664 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001665 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001666 ++NumDeleted;
1667 return true;
1668 }
1669
1670 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001671#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001672 cerr << "Global: " << *GV;
1673 cerr << " isLoaded = " << GS.isLoaded << "\n";
1674 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001675 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001676 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1677 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1678 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1679 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001680 }
1681 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001682 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001683 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001684 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001685 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001686 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001687 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001688 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001689 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001690#endif
1691
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001692 // If this is a first class global and has only one accessing function
1693 // and this function is main (which we know is not recursive we can make
1694 // this global a local variable) we replace the global with a local alloca
1695 // in this function.
1696 //
Dan Gohman399101a2008-05-23 00:17:26 +00001697 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001698 // are just replacing static memory to stack memory.
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001699 //
1700 // If the global is in different address space, don't bring it to stack.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001701 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001702 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001703 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001704 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001705 GS.AccessingFunction->hasExternalLinkage() &&
1706 GV->getType()->getAddressSpace() == 0) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001707 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001708 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1709 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001710 // FIXME: Pass Global's alignment when globals have alignment
Owen Anderson50dead02009-07-15 23:53:25 +00001711 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001712 if (!isa<UndefValue>(GV->getInitializer()))
1713 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001714
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001715 GV->replaceAllUsesWith(Alloca);
1716 GV->eraseFromParent();
1717 ++NumLocalized;
1718 return true;
1719 }
Chris Lattnercff16732006-09-30 19:40:30 +00001720
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001721 // If the global is never loaded (but may be stored to), it is dead.
1722 // Delete it now.
1723 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001724 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001725
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001726 // Delete any stores we can find to the global. We may not be able to
1727 // make it completely dead though.
Owen Anderson50895512009-07-06 18:42:36 +00001728 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
Owen Andersone922c022009-07-22 00:24:57 +00001729 GV->getContext());
Chris Lattner930f4752004-10-09 03:32:52 +00001730
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001731 // If the global is dead now, delete it.
1732 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001733 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001734 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001735 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001736 }
Chris Lattner930f4752004-10-09 03:32:52 +00001737 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001738
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001739 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001740 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001741 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001742
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001743 // Clean up any obviously simplifiable users now.
Owen Andersone922c022009-07-22 00:24:57 +00001744 CleanupConstantGlobalUsers(GV, GV->getInitializer(), GV->getContext());
Misha Brukmanfd939082005-04-21 23:48:37 +00001745
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001746 // If the global is dead now, just nuke it.
1747 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001748 DOUT << " *** Marking constant allowed us to simplify "
1749 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001750 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001751 ++NumDeleted;
1752 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001753
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001754 ++NumMarked;
1755 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001756 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Dan Gohman7eb28f32009-08-14 00:11:03 +00001757 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1758 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD,
1759 GV->getContext())) {
1760 GVI = FirstNewGV; // Don't skip the newly produced globals!
1761 return true;
1762 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001763 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001764 // If the initial value for the global was an undef value, and if only
1765 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001766 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001767 // global. This allows us to mark it constant.
1768 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1769 if (isa<UndefValue>(GV->getInitializer())) {
1770 // Change the initial value here.
1771 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001772
Chris Lattner96a86b22004-12-12 05:53:50 +00001773 // Clean up any obviously simplifiable users now.
Owen Andersone922c022009-07-22 00:24:57 +00001774 CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1775 GV->getContext());
Misha Brukmanfd939082005-04-21 23:48:37 +00001776
Chris Lattner96a86b22004-12-12 05:53:50 +00001777 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001778 DOUT << " *** Substituting initializer allowed us to "
1779 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001780 GV->eraseFromParent();
1781 ++NumDeleted;
1782 } else {
1783 GVI = GV;
1784 }
1785 ++NumSubstitute;
1786 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001787 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001788
Chris Lattner9b34a612004-10-09 21:48:45 +00001789 // Try to optimize globals based on the knowledge that only one value
1790 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001791 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Dan Gohman7eb28f32009-08-14 00:11:03 +00001792 getAnalysisIfAvailable<TargetData>(),
1793 GV->getContext()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001794 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001795
1796 // Otherwise, if the global was not a boolean, we can shrink it to be a
1797 // boolean.
1798 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Owen Andersone922c022009-07-22 00:24:57 +00001799 if (TryToShrinkGlobalToBoolean(GV, SOVConstant, GV->getContext())) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001800 ++NumShrunkToBool;
1801 return true;
1802 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001803 }
1804 }
1805 return false;
1806}
1807
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001808/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1809/// function, changing them to FastCC.
1810static void ChangeCalleesToFastCall(Function *F) {
1811 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001812 CallSite User(cast<Instruction>(*UI));
1813 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001814 }
1815}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001816
Devang Patel05988662008-09-25 21:00:45 +00001817static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001818 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001819 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001820 continue;
1821
Duncan Sands548448a2008-02-18 17:32:13 +00001822 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001823 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001824 }
1825
1826 return Attrs;
1827}
1828
1829static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001830 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001831 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001832 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001833 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001834 }
1835}
1836
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001837bool GlobalOpt::OptimizeFunctions(Module &M) {
1838 bool Changed = false;
1839 // Optimize functions.
1840 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1841 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001842 // Functions without names cannot be referenced outside this module.
1843 if (!F->hasName() && !F->isDeclaration())
1844 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001845 F->removeDeadConstantUsers();
Rafael Espindolabb46f522009-01-15 20:18:42 +00001846 if (F->use_empty() && (F->hasLocalLinkage() ||
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001847 F->hasLinkOnceLinkage())) {
1848 M.getFunctionList().erase(F);
1849 Changed = true;
1850 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001851 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001852 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001853 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001854 // If this function has C calling conventions, is not a varargs
1855 // function, and is only called directly, promote it to use the Fast
1856 // calling convention.
1857 F->setCallingConv(CallingConv::Fast);
1858 ChangeCalleesToFastCall(F);
1859 ++NumFastCallFns;
1860 Changed = true;
1861 }
1862
Devang Patel05988662008-09-25 21:00:45 +00001863 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001864 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001865 // The function is not used by a trampoline intrinsic, so it is safe
1866 // to remove the 'nest' attribute.
1867 RemoveNestAttribute(F);
1868 ++NumNestRemoved;
1869 Changed = true;
1870 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001871 }
1872 }
1873 return Changed;
1874}
1875
1876bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1877 bool Changed = false;
1878 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1879 GVI != E; ) {
1880 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001881 // Global variables without names cannot be referenced outside this module.
1882 if (!GV->hasName() && !GV->isDeclaration())
1883 GV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolabb46f522009-01-15 20:18:42 +00001884 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001885 GV->hasInitializer())
1886 Changed |= ProcessInternalGlobal(GV, GVI);
1887 }
1888 return Changed;
1889}
1890
1891/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1892/// initializers have an init priority of 65535.
1893GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001894 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1895 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001896 if (I->getName() == "llvm.global_ctors") {
1897 // Found it, verify it's an array of { int, void()* }.
1898 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1899 if (!ATy) return 0;
1900 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1901 if (!STy || STy->getNumElements() != 2 ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001902 STy->getElementType(0) != Type::getInt32Ty(M.getContext())) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001903 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1904 if (!PFTy) return 0;
1905 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001906 if (!FTy || FTy->getReturnType() != Type::getVoidTy(M.getContext()) ||
1907 FTy->isVarArg() || FTy->getNumParams() != 0)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001908 return 0;
1909
1910 // Verify that the initializer is simple enough for us to handle.
1911 if (!I->hasInitializer()) return 0;
1912 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1913 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001914 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1915 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001916 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1917 continue;
1918
1919 // Must have a function or null ptr.
1920 if (!isa<Function>(CS->getOperand(1)))
1921 return 0;
1922
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001923 // Init priority must be standard.
1924 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001925 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001926 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001927 } else {
1928 return 0;
1929 }
1930
1931 return I;
1932 }
1933 return 0;
1934}
1935
Chris Lattnerdb973e62005-09-26 02:31:18 +00001936/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1937/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001938static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1939 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1940 std::vector<Function*> Result;
1941 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001942 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1943 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001944 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1945 }
1946 return Result;
1947}
1948
Chris Lattnerdb973e62005-09-26 02:31:18 +00001949/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1950/// specified array, returning the new global to use.
1951static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001952 const std::vector<Function*> &Ctors,
Owen Andersone922c022009-07-22 00:24:57 +00001953 LLVMContext &Context) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001954 // If we made a change, reassemble the initializer list.
1955 std::vector<Constant*> CSVals;
Owen Anderson1d0be152009-08-13 21:58:54 +00001956 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(Context), 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001957 CSVals.push_back(0);
1958
1959 // Create the new init list.
1960 std::vector<Constant*> CAList;
1961 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001962 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001963 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001964 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00001965 const Type *FTy = FunctionType::get(Type::getVoidTy(Context), false);
Owen Andersondebcb012009-07-29 22:17:13 +00001966 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00001967 CSVals[1] = Constant::getNullValue(PFTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001968 CSVals[0] = ConstantInt::get(Type::getInt32Ty(Context), 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001969 }
Owen Andersond7f2a6c2009-08-05 23:16:16 +00001970 CAList.push_back(ConstantStruct::get(Context, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001971 }
1972
1973 // Create the array initializer.
1974 const Type *StructTy =
1975 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson1fd70962009-07-28 18:32:17 +00001976 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001977 CAList.size()), CAList);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001978
1979 // If we didn't change the number of elements, don't create a new GV.
1980 if (CA->getType() == GCL->getInitializer()->getType()) {
1981 GCL->setInitializer(CA);
1982 return GCL;
1983 }
1984
1985 // Create the new global and insert it next to the existing list.
Owen Andersone922c022009-07-22 00:24:57 +00001986 GlobalVariable *NGV = new GlobalVariable(Context, CA->getType(),
Owen Anderson3d29df32009-07-08 01:26:06 +00001987 GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001988 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001989 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001990 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001991 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001992
1993 // Nuke the old list, replacing any uses with the new one.
1994 if (!GCL->use_empty()) {
1995 Constant *V = NGV;
1996 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001997 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001998 GCL->replaceAllUsesWith(V);
1999 }
2000 GCL->eraseFromParent();
2001
2002 if (Ctors.size())
2003 return NGV;
2004 else
2005 return 0;
2006}
Chris Lattner79c11012005-09-26 04:44:35 +00002007
2008
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002009static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00002010 Value *V) {
2011 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2012 Constant *R = ComputedValues[V];
2013 assert(R && "Reference to an uncomputed value!");
2014 return R;
2015}
2016
2017/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2018/// enough for us to understand. In particular, if it is a cast of something,
2019/// we punt. We basically just support direct accesses to globals and GEP's of
2020/// globals. This should be kept up to date with CommitValueTo.
Owen Andersone922c022009-07-22 00:24:57 +00002021static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext &Context) {
Chris Lattner231308c2005-09-27 04:50:03 +00002022 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolabb46f522009-01-15 20:18:42 +00002023 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002024 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00002025 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00002026 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002027 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2028 // Handle a constantexpr gep.
2029 if (CE->getOpcode() == Instruction::GetElementPtr &&
2030 isa<GlobalVariable>(CE->getOperand(0))) {
2031 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolabb46f522009-01-15 20:18:42 +00002032 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002033 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00002034 return GV->hasInitializer() &&
Owen Anderson50895512009-07-06 18:42:36 +00002035 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2036 Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002037 }
Chris Lattner79c11012005-09-26 04:44:35 +00002038 return false;
2039}
2040
Chris Lattner798b4d52005-09-26 06:52:44 +00002041/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2042/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2043/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2044static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002045 ConstantExpr *Addr, unsigned OpNo,
Owen Andersone922c022009-07-22 00:24:57 +00002046 LLVMContext &Context) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002047 // Base case of the recursion.
2048 if (OpNo == Addr->getNumOperands()) {
2049 assert(Val->getType() == Init->getType() && "Type mismatch!");
2050 return Val;
2051 }
2052
2053 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2054 std::vector<Constant*> Elts;
2055
2056 // Break up the constant into its elements.
2057 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002058 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2059 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002060 } else if (isa<ConstantAggregateZero>(Init)) {
2061 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002062 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002063 } else if (isa<UndefValue>(Init)) {
2064 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002065 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002066 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002067 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002068 " ConstantFoldLoadThroughGEPConstantExpr");
2069 }
2070
2071 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002072 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2073 unsigned Idx = CU->getZExtValue();
2074 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002075 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002076
2077 // Return the modified struct.
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002078 return ConstantStruct::get(Context, &Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002079 } else {
2080 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2081 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2082
2083 // Break up the array into elements.
2084 std::vector<Constant*> Elts;
2085 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002086 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2087 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002088 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002089 Constant *Elt = Constant::getNullValue(ATy->getElementType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002090 Elts.assign(ATy->getNumElements(), Elt);
2091 } else if (isa<UndefValue>(Init)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002092 Constant *Elt = UndefValue::get(ATy->getElementType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002093 Elts.assign(ATy->getNumElements(), Elt);
2094 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002095 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002096 " ConstantFoldLoadThroughGEPConstantExpr");
2097 }
2098
Reid Spencerb83eb642006-10-20 07:07:24 +00002099 assert(CI->getZExtValue() < ATy->getNumElements());
2100 Elts[CI->getZExtValue()] =
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002101 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
Owen Anderson1fd70962009-07-28 18:32:17 +00002102 return ConstantArray::get(ATy, Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002103 }
2104}
2105
Chris Lattner79c11012005-09-26 04:44:35 +00002106/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2107/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002108static void CommitValueTo(Constant *Val, Constant *Addr,
Owen Andersone922c022009-07-22 00:24:57 +00002109 LLVMContext &Context) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002110 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2111 assert(GV->hasInitializer());
2112 GV->setInitializer(Val);
2113 return;
2114 }
2115
2116 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2117 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2118
2119 Constant *Init = GV->getInitializer();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002120 Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002121 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00002122}
2123
Chris Lattner562a0552005-09-26 05:16:34 +00002124/// ComputeLoadResult - Return the value that would be computed by a load from
2125/// P after the stores reflected by 'memory' have been performed. If we can't
2126/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002127static Constant *ComputeLoadResult(Constant *P,
Owen Anderson50895512009-07-06 18:42:36 +00002128 const DenseMap<Constant*, Constant*> &Memory,
Owen Andersone922c022009-07-22 00:24:57 +00002129 LLVMContext &Context) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002130 // If this memory location has been recently stored, use the stored value: it
2131 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002132 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002133 if (I != Memory.end()) return I->second;
2134
2135 // Access it.
2136 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2137 if (GV->hasInitializer())
2138 return GV->getInitializer();
2139 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002140 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002141
2142 // Handle a constantexpr getelementptr.
2143 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2144 if (CE->getOpcode() == Instruction::GetElementPtr &&
2145 isa<GlobalVariable>(CE->getOperand(0))) {
2146 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2147 if (GV->hasInitializer())
Owen Anderson50895512009-07-06 18:42:36 +00002148 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2149 Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002150 }
2151
2152 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002153}
2154
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002155/// EvaluateFunction - Evaluate a call to function F, returning true if
2156/// successful, false if we can't evaluate it. ActualArgs contains the formal
2157/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002158static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002159 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002160 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002161 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002162 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002163 // Check to see if this function is already executing (recursion). If so,
2164 // bail out. TODO: we might want to accept limited recursion.
2165 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2166 return false;
2167
Owen Andersone922c022009-07-22 00:24:57 +00002168 LLVMContext &Context = F->getContext();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002169
Chris Lattnercd271422005-09-27 04:45:34 +00002170 CallStack.push_back(F);
2171
Chris Lattner79c11012005-09-26 04:44:35 +00002172 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002173 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002174
2175 // Initialize arguments to the incoming values specified.
2176 unsigned ArgNo = 0;
2177 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2178 ++AI, ++ArgNo)
2179 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002180
Chris Lattnercdf98be2005-09-26 04:57:38 +00002181 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2182 /// we can only evaluate any one basic block at most once. This set keeps
2183 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002184 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002185
Chris Lattner79c11012005-09-26 04:44:35 +00002186 // CurInst - The current instruction we're evaluating.
2187 BasicBlock::iterator CurInst = F->begin()->begin();
2188
2189 // This is the main evaluation loop.
2190 while (1) {
2191 Constant *InstResult = 0;
2192
2193 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002194 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002195 Constant *Ptr = getVal(Values, SI->getOperand(1));
Owen Anderson50895512009-07-06 18:42:36 +00002196 if (!isSimpleEnoughPointerToCommit(Ptr, Context))
Chris Lattner79c11012005-09-26 04:44:35 +00002197 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002198 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002199 Constant *Val = getVal(Values, SI->getOperand(0));
2200 MutatedMemory[Ptr] = Val;
2201 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002202 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002203 getVal(Values, BO->getOperand(0)),
2204 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002205 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002206 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002207 getVal(Values, CI->getOperand(0)),
2208 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002209 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002210 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002211 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002212 CI->getType());
2213 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002214 InstResult =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002215 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002216 getVal(Values, SI->getOperand(1)),
2217 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002218 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2219 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002220 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002221 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2222 i != e; ++i)
2223 GEPOps.push_back(getVal(Values, *i));
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002224 InstResult =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002225 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002226 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002227 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002228 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Owen Anderson50895512009-07-06 18:42:36 +00002229 MutatedMemory, Context);
Chris Lattnercd271422005-09-27 04:45:34 +00002230 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002231 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002232 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002233 const Type *Ty = AI->getType()->getElementType();
Owen Andersone922c022009-07-22 00:24:57 +00002234 AllocaTmps.push_back(new GlobalVariable(Context, Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002235 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002236 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002237 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002238 InstResult = AllocaTmps.back();
2239 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002240
2241 // Debug info can safely be ignored here.
2242 if (isa<DbgInfoIntrinsic>(CI)) {
2243 ++CurInst;
2244 continue;
2245 }
2246
Chris Lattner7cd580f2006-07-07 21:37:01 +00002247 // Cannot handle inline asm.
2248 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2249
Chris Lattnercd271422005-09-27 04:45:34 +00002250 // Resolve function pointers.
2251 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2252 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002253
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002254 SmallVector<Constant*, 8> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002255 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2256 i != e; ++i)
2257 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002258
Reid Spencer5cbf9852007-01-30 20:08:39 +00002259 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002260 // If this is a function we can constant fold, do it.
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002261 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
Chris Lattner6c1f5652007-01-30 23:14:52 +00002262 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002263 InstResult = C;
2264 } else {
2265 return false;
2266 }
2267 } else {
2268 if (Callee->getFunctionType()->isVarArg())
2269 return false;
2270
2271 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002272 // Execute the call, if successful, use the return value.
2273 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2274 MutatedMemory, AllocaTmps))
2275 return false;
2276 InstResult = RetVal;
2277 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002278 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002279 BasicBlock *NewBB = 0;
2280 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2281 if (BI->isUnconditional()) {
2282 NewBB = BI->getSuccessor(0);
2283 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002284 ConstantInt *Cond =
2285 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002286 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002287
Reid Spencer579dca12007-01-12 04:24:46 +00002288 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002289 }
2290 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2291 ConstantInt *Val =
2292 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002293 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002294 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2295 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002296 if (RI->getNumOperands())
2297 RetVal = getVal(Values, RI->getOperand(0));
2298
2299 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002300 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002301 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002302 // invoke, unwind, unreachable.
2303 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002304 }
2305
2306 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002307 // executed the new block before. If so, we have a looping function,
2308 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002309 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002310 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002311
2312 // Okay, we have never been in this block before. Check to see if there
2313 // are any PHI nodes. If so, evaluate them with information about where
2314 // we came from.
2315 BasicBlock *OldBB = CurInst->getParent();
2316 CurInst = NewBB->begin();
2317 PHINode *PN;
2318 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2319 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2320
2321 // Do NOT increment CurInst. We know that the terminator had no value.
2322 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002323 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002324 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002325 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002326 }
2327
2328 if (!CurInst->use_empty())
2329 Values[CurInst] = InstResult;
2330
2331 // Advance program counter.
2332 ++CurInst;
2333 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002334}
2335
2336/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2337/// we can. Return true if we can, false otherwise.
2338static bool EvaluateStaticConstructor(Function *F) {
2339 /// MutatedMemory - For each store we execute, we update this map. Loads
2340 /// check this to get the most up-to-date value. If evaluation is successful,
2341 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002342 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002343
2344 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2345 /// to represent its body. This vector is needed so we can delete the
2346 /// temporary globals when we are done.
2347 std::vector<GlobalVariable*> AllocaTmps;
2348
2349 /// CallStack - This is used to detect recursion. In pathological situations
2350 /// we could hit exponential behavior, but at least there is nothing
2351 /// unbounded.
2352 std::vector<Function*> CallStack;
2353
2354 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002355 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002356 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2357 SmallVector<Constant*, 0>(), CallStack,
2358 MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002359 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002360 // We succeeded at evaluation: commit the result.
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002361 DEBUG(errs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2362 << F->getName() << "' to " << MutatedMemory.size()
2363 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002364 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002365 E = MutatedMemory.end(); I != E; ++I)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002366 CommitValueTo(I->second, I->first, F->getContext());
Chris Lattnera22fdb02005-09-26 17:07:09 +00002367 }
Chris Lattner79c11012005-09-26 04:44:35 +00002368
Chris Lattnera22fdb02005-09-26 17:07:09 +00002369 // At this point, we are done interpreting. If we created any 'alloca'
2370 // temporaries, release them now.
2371 while (!AllocaTmps.empty()) {
2372 GlobalVariable *Tmp = AllocaTmps.back();
2373 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002374
Chris Lattnera22fdb02005-09-26 17:07:09 +00002375 // If there are still users of the alloca, the program is doing something
2376 // silly, e.g. storing the address of the alloca somewhere and using it
2377 // later. Since this is undefined, we'll just make it be null.
2378 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002379 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002380 delete Tmp;
2381 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002382
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002383 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002384}
2385
Chris Lattnerdb973e62005-09-26 02:31:18 +00002386
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002387
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002388/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2389/// Return true if anything changed.
2390bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2391 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2392 bool MadeChange = false;
2393 if (Ctors.empty()) return false;
2394
2395 // Loop over global ctors, optimizing them when we can.
2396 for (unsigned i = 0; i != Ctors.size(); ++i) {
2397 Function *F = Ctors[i];
2398 // Found a null terminator in the middle of the list, prune off the rest of
2399 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002400 if (F == 0) {
2401 if (i != Ctors.size()-1) {
2402 Ctors.resize(i+1);
2403 MadeChange = true;
2404 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002405 break;
2406 }
2407
Chris Lattner79c11012005-09-26 04:44:35 +00002408 // We cannot simplify external ctor functions.
2409 if (F->empty()) continue;
2410
2411 // If we can evaluate the ctor at compile time, do.
2412 if (EvaluateStaticConstructor(F)) {
2413 Ctors.erase(Ctors.begin()+i);
2414 MadeChange = true;
2415 --i;
2416 ++NumCtorsEvaluated;
2417 continue;
2418 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002419 }
2420
2421 if (!MadeChange) return false;
2422
Owen Andersone922c022009-07-22 00:24:57 +00002423 GCL = InstallGlobalCtors(GCL, Ctors, GCL->getContext());
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002424 return true;
2425}
2426
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002427bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002428 bool Changed = false;
2429
Duncan Sands177d84e2009-01-07 20:01:06 +00002430 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002431 I != E;) {
2432 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002433 // Aliases without names cannot be referenced outside this module.
2434 if (!J->hasName() && !J->isDeclaration())
2435 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002436 // If the aliasee may change at link time, nothing can be done - bail out.
2437 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002438 continue;
2439
Duncan Sands4782b302009-02-15 09:56:08 +00002440 Constant *Aliasee = J->getAliasee();
2441 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002442 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002443 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2444
2445 // Make all users of the alias use the aliasee instead.
2446 if (!J->use_empty()) {
2447 J->replaceAllUsesWith(Aliasee);
2448 ++NumAliasesResolved;
2449 Changed = true;
2450 }
2451
2452 // If the aliasee has internal linkage, give it the name and linkage
2453 // of the alias, and delete the alias. This turns:
2454 // define internal ... @f(...)
2455 // @a = alias ... @f
2456 // into:
2457 // define ... @a(...)
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002458 if (!Target->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002459 continue;
2460
2461 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002462 if (J->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002463 continue;
2464
Duncan Sandsa37d1192009-02-15 11:54:49 +00002465 // Do not perform the transform if multiple aliases potentially target the
2466 // aliasee. This check also ensures that it is safe to replace the section
2467 // and other attributes of the aliasee with those of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002468 if (!hasOneUse)
2469 continue;
2470
Duncan Sandsa37d1192009-02-15 11:54:49 +00002471 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002472 Target->takeName(J);
2473 Target->setLinkage(J->getLinkage());
Duncan Sandsa37d1192009-02-15 11:54:49 +00002474 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sands4782b302009-02-15 09:56:08 +00002475
2476 // Delete the alias.
2477 M.getAliasList().erase(J);
2478 ++NumAliasesRemoved;
2479 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002480 }
2481
2482 return Changed;
2483}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002484
Chris Lattner7a90b682004-10-07 04:16:33 +00002485bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002486 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002487
2488 // Try to find the llvm.globalctors list.
2489 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002490
Chris Lattner7a90b682004-10-07 04:16:33 +00002491 bool LocalChange = true;
2492 while (LocalChange) {
2493 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002494
2495 // Delete functions that are trivially dead, ccc -> fastcc
2496 LocalChange |= OptimizeFunctions(M);
2497
2498 // Optimize global_ctors list.
2499 if (GlobalCtors)
2500 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2501
2502 // Optimize non-address-taken globals.
2503 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002504
2505 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002506 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002507 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002508 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002509
2510 // TODO: Move all global ctors functions to the end of the module for code
2511 // layout.
2512
Chris Lattner079236d2004-02-25 21:34:36 +00002513 return Changed;
2514}