blob: 8362e8c8939eaf6524e0d15c5745ed5f2ebcb672 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Devang Patelf70bda22009-03-06 00:21:00 +000026#include "llvm/Transforms/Utils/Local.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"
Chris Lattner941db492008-01-14 02:09:12 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000032#include "llvm/Support/MathExtras.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000033#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000034#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000035#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/ADT/Statistic.h"
Chris Lattner670c8892004-10-08 17:32:09 +000037#include "llvm/ADT/StringExtras.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000038#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000039#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000040using namespace llvm;
41
Chris Lattner86453c52006-12-19 22:09:18 +000042STATISTIC(NumMarked , "Number of globals marked constant");
43STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
44STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
45STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
46STATISTIC(NumDeleted , "Number of globals deleted");
47STATISTIC(NumFnDeleted , "Number of functions deleted");
48STATISTIC(NumGlobUses , "Number of global uses devirtualized");
49STATISTIC(NumLocalized , "Number of globals localized");
50STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
51STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
52STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000053STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000054STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
55STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Chris Lattner079236d2004-02-25 21:34:36 +000056
Chris Lattner86453c52006-12-19 22:09:18 +000057namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000058 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000059 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60 AU.addRequired<TargetData>();
61 }
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);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +000071 bool ResolveAliases(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
140/// ConstantIsDead - Return true if the specified constant is (transitively)
Devang Patel743cdf82009-03-06 01:37:41 +0000141/// dead. The constant may be used by other constants (e.g. constant arrays and
142/// constant exprs) as long as they are dead, but it cannot be used by anything
143/// else.
144static bool ConstantIsDead(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)) {
149 if (!ConstantIsDead(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 Lattner35c81b02005-02-27 18:58:52 +0000223 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
224 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.
237 if (!ConstantIsDead(C))
238 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
Chris Lattner670c8892004-10-08 17:32:09 +0000248static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
249 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
250 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000251 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000252
Chris Lattner670c8892004-10-08 17:32:09 +0000253 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
254 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
255 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
256 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000257 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000258 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000259 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000260 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
261 if (IdxV < STy->getNumElements())
262 return Constant::getNullValue(STy->getElementType(IdxV));
263 } else if (const SequentialType *STy =
264 dyn_cast<SequentialType>(Agg->getType())) {
265 return Constant::getNullValue(STy->getElementType());
266 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000267 } else if (isa<UndefValue>(Agg)) {
268 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
269 if (IdxV < STy->getNumElements())
270 return UndefValue::get(STy->getElementType(IdxV));
271 } else if (const SequentialType *STy =
272 dyn_cast<SequentialType>(Agg->getType())) {
273 return UndefValue::get(STy->getElementType());
274 }
Chris Lattner670c8892004-10-08 17:32:09 +0000275 }
276 return 0;
277}
Chris Lattner7a90b682004-10-07 04:16:33 +0000278
Chris Lattner7a90b682004-10-07 04:16:33 +0000279
Chris Lattnere47ba742004-10-06 20:57:02 +0000280/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
281/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000282/// quick scan over the use list to clean up the easy and obvious cruft. This
283/// returns true if it made a change.
284static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
285 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000286 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
287 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000288
Chris Lattner7a90b682004-10-07 04:16:33 +0000289 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000290 if (Init) {
291 // Replace the load with the initializer.
292 LI->replaceAllUsesWith(Init);
293 LI->eraseFromParent();
294 Changed = true;
295 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000296 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000297 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000298 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000299 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000300 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
301 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000302 Constant *SubInit = 0;
303 if (Init)
304 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000305 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000306 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000307 isa<PointerType>(CE->getType())) {
308 // Pointer cast, delete any stores and memsets to the global.
309 Changed |= CleanupConstantGlobalUsers(CE, 0);
310 }
311
312 if (CE->use_empty()) {
313 CE->destroyConstant();
314 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000315 }
316 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000317 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
318 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
319 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000320 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000321 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
322 ConstantExpr *CE =
323 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
324 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner19450242007-11-13 21:46:23 +0000325 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000326 }
Chris Lattner19450242007-11-13 21:46:23 +0000327 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000328
Chris Lattner031955d2004-10-10 16:43:46 +0000329 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000330 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000331 Changed = true;
332 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000333 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
334 if (MI->getRawDest() == V) {
335 MI->eraseFromParent();
336 Changed = true;
337 }
338
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000339 } else if (Constant *C = dyn_cast<Constant>(U)) {
340 // If we have a chain of dead constantexprs or other things dangling from
341 // us, and if they are all dead, nuke them without remorse.
Devang Patel743cdf82009-03-06 01:37:41 +0000342 if (ConstantIsDead(C)) {
343 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000344 // This could have invalidated UI, start over from scratch.
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000345 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000346 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000347 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000348 }
349 }
Chris Lattner031955d2004-10-10 16:43:46 +0000350 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000351}
352
Chris Lattner941db492008-01-14 02:09:12 +0000353/// isSafeSROAElementUse - Return true if the specified instruction is a safe
354/// user of a derived expression from a global that we want to SROA.
355static bool isSafeSROAElementUse(Value *V) {
356 // We might have a dead and dangling constant hanging off of here.
357 if (Constant *C = dyn_cast<Constant>(V))
358 return ConstantIsDead(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000359
Chris Lattner941db492008-01-14 02:09:12 +0000360 Instruction *I = dyn_cast<Instruction>(V);
361 if (!I) return false;
362
363 // Loads are ok.
364 if (isa<LoadInst>(I)) return true;
365
366 // Stores *to* the pointer are ok.
367 if (StoreInst *SI = dyn_cast<StoreInst>(I))
368 return SI->getOperand(0) != V;
369
370 // Otherwise, it must be a GEP.
371 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
372 if (GEPI == 0) return false;
373
374 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
375 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
376 return false;
377
378 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
379 I != E; ++I)
380 if (!isSafeSROAElementUse(*I))
381 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000382 return true;
383}
384
Chris Lattner941db492008-01-14 02:09:12 +0000385
386/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
387/// Look at it and its uses and decide whether it is safe to SROA this global.
388///
389static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
390 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
391 if (!isa<GetElementPtrInst>(U) &&
392 (!isa<ConstantExpr>(U) ||
393 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
394 return false;
395
396 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
397 // don't like < 3 operand CE's, and we don't like non-constant integer
398 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
399 // value of C.
400 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
401 !cast<Constant>(U->getOperand(1))->isNullValue() ||
402 !isa<ConstantInt>(U->getOperand(2)))
403 return false;
404
405 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
406 ++GEPI; // Skip over the pointer index.
407
408 // If this is a use of an array allocation, do a bit more checking for sanity.
409 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
410 uint64_t NumElements = AT->getNumElements();
411 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
412
413 // Check to make sure that index falls within the array. If not,
414 // something funny is going on, so we won't do the optimization.
415 //
416 if (Idx->getZExtValue() >= NumElements)
417 return false;
418
419 // We cannot scalar repl this level of the array unless any array
420 // sub-indices are in-range constants. In particular, consider:
421 // A[0][i]. We cannot know that the user isn't doing invalid things like
422 // allowing i to index an out-of-range subscript that accesses A[1].
423 //
424 // Scalar replacing *just* the outer index of the array is probably not
425 // going to be a win anyway, so just give up.
426 for (++GEPI; // Skip array index.
427 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
428 ++GEPI) {
429 uint64_t NumElements;
430 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
431 NumElements = SubArrayTy->getNumElements();
432 else
433 NumElements = cast<VectorType>(*GEPI)->getNumElements();
434
435 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
436 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
437 return false;
438 }
439 }
440
441 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
442 if (!isSafeSROAElementUse(*I))
443 return false;
444 return true;
445}
446
447/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
448/// is safe for us to perform this transformation.
449///
450static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
451 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
452 UI != E; ++UI) {
453 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
454 return false;
455 }
456 return true;
457}
458
459
Chris Lattner670c8892004-10-08 17:32:09 +0000460/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
461/// variable. This opens the door for other optimizations by exposing the
462/// behavior of the program in a more fine-grained way. We have determined that
463/// this transformation is safe already. We return the first global variable we
464/// insert so that the caller can reprocess it.
Chris Lattner998182b2008-04-26 07:40:11 +0000465static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000466 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000467 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000468 return 0;
469
Rafael Espindolabb46f522009-01-15 20:18:42 +0000470 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000471 Constant *Init = GV->getInitializer();
472 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000473
Chris Lattner670c8892004-10-08 17:32:09 +0000474 std::vector<GlobalVariable*> NewGlobals;
475 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
476
Chris Lattner998182b2008-04-26 07:40:11 +0000477 // Get the alignment of the global, either explicit or target-specific.
478 unsigned StartAlignment = GV->getAlignment();
479 if (StartAlignment == 0)
480 StartAlignment = TD.getABITypeAlignment(GV->getType());
481
Chris Lattner670c8892004-10-08 17:32:09 +0000482 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
483 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000484 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000485 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
486 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000487 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000488 assert(In && "Couldn't get element of initializer?");
489 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
490 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000491 In, GV->getName()+"."+utostr(i),
492 (Module *)NULL,
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000493 GV->isThreadLocal(),
494 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000495 Globals.insert(GV, NGV);
496 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000497
498 // Calculate the known alignment of the field. If the original aggregate
499 // had 256 byte alignment for example, something might depend on that:
500 // propagate info to each field.
501 uint64_t FieldOffset = Layout.getElementOffset(i);
502 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
503 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
504 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000505 }
506 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
507 unsigned NumElements = 0;
508 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
509 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000510 else
Chris Lattner998182b2008-04-26 07:40:11 +0000511 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000512
Chris Lattner1f21ef12005-02-23 16:53:04 +0000513 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000514 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000515 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000516
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000517 uint64_t EltSize = TD.getTypePaddedSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000518 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000519 for (unsigned i = 0, e = NumElements; i != e; ++i) {
520 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000521 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000522 assert(In && "Couldn't get element of initializer?");
523
524 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
525 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000526 In, GV->getName()+"."+utostr(i),
527 (Module *)NULL,
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000528 GV->isThreadLocal(),
529 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000530 Globals.insert(GV, NGV);
531 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000532
533 // Calculate the known alignment of the field. If the original aggregate
534 // had 256 byte alignment for example, something might depend on that:
535 // propagate info to each field.
536 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
537 if (NewAlign > EltAlign)
538 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000539 }
540 }
541
542 if (NewGlobals.empty())
543 return 0;
544
Bill Wendling0a81aac2006-11-26 10:02:32 +0000545 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000546
Reid Spencerc5b206b2006-12-31 05:48:39 +0000547 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner670c8892004-10-08 17:32:09 +0000548
549 // Loop over all of the uses of the global, replacing the constantexpr geps,
550 // with smaller constantexpr geps or direct references.
551 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000552 User *GEP = GV->use_back();
553 assert(((isa<ConstantExpr>(GEP) &&
554 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
555 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000556
Chris Lattner670c8892004-10-08 17:32:09 +0000557 // Ignore the 1th operand, which has to be zero or else the program is quite
558 // broken (undefined). Get the 2nd operand, which is the structure or array
559 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000560 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000561 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
562
Chris Lattner30ba5692004-10-11 05:54:41 +0000563 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000564
565 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000566 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000567 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000568 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000569 Idxs.push_back(NullInt);
570 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
571 Idxs.push_back(CE->getOperand(i));
Chris Lattner55eb1c42007-01-31 04:40:53 +0000572 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
573 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000574 } else {
575 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000576 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000577 Idxs.push_back(NullInt);
578 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
579 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000580 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
581 GEPI->getName()+"."+utostr(Val), GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000582 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000583 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000584 GEP->replaceAllUsesWith(NewPtr);
585
586 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000587 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000588 else
589 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000590 }
591
Chris Lattnere40e2d12004-10-08 20:25:55 +0000592 // Delete the old global, now that it is dead.
593 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000594 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000595
596 // Loop over the new globals array deleting any globals that are obviously
597 // dead. This can arise due to scalarization of a structure or an array that
598 // has elements that are dead.
599 unsigned FirstGlobal = 0;
600 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
601 if (NewGlobals[i]->use_empty()) {
602 Globals.erase(NewGlobals[i]);
603 if (FirstGlobal == i) ++FirstGlobal;
604 }
605
606 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000607}
608
Chris Lattner9b34a612004-10-09 21:48:45 +0000609/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000610/// value will trap if the value is dynamically null. PHIs keeps track of any
611/// phi nodes we've seen to avoid reprocessing them.
612static bool AllUsesOfValueWillTrapIfNull(Value *V,
613 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000614 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
615 if (isa<LoadInst>(*UI)) {
616 // Will trap.
617 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
618 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000619 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000620 return false; // Storing the value.
621 }
622 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
623 if (CI->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; // Not calling the ptr
626 }
627 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
628 if (II->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 }
Chris Lattner81686182007-09-13 16:30:19 +0000632 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
633 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000634 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000635 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
636 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
637 // If we've already seen this phi node, ignore it, it has already been
638 // checked.
639 if (PHIs.insert(PN))
640 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000641 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000642 isa<ConstantPointerNull>(UI->getOperand(1))) {
643 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000644 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000645 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000646 return false;
647 }
648 return true;
649}
650
651/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000652/// from GV will trap if the loaded value is null. Note that this also permits
653/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000654static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
655 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
656 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000657 SmallPtrSet<PHINode*, 8> PHIs;
658 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000659 return false;
660 } else if (isa<StoreInst>(*UI)) {
661 // Ignore stores to the global.
662 } else {
663 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000664 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000665 return false;
666 }
667
668 return true;
669}
670
Chris Lattner708148e2004-10-10 23:14:11 +0000671static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
672 bool Changed = false;
673 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
674 Instruction *I = cast<Instruction>(*UI++);
675 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
676 LI->setOperand(0, NewV);
677 Changed = true;
678 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
679 if (SI->getOperand(1) == V) {
680 SI->setOperand(1, NewV);
681 Changed = true;
682 }
683 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
684 if (I->getOperand(0) == V) {
685 // Calling through the pointer! Turn into a direct call, but be careful
686 // that the pointer is not also being passed as an argument.
687 I->setOperand(0, NewV);
688 Changed = true;
689 bool PassedAsArg = false;
690 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
691 if (I->getOperand(i) == V) {
692 PassedAsArg = true;
693 I->setOperand(i, NewV);
694 }
695
696 if (PassedAsArg) {
697 // Being passed as an argument also. Be careful to not invalidate UI!
698 UI = V->use_begin();
699 }
700 }
701 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
702 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000703 ConstantExpr::getCast(CI->getOpcode(),
704 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000705 if (CI->use_empty()) {
706 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000707 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000708 }
709 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
710 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000711 SmallVector<Constant*, 8> Idxs;
712 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000713 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
714 i != e; ++i)
715 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000716 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000717 else
718 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000719 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000720 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Chris Lattner55eb1c42007-01-31 04:40:53 +0000721 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
722 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000723 if (GEPI->use_empty()) {
724 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000725 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000726 }
727 }
728 }
729
730 return Changed;
731}
732
733
734/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
735/// value stored into it. If there are uses of the loaded value that would trap
736/// if the loaded value is dynamically null, then we know that they cannot be
737/// reachable with a null optimize away the load.
738static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000739 bool Changed = false;
740
Chris Lattner92c6bd22009-01-14 00:12:58 +0000741 // Keep track of whether we are able to remove all the uses of the global
742 // other than the store that defines it.
743 bool AllNonStoreUsesGone = true;
744
Chris Lattner708148e2004-10-10 23:14:11 +0000745 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000746 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
747 User *GlobalUser = *GUI++;
748 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner708148e2004-10-10 23:14:11 +0000749 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000750 // If we were able to delete all uses of the loads
751 if (LI->use_empty()) {
752 LI->eraseFromParent();
753 Changed = true;
754 } else {
755 AllNonStoreUsesGone = false;
756 }
757 } else if (isa<StoreInst>(GlobalUser)) {
758 // Ignore the store that stores "LV" to the global.
759 assert(GlobalUser->getOperand(1) == GV &&
760 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000761 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000762 AllNonStoreUsesGone = false;
763
764 // If we get here we could have other crazy uses that are transitively
765 // loaded.
766 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
767 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000768 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000769 }
Chris Lattner708148e2004-10-10 23:14:11 +0000770
771 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000772 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000773 ++NumGlobUses;
774 }
775
Chris Lattner708148e2004-10-10 23:14:11 +0000776 // If we nuked all of the loads, then none of the stores are needed either,
777 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000778 if (AllNonStoreUsesGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000779 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattner708148e2004-10-10 23:14:11 +0000780 CleanupConstantGlobalUsers(GV, 0);
781 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000782 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000783 ++NumDeleted;
784 }
785 Changed = true;
786 }
787 return Changed;
788}
789
Chris Lattner30ba5692004-10-11 05:54:41 +0000790/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
791/// instructions that are foldable.
792static void ConstantPropUsersOf(Value *V) {
793 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
794 if (Instruction *I = dyn_cast<Instruction>(*UI++))
795 if (Constant *NewC = ConstantFoldInstruction(I)) {
796 I->replaceAllUsesWith(NewC);
797
Chris Lattnerd514d822005-02-01 01:23:31 +0000798 // Advance UI to the next non-I use to avoid invalidating it!
799 // Instructions could multiply use V.
800 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000801 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000802 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000803 }
804}
805
806/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
807/// variable, and transforms the program as if it always contained the result of
808/// the specified malloc. Because it is always the result of the specified
809/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000810/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000811static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
812 MallocInst *MI) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000813 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000814 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
815
Reid Spencerb83eb642006-10-20 07:07:24 +0000816 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000817 // If we have an array allocation, transform it to a single element
818 // allocation to make the code below simpler.
819 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000820 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000821 MallocInst *NewMI =
Reid Spencerc5b206b2006-12-31 05:48:39 +0000822 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
Nate Begeman14b05292005-11-05 09:21:28 +0000823 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000824 Value* Indices[2];
825 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greif051a9502008-04-06 20:25:17 +0000826 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
827 NewMI->getName()+".el0", MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000828 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000829 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000830 MI = NewMI;
831 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000832
Chris Lattner7a7ed022004-10-16 18:09:00 +0000833 // Create the new global variable. The contents of the malloc'd memory is
834 // undefined, so initialize with an undef value.
835 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000836 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
837 GlobalValue::InternalLinkage, Init,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000838 GV->getName()+".body",
839 (Module *)NULL,
840 GV->isThreadLocal());
Chris Lattner998182b2008-04-26 07:40:11 +0000841 // FIXME: This new global should have the alignment returned by malloc. Code
842 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
843 // this would only guarantee some lower alignment.
Chris Lattner30ba5692004-10-11 05:54:41 +0000844 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanfd939082005-04-21 23:48:37 +0000845
Chris Lattner30ba5692004-10-11 05:54:41 +0000846 // Anything that used the malloc now uses the global directly.
847 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000848
849 Constant *RepValue = NewGV;
850 if (NewGV->getType() != GV->getType()->getElementType())
Reid Spencerd977d862006-12-12 23:36:14 +0000851 RepValue = ConstantExpr::getBitCast(RepValue,
852 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000853
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000854 // If there is a comparison against null, we will insert a global bool to
855 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000856 GlobalVariable *InitBool =
Reid Spencer4fe16d62007-01-11 18:21:29 +0000857 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000858 ConstantInt::getFalse(), GV->getName()+".init",
859 (Module *)NULL, GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000860 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000861
Chris Lattner30ba5692004-10-11 05:54:41 +0000862 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000863 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000864 while (!GV->use_empty())
865 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000866 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000867 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000868 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000869 LoadUse = RepValue;
870 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000871 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
872 // Replace the cmp X, 0 with a use of the bool value.
873 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000874 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000875 switch (CI->getPredicate()) {
876 default: assert(0 && "Unknown ICmp Predicate!");
877 case ICmpInst::ICMP_ULT:
878 case ICmpInst::ICMP_SLT:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000879 LV = ConstantInt::getFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000880 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000881 case ICmpInst::ICMP_ULE:
882 case ICmpInst::ICMP_SLE:
883 case ICmpInst::ICMP_EQ:
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000884 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000885 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000886 case ICmpInst::ICMP_NE:
887 case ICmpInst::ICMP_UGE:
888 case ICmpInst::ICMP_SGE:
889 case ICmpInst::ICMP_UGT:
890 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000891 break; // no change.
892 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000893 CI->replaceAllUsesWith(LV);
894 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000895 }
896 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000897 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000898 } else {
899 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000900 // The global is initialized when the store to it occurs.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000901 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000902 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000903 }
904
Chris Lattnerbc965b92004-12-02 06:25:58 +0000905 // If the initialization boolean was used, insert it, otherwise delete it.
906 if (!InitBoolUsed) {
907 while (!InitBool->use_empty()) // Delete initializations
908 cast<Instruction>(InitBool->use_back())->eraseFromParent();
909 delete InitBool;
910 } else
911 GV->getParent()->getGlobalList().insert(GV, InitBool);
912
913
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000914 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000915 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000916 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000917
918 // To further other optimizations, loop over all users of NewGV and try to
919 // constant prop them. This will promote GEP instructions with constant
920 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
921 ConstantPropUsersOf(NewGV);
922 if (RepValue != NewGV)
923 ConstantPropUsersOf(RepValue);
924
925 return NewGV;
926}
Chris Lattner708148e2004-10-10 23:14:11 +0000927
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000928/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
929/// to make sure that there are no complex uses of V. We permit simple things
930/// like dereferencing the pointer, but not storing through the address, unless
931/// it is to the specified global.
932static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000933 GlobalVariable *GV,
934 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000935 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
936 Instruction *Inst = dyn_cast<Instruction>(*UI);
937 if (Inst == 0) return false;
938
939 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
940 continue; // Fine, ignore.
941 }
942
943 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000944 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
945 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000946 continue; // Otherwise, storing through it, or storing into GV... fine.
947 }
948
949 if (isa<GetElementPtrInst>(Inst)) {
950 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000951 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000952 continue;
953 }
954
955 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000956 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
957 // cycles.
958 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000959 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
960 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000961 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000962 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000963
964 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
965 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
966 return false;
967 continue;
968 }
969
970 return false;
971 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000972 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000973}
974
Chris Lattner86395032006-09-30 23:32:09 +0000975/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
976/// somewhere. Transform all uses of the allocation into loads from the
977/// global and uses of the resultant pointer. Further, delete the store into
978/// GV. This assumes that these value pass the
979/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
980static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
981 GlobalVariable *GV) {
982 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000983 Instruction *U = cast<Instruction>(*Alloc->use_begin());
984 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +0000985 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
986 // If this is the store of the allocation into the global, remove it.
987 if (SI->getOperand(1) == GV) {
988 SI->eraseFromParent();
989 continue;
990 }
Chris Lattnera637a8b2007-09-13 18:00:31 +0000991 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
992 // Insert the load in the corresponding predecessor, not right before the
993 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +0000994 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +0000995 } else if (isa<BitCastInst>(U)) {
996 // Must be bitcast between the malloc and store to initialize the global.
997 ReplaceUsesOfMallocWithGlobal(U, GV);
998 U->eraseFromParent();
999 continue;
1000 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1001 // If this is a "GEP bitcast" and the user is a store to the global, then
1002 // just process it as a bitcast.
1003 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1004 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1005 if (SI->getOperand(1) == GV) {
1006 // Must be bitcast GEP between the malloc and store to initialize
1007 // the global.
1008 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1009 GEPI->eraseFromParent();
1010 continue;
1011 }
Chris Lattner86395032006-09-30 23:32:09 +00001012 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001013
Chris Lattner86395032006-09-30 23:32:09 +00001014 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001015 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001016 U->replaceUsesOfWith(Alloc, NL);
1017 }
1018}
1019
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001020/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1021/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1022/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001023static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
1024 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001025 // We permit two users of the load: setcc comparing against the null
1026 // pointer, and a getelementptr of a specific form.
1027 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1028 Instruction *User = cast<Instruction>(*UI);
1029
1030 // Comparison against null is ok.
1031 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1032 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1033 return false;
1034 continue;
1035 }
1036
1037 // getelementptr is also ok, but only a simple form.
1038 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1039 // Must index into the array and into the struct.
1040 if (GEPI->getNumOperands() < 3)
1041 return false;
1042
1043 // Otherwise the GEP is ok.
1044 continue;
1045 }
1046
1047 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1048 // If we have already recursively analyzed this PHI, then it is safe.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001049 if (LoadUsingPHIs.insert(PN))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001050 continue;
1051
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001052 // Make sure all uses of the PHI are simple enough to transform.
1053 if (!LoadUsesSimpleEnoughForHeapSRA(PN, LoadUsingPHIs))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001054 return false;
1055
1056 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001057 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001058
1059 // Otherwise we don't know what this is, not ok.
1060 return false;
1061 }
1062
1063 return true;
1064}
1065
1066
1067/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1068/// GV are simple enough to perform HeapSRA, return true.
1069static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1070 MallocInst *MI) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001071 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001072 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1073 ++UI)
1074 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001075 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001076 return false;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001077
1078 // If we reach here, we know that all uses of the loads and transitive uses
1079 // (through PHI nodes) are simple enough to transform. However, we don't know
1080 // that all inputs the to the PHI nodes are in the same equivalence sets.
1081 // Check to verify that all operands of the PHIs are either PHIS that can be
1082 // transformed, loads from GV, or MI itself.
1083 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1084 E = LoadUsingPHIs.end(); I != E; ++I) {
1085 PHINode *PN = *I;
1086 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1087 Value *InVal = PN->getIncomingValue(op);
1088
1089 // PHI of the stored value itself is ok.
1090 if (InVal == MI) continue;
1091
1092 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1093 // One of the PHIs in our set is (optimistically) ok.
1094 if (LoadUsingPHIs.count(InPN))
1095 continue;
1096 return false;
1097 }
1098
1099 // Load from GV is ok.
1100 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1101 if (LI->getOperand(0) == GV)
1102 continue;
1103
1104 // UNDEF? NULL?
1105
1106 // Anything else is rejected.
1107 return false;
1108 }
1109 }
1110
Chris Lattner86395032006-09-30 23:32:09 +00001111 return true;
1112}
1113
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001114static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1115 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1116 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1117 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1118
1119 if (FieldNo >= FieldVals.size())
1120 FieldVals.resize(FieldNo+1);
1121
1122 // If we already have this value, just reuse the previously scalarized
1123 // version.
1124 if (Value *FieldVal = FieldVals[FieldNo])
1125 return FieldVal;
1126
1127 // Depending on what instruction this is, we have several cases.
1128 Value *Result;
1129 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1130 // This is a scalarized version of the load from the global. Just create
1131 // a new Load of the scalarized global.
1132 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1133 InsertedScalarizedValues,
1134 PHIsToRewrite),
1135 LI->getName()+".f" + utostr(FieldNo), LI);
1136 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1137 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1138 // field.
1139 const StructType *ST =
1140 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1141
1142 Result =PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1143 PN->getName()+".f"+utostr(FieldNo), PN);
1144 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1145 } else {
1146 assert(0 && "Unknown usable value");
1147 Result = 0;
1148 }
1149
1150 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001151}
1152
Chris Lattner330245e2007-09-13 17:29:05 +00001153/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1154/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001155static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1156 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1157 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001158 // If this is a comparison against null, handle it.
1159 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1160 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1161 // If we have a setcc of the loaded pointer, we can use a setcc of any
1162 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001163 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1164 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner330245e2007-09-13 17:29:05 +00001165
1166 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
1167 Constant::getNullValue(NPtr->getType()),
1168 SCI->getName(), SCI);
1169 SCI->replaceAllUsesWith(New);
1170 SCI->eraseFromParent();
1171 return;
1172 }
1173
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001174 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001175 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1176 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1177 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001178
Chris Lattnera637a8b2007-09-13 18:00:31 +00001179 // Load the pointer for this field.
1180 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001181 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1182 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001183
1184 // Create the new GEP idx vector.
1185 SmallVector<Value*, 8> GEPIdx;
1186 GEPIdx.push_back(GEPI->getOperand(1));
1187 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1188
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001189 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1190 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001191 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001192 GEPI->replaceAllUsesWith(NGEPI);
1193 GEPI->eraseFromParent();
1194 return;
1195 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001196
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001197 // Recursively transform the users of PHI nodes. This will lazily create the
1198 // PHIs that are needed for individual elements. Keep track of what PHIs we
1199 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1200 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1201 // already been seen first by another load, so its uses have already been
1202 // processed.
1203 PHINode *PN = cast<PHINode>(LoadUser);
1204 bool Inserted;
1205 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1206 tie(InsertPos, Inserted) =
1207 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1208 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001209
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001210 // If this is the first time we've seen this PHI, recursively process all
1211 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001212 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1213 Instruction *User = cast<Instruction>(*UI++);
1214 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1215 }
Chris Lattner330245e2007-09-13 17:29:05 +00001216}
1217
Chris Lattner86395032006-09-30 23:32:09 +00001218/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1219/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1220/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001221/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001222static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001223 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1224 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1225 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001226 UI != E; ) {
1227 Instruction *User = cast<Instruction>(*UI++);
1228 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1229 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001230
1231 if (Load->use_empty()) {
1232 Load->eraseFromParent();
1233 InsertedScalarizedValues.erase(Load);
1234 }
Chris Lattner86395032006-09-30 23:32:09 +00001235}
1236
1237/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1238/// it up into multiple allocations of arrays of the fields.
1239static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Bill Wendling0a81aac2006-11-26 10:02:32 +00001240 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +00001241 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1242
1243 // There is guaranteed to be at least one use of the malloc (storing
1244 // it into GV). If there are other uses, change them to be uses of
1245 // the global to simplify later code. This also deletes the store
1246 // into GV.
1247 ReplaceUsesOfMallocWithGlobal(MI, GV);
1248
1249 // Okay, at this point, there are no users of the malloc. Insert N
1250 // new mallocs at the same place as MI, and N globals.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001251 std::vector<Value*> FieldGlobals;
Chris Lattner86395032006-09-30 23:32:09 +00001252 std::vector<MallocInst*> FieldMallocs;
1253
1254 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1255 const Type *FieldTy = STy->getElementType(FieldNo);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001256 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001257
1258 GlobalVariable *NGV =
1259 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
1260 Constant::getNullValue(PFieldTy),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001261 GV->getName() + ".f" + utostr(FieldNo), GV,
1262 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001263 FieldGlobals.push_back(NGV);
1264
1265 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1266 MI->getName() + ".f" + utostr(FieldNo),MI);
1267 FieldMallocs.push_back(NMI);
1268 new StoreInst(NMI, NGV, MI);
1269 }
1270
1271 // The tricky aspect of this transformation is handling the case when malloc
1272 // fails. In the original code, malloc failing would set the result pointer
1273 // of malloc to null. In this case, some mallocs could succeed and others
1274 // could fail. As such, we emit code that looks like this:
1275 // F0 = malloc(field0)
1276 // F1 = malloc(field1)
1277 // F2 = malloc(field2)
1278 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1279 // if (F0) { free(F0); F0 = 0; }
1280 // if (F1) { free(F1); F1 = 0; }
1281 // if (F2) { free(F2); F2 = 0; }
1282 // }
1283 Value *RunningOr = 0;
1284 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001285 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Chris Lattner86395032006-09-30 23:32:09 +00001286 Constant::getNullValue(FieldMallocs[i]->getType()),
1287 "isnull", MI);
1288 if (!RunningOr)
1289 RunningOr = Cond; // First seteq
1290 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001291 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Chris Lattner86395032006-09-30 23:32:09 +00001292 }
1293
1294 // Split the basic block at the old malloc.
1295 BasicBlock *OrigBB = MI->getParent();
1296 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1297
1298 // Create the block to check the first condition. Put all these blocks at the
1299 // end of the function as they are unlikely to be executed.
Gabor Greif051a9502008-04-06 20:25:17 +00001300 BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
1301 OrigBB->getParent());
Chris Lattner86395032006-09-30 23:32:09 +00001302
1303 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1304 // branch on RunningOr.
1305 OrigBB->getTerminator()->eraseFromParent();
Gabor Greif051a9502008-04-06 20:25:17 +00001306 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Chris Lattner86395032006-09-30 23:32:09 +00001307
1308 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1309 // pointer, because some may be null while others are not.
1310 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1311 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001312 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1313 Constant::getNullValue(GVVal->getType()),
1314 "tmp", NullPtrBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001315 BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
1316 BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
1317 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001318
1319 // Fill in FreeBlock.
1320 new FreeInst(GVVal, FreeBlock);
1321 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1322 FreeBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001323 BranchInst::Create(NextBlock, FreeBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001324
1325 NullPtrBlock = NextBlock;
1326 }
1327
Gabor Greif051a9502008-04-06 20:25:17 +00001328 BranchInst::Create(ContBB, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001329
1330 // MI is no longer needed, remove it.
1331 MI->eraseFromParent();
1332
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001333 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1334 /// update all uses of the load, keep track of what scalarized loads are
1335 /// inserted for a given load.
1336 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1337 InsertedScalarizedValues[GV] = FieldGlobals;
1338
1339 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Chris Lattner86395032006-09-30 23:32:09 +00001340
1341 // Okay, the malloc site is completely handled. All of the uses of GV are now
1342 // loads, and all uses of those loads are simple. Rewrite them to use loads
1343 // of the per-field globals instead.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001344 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1345 Instruction *User = cast<Instruction>(*UI++);
1346
1347 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1348 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1349 continue;
Chris Lattner39ff1e22007-01-09 23:29:37 +00001350 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001351
1352 // Must be a store of null.
1353 StoreInst *SI = cast<StoreInst>(User);
1354 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1355 "Unexpected heap-sra user!");
1356
1357 // Insert a store of null into each global.
1358 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1359 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1360 Constant *Null = Constant::getNullValue(PT->getElementType());
1361 new StoreInst(Null, FieldGlobals[i], SI);
1362 }
1363 // Erase the original store.
1364 SI->eraseFromParent();
Chris Lattner86395032006-09-30 23:32:09 +00001365 }
1366
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001367 // While we have PHIs that are interesting to rewrite, do it.
1368 while (!PHIsToRewrite.empty()) {
1369 PHINode *PN = PHIsToRewrite.back().first;
1370 unsigned FieldNo = PHIsToRewrite.back().second;
1371 PHIsToRewrite.pop_back();
1372 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1373 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1374
1375 // Add all the incoming values. This can materialize more phis.
1376 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1377 Value *InVal = PN->getIncomingValue(i);
1378 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1379 PHIsToRewrite);
1380 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1381 }
1382 }
1383
1384 // Drop all inter-phi links and any loads that made it this far.
1385 for (DenseMap<Value*, std::vector<Value*> >::iterator
1386 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1387 I != E; ++I) {
1388 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1389 PN->dropAllReferences();
1390 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1391 LI->dropAllReferences();
1392 }
1393
1394 // Delete all the phis and loads now that inter-references are dead.
1395 for (DenseMap<Value*, std::vector<Value*> >::iterator
1396 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1397 I != E; ++I) {
1398 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1399 PN->eraseFromParent();
1400 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1401 LI->eraseFromParent();
1402 }
1403
Chris Lattner86395032006-09-30 23:32:09 +00001404 // The old global is now dead, remove it.
1405 GV->eraseFromParent();
1406
1407 ++NumHeapSRA;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001408 return cast<GlobalVariable>(FieldGlobals[0]);
Chris Lattner86395032006-09-30 23:32:09 +00001409}
1410
Chris Lattnere61d0a62008-12-15 21:02:25 +00001411/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1412/// pointer global variable with a single value stored it that is a malloc or
1413/// cast of malloc.
1414static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1415 MallocInst *MI,
1416 Module::global_iterator &GVI,
1417 TargetData &TD) {
1418 // If this is a malloc of an abstract type, don't touch it.
1419 if (!MI->getAllocatedType()->isSized())
1420 return false;
1421
1422 // We can't optimize this global unless all uses of it are *known* to be
1423 // of the malloc value, not of the null initializer value (consider a use
1424 // that compares the global's value against zero to see if the malloc has
1425 // been reached). To do this, we check to see if all uses of the global
1426 // would trap if the global were null: this proves that they must all
1427 // happen after the malloc.
1428 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1429 return false;
1430
1431 // We can't optimize this if the malloc itself is used in a complex way,
1432 // for example, being stored into multiple globals. This allows the
1433 // malloc to be stored into the specified global, loaded setcc'd, and
1434 // GEP'd. These are all things we could transform to using the global
1435 // for.
1436 {
1437 SmallPtrSet<PHINode*, 8> PHIs;
1438 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1439 return false;
1440 }
1441
1442
1443 // If we have a global that is only initialized with a fixed size malloc,
1444 // transform the program to use global memory instead of malloc'd memory.
1445 // This eliminates dynamic allocation, avoids an indirection accessing the
1446 // data, and exposes the resultant global to further GlobalOpt.
1447 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1448 // Restrict this transformation to only working on small allocations
1449 // (2048 bytes currently), as we don't want to introduce a 16M global or
1450 // something.
1451 if (NElements->getZExtValue()*
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001452 TD.getTypePaddedSize(MI->getAllocatedType()) < 2048) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001453 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1454 return true;
1455 }
1456 }
1457
1458 // If the allocation is an array of structures, consider transforming this
1459 // into multiple malloc'd arrays, one for each field. This is basically
1460 // SRoA for malloc'd memory.
Chris Lattner101f44e2008-12-15 21:44:34 +00001461 const Type *AllocTy = MI->getAllocatedType();
1462
1463 // If this is an allocation of a fixed size array of structs, analyze as a
1464 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1465 if (!MI->isArrayAllocation())
1466 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1467 AllocTy = AT->getElementType();
1468
1469 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001470 // This the structure has an unreasonable number of fields, leave it
1471 // alone.
Chris Lattner101f44e2008-12-15 21:44:34 +00001472 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001473 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner101f44e2008-12-15 21:44:34 +00001474
1475 // If this is a fixed size array, transform the Malloc to be an alloc of
1476 // structs. malloc [100 x struct],1 -> malloc struct, 100
1477 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1478 MallocInst *NewMI =
1479 new MallocInst(AllocSTy,
1480 ConstantInt::get(Type::Int32Ty, AT->getNumElements()),
1481 "", MI);
1482 NewMI->takeName(MI);
1483 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1484 MI->replaceAllUsesWith(Cast);
1485 MI->eraseFromParent();
1486 MI = NewMI;
1487 }
1488
Chris Lattnere61d0a62008-12-15 21:02:25 +00001489 GVI = PerformHeapAllocSRoA(GV, MI);
1490 return true;
1491 }
1492 }
1493
1494 return false;
1495}
Chris Lattner86395032006-09-30 23:32:09 +00001496
Chris Lattner9b34a612004-10-09 21:48:45 +00001497// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1498// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001499static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001500 Module::global_iterator &GVI,
1501 TargetData &TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001502 // Ignore no-op GEPs and bitcasts.
1503 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001504
Chris Lattner708148e2004-10-10 23:14:11 +00001505 // If we are dealing with a pointer global that is initialized to null and
1506 // only has one (non-null) value stored into it, then we can optimize any
1507 // users of the loaded value (often calls and loads) that would trap if the
1508 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001509 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1510 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001511 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1512 if (GV->getInitializer()->getType() != SOVC->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001513 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001514
Chris Lattner708148e2004-10-10 23:14:11 +00001515 // Optimize away any trapping uses of the loaded value.
1516 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001517 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001518 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001519 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD))
1520 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001521 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001522 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001523
Chris Lattner9b34a612004-10-09 21:48:45 +00001524 return false;
1525}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001526
Chris Lattner58e44f42008-01-14 01:17:44 +00001527/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1528/// two values ever stored into GV are its initializer and OtherVal. See if we
1529/// can shrink the global into a boolean and select between the two values
1530/// whenever it is used. This exposes the values to other scalar optimizations.
1531static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1532 const Type *GVElType = GV->getType()->getElementType();
1533
1534 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1535 // an FP value or vector, don't do this optimization because a select between
1536 // them is very expensive and unlikely to lead to later simplification.
1537 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
1538 isa<VectorType>(GVElType))
1539 return false;
1540
1541 // Walk the use list of the global seeing if all the uses are load or store.
1542 // If there is anything else, bail out.
1543 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patelf70bda22009-03-06 00:21:00 +00001544 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !UserIsDebugInfo(*I))
Chris Lattner58e44f42008-01-14 01:17:44 +00001545 return false;
1546
1547 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1548
Chris Lattner96a86b22004-12-12 05:53:50 +00001549 // Create the new global, initializing it to false.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001550 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001551 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001552 GV->getName()+".b",
1553 (Module *)NULL,
1554 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001555 GV->getParent()->getGlobalList().insert(GV, NewGV);
1556
1557 Constant *InitVal = GV->getInitializer();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001558 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001559
1560 // If initialized to zero and storing one into the global, we can use a cast
1561 // instead of a select to synthesize the desired value.
1562 bool IsOneZero = false;
1563 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001564 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001565
1566 while (!GV->use_empty()) {
Devang Patelf70bda22009-03-06 00:21:00 +00001567 User *GVU = GV->use_back();
1568 if (StoreInst *SI = dyn_cast<StoreInst>(GVU)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001569 // Change the store into a boolean store.
1570 bool StoringOther = SI->getOperand(0) == OtherVal;
1571 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001572 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001573 if (StoringOther || SI->getOperand(0) == InitVal)
Reid Spencer579dca12007-01-12 04:24:46 +00001574 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001575 else {
1576 // Otherwise, we are storing a previously loaded copy. To do this,
1577 // change the copy from copying the original value to just copying the
1578 // bool.
1579 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1580
1581 // If we're already replaced the input, StoredVal will be a cast or
1582 // select instruction. If not, it will be a load of the original
1583 // global.
1584 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1585 assert(LI->getOperand(0) == GV && "Not a copy!");
1586 // Insert a new load, to preserve the saved value.
1587 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1588 } else {
1589 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1590 "This is not a form that we understand!");
1591 StoreVal = StoredVal->getOperand(0);
1592 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1593 }
1594 }
1595 new StoreInst(StoreVal, NewGV, SI);
Devang Patelf70bda22009-03-06 00:21:00 +00001596 SI->eraseFromParent();
1597 } else if (LoadInst *LI = dyn_cast<LoadInst>(GVU)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001598 // Change the load into a load of bool then a select.
Chris Lattner046800a2007-02-11 01:08:35 +00001599 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001600 Value *NSI;
1601 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001602 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001603 else
Gabor Greif051a9502008-04-06 20:25:17 +00001604 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001605 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001606 LI->replaceAllUsesWith(NSI);
Devang Patelf70bda22009-03-06 00:21:00 +00001607 LI->eraseFromParent();
1608 } else
1609 RemoveDbgInfoUser(GVU);
Chris Lattner96a86b22004-12-12 05:53:50 +00001610 }
1611
1612 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001613 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001614}
1615
1616
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001617/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1618/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001619bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001620 Module::global_iterator &GVI) {
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001621 SmallPtrSet<PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001622 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001623 GV->removeDeadConstantUsers();
1624
1625 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001626 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001627 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001628 ++NumDeleted;
1629 return true;
1630 }
1631
1632 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001633#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001634 cerr << "Global: " << *GV;
1635 cerr << " isLoaded = " << GS.isLoaded << "\n";
1636 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001637 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001638 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1639 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1640 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1641 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001642 }
1643 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001644 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001645 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001646 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001647 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001648 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001649 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001650 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001651 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001652#endif
1653
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001654 // If this is a first class global and has only one accessing function
1655 // and this function is main (which we know is not recursive we can make
1656 // this global a local variable) we replace the global with a local alloca
1657 // in this function.
1658 //
Dan Gohman399101a2008-05-23 00:17:26 +00001659 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001660 // are just replacing static memory to stack memory.
1661 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001662 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001663 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001664 GS.AccessingFunction->getName() == "main" &&
1665 GS.AccessingFunction->hasExternalLinkage()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001666 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001667 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1668 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001669 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001670 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1671 if (!isa<UndefValue>(GV->getInitializer()))
1672 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001673
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001674 GV->replaceAllUsesWith(Alloca);
1675 GV->eraseFromParent();
1676 ++NumLocalized;
1677 return true;
1678 }
Chris Lattnercff16732006-09-30 19:40:30 +00001679
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001680 // If the global is never loaded (but may be stored to), it is dead.
1681 // Delete it now.
1682 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001683 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001684
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001685 // Delete any stores we can find to the global. We may not be able to
1686 // make it completely dead though.
Chris Lattner031955d2004-10-10 16:43:46 +00001687 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001688
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001689 // If the global is dead now, delete it.
1690 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001691 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001692 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001693 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001694 }
Chris Lattner930f4752004-10-09 03:32:52 +00001695 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001696
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001697 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001698 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001699 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001700
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001701 // Clean up any obviously simplifiable users now.
1702 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001703
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001704 // If the global is dead now, just nuke it.
1705 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001706 DOUT << " *** Marking constant allowed us to simplify "
1707 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001708 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001709 ++NumDeleted;
1710 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001711
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001712 ++NumMarked;
1713 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001714 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Chris Lattner998182b2008-04-26 07:40:11 +00001715 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
1716 getAnalysis<TargetData>())) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001717 GVI = FirstNewGV; // Don't skip the newly produced globals!
1718 return true;
1719 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001720 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001721 // If the initial value for the global was an undef value, and if only
1722 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001723 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001724 // global. This allows us to mark it constant.
1725 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1726 if (isa<UndefValue>(GV->getInitializer())) {
1727 // Change the initial value here.
1728 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001729
Chris Lattner96a86b22004-12-12 05:53:50 +00001730 // Clean up any obviously simplifiable users now.
1731 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001732
Chris Lattner96a86b22004-12-12 05:53:50 +00001733 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001734 DOUT << " *** Substituting initializer allowed us to "
1735 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001736 GV->eraseFromParent();
1737 ++NumDeleted;
1738 } else {
1739 GVI = GV;
1740 }
1741 ++NumSubstitute;
1742 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001743 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001744
Chris Lattner9b34a612004-10-09 21:48:45 +00001745 // Try to optimize globals based on the knowledge that only one value
1746 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001747 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1748 getAnalysis<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001749 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001750
1751 // Otherwise, if the global was not a boolean, we can shrink it to be a
1752 // boolean.
1753 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner58e44f42008-01-14 01:17:44 +00001754 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001755 ++NumShrunkToBool;
1756 return true;
1757 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001758 }
1759 }
1760 return false;
1761}
1762
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001763/// OnlyCalledDirectly - Return true if the specified function is only called
1764/// directly. In other words, its address is never taken.
1765static bool OnlyCalledDirectly(Function *F) {
1766 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1767 Instruction *User = dyn_cast<Instruction>(*UI);
1768 if (!User) return false;
1769 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1770
1771 // See if the function address is passed as an argument.
Gabor Greif5e463212008-05-29 01:59:18 +00001772 for (User::op_iterator i = User->op_begin() + 1, e = User->op_end();
Bill Wendlingf9e67ac2008-08-12 23:15:44 +00001773 i != e; ++i)
Gabor Greif5e463212008-05-29 01:59:18 +00001774 if (*i == F) return false;
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001775 }
1776 return true;
1777}
1778
1779/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1780/// function, changing them to FastCC.
1781static void ChangeCalleesToFastCall(Function *F) {
1782 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001783 CallSite User(cast<Instruction>(*UI));
1784 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001785 }
1786}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001787
Devang Patel05988662008-09-25 21:00:45 +00001788static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001789 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001790 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001791 continue;
1792
Duncan Sands548448a2008-02-18 17:32:13 +00001793 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001794 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001795 }
1796
1797 return Attrs;
1798}
1799
1800static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001801 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001802 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001803 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001804 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001805 }
1806}
1807
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001808bool GlobalOpt::OptimizeFunctions(Module &M) {
1809 bool Changed = false;
1810 // Optimize functions.
1811 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1812 Function *F = FI++;
1813 F->removeDeadConstantUsers();
Rafael Espindolabb46f522009-01-15 20:18:42 +00001814 if (F->use_empty() && (F->hasLocalLinkage() ||
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001815 F->hasLinkOnceLinkage())) {
1816 M.getFunctionList().erase(F);
1817 Changed = true;
1818 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001819 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001820 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1821 OnlyCalledDirectly(F)) {
1822 // If this function has C calling conventions, is not a varargs
1823 // function, and is only called directly, promote it to use the Fast
1824 // calling convention.
1825 F->setCallingConv(CallingConv::Fast);
1826 ChangeCalleesToFastCall(F);
1827 ++NumFastCallFns;
1828 Changed = true;
1829 }
1830
Devang Patel05988662008-09-25 21:00:45 +00001831 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Duncan Sands3d5378f2008-02-16 20:56:04 +00001832 OnlyCalledDirectly(F)) {
1833 // The function is not used by a trampoline intrinsic, so it is safe
1834 // to remove the 'nest' attribute.
1835 RemoveNestAttribute(F);
1836 ++NumNestRemoved;
1837 Changed = true;
1838 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001839 }
1840 }
1841 return Changed;
1842}
1843
1844bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1845 bool Changed = false;
1846 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1847 GVI != E; ) {
1848 GlobalVariable *GV = GVI++;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001849 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001850 GV->hasInitializer())
1851 Changed |= ProcessInternalGlobal(GV, GVI);
1852 }
1853 return Changed;
1854}
1855
1856/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1857/// initializers have an init priority of 65535.
1858GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001859 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1860 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001861 if (I->getName() == "llvm.global_ctors") {
1862 // Found it, verify it's an array of { int, void()* }.
1863 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1864 if (!ATy) return 0;
1865 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1866 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc5b206b2006-12-31 05:48:39 +00001867 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001868 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1869 if (!PFTy) return 0;
1870 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1871 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1872 FTy->getNumParams() != 0)
1873 return 0;
1874
1875 // Verify that the initializer is simple enough for us to handle.
1876 if (!I->hasInitializer()) return 0;
1877 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1878 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001879 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1880 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001881 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1882 continue;
1883
1884 // Must have a function or null ptr.
1885 if (!isa<Function>(CS->getOperand(1)))
1886 return 0;
1887
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001888 // Init priority must be standard.
1889 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001890 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001891 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001892 } else {
1893 return 0;
1894 }
1895
1896 return I;
1897 }
1898 return 0;
1899}
1900
Chris Lattnerdb973e62005-09-26 02:31:18 +00001901/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1902/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001903static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1904 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1905 std::vector<Function*> Result;
1906 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001907 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1908 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001909 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1910 }
1911 return Result;
1912}
1913
Chris Lattnerdb973e62005-09-26 02:31:18 +00001914/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1915/// specified array, returning the new global to use.
1916static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1917 const std::vector<Function*> &Ctors) {
1918 // If we made a change, reassemble the initializer list.
1919 std::vector<Constant*> CSVals;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001920 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001921 CSVals.push_back(0);
1922
1923 // Create the new init list.
1924 std::vector<Constant*> CAList;
1925 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001926 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001927 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001928 } else {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001929 const Type *FTy = FunctionType::get(Type::VoidTy,
1930 std::vector<const Type*>(), false);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001931 const PointerType *PFTy = PointerType::getUnqual(FTy);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001932 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001933 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001934 }
1935 CAList.push_back(ConstantStruct::get(CSVals));
1936 }
1937
1938 // Create the array initializer.
1939 const Type *StructTy =
1940 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1941 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1942 CAList);
1943
1944 // If we didn't change the number of elements, don't create a new GV.
1945 if (CA->getType() == GCL->getInitializer()->getType()) {
1946 GCL->setInitializer(CA);
1947 return GCL;
1948 }
1949
1950 // Create the new global and insert it next to the existing list.
1951 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001952 GCL->getLinkage(), CA, "",
1953 (Module *)NULL,
1954 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001955 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001956 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001957
1958 // Nuke the old list, replacing any uses with the new one.
1959 if (!GCL->use_empty()) {
1960 Constant *V = NGV;
1961 if (V->getType() != GCL->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001962 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001963 GCL->replaceAllUsesWith(V);
1964 }
1965 GCL->eraseFromParent();
1966
1967 if (Ctors.size())
1968 return NGV;
1969 else
1970 return 0;
1971}
Chris Lattner79c11012005-09-26 04:44:35 +00001972
1973
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001974static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00001975 Value *V) {
1976 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1977 Constant *R = ComputedValues[V];
1978 assert(R && "Reference to an uncomputed value!");
1979 return R;
1980}
1981
1982/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1983/// enough for us to understand. In particular, if it is a cast of something,
1984/// we punt. We basically just support direct accesses to globals and GEP's of
1985/// globals. This should be kept up to date with CommitValueTo.
1986static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner231308c2005-09-27 04:50:03 +00001987 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolabb46f522009-01-15 20:18:42 +00001988 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001989 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00001990 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00001991 }
Chris Lattner798b4d52005-09-26 06:52:44 +00001992 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1993 // Handle a constantexpr gep.
1994 if (CE->getOpcode() == Instruction::GetElementPtr &&
1995 isa<GlobalVariable>(CE->getOperand(0))) {
1996 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolabb46f522009-01-15 20:18:42 +00001997 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001998 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00001999 return GV->hasInitializer() &&
2000 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2001 }
Chris Lattner79c11012005-09-26 04:44:35 +00002002 return false;
2003}
2004
Chris Lattner798b4d52005-09-26 06:52:44 +00002005/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2006/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2007/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2008static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2009 ConstantExpr *Addr, unsigned OpNo) {
2010 // Base case of the recursion.
2011 if (OpNo == Addr->getNumOperands()) {
2012 assert(Val->getType() == Init->getType() && "Type mismatch!");
2013 return Val;
2014 }
2015
2016 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2017 std::vector<Constant*> Elts;
2018
2019 // Break up the constant into its elements.
2020 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002021 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2022 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002023 } else if (isa<ConstantAggregateZero>(Init)) {
2024 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2025 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2026 } else if (isa<UndefValue>(Init)) {
2027 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2028 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2029 } else {
2030 assert(0 && "This code is out of sync with "
2031 " ConstantFoldLoadThroughGEPConstantExpr");
2032 }
2033
2034 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002035 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2036 unsigned Idx = CU->getZExtValue();
2037 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner798b4d52005-09-26 06:52:44 +00002038 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2039
2040 // Return the modified struct.
Chris Lattnerf0a9aab2007-06-04 22:23:42 +00002041 return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002042 } else {
2043 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2044 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2045
2046 // Break up the array into elements.
2047 std::vector<Constant*> Elts;
2048 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002049 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2050 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002051 } else if (isa<ConstantAggregateZero>(Init)) {
2052 Constant *Elt = Constant::getNullValue(ATy->getElementType());
2053 Elts.assign(ATy->getNumElements(), Elt);
2054 } else if (isa<UndefValue>(Init)) {
2055 Constant *Elt = UndefValue::get(ATy->getElementType());
2056 Elts.assign(ATy->getNumElements(), Elt);
2057 } else {
2058 assert(0 && "This code is out of sync with "
2059 " ConstantFoldLoadThroughGEPConstantExpr");
2060 }
2061
Reid Spencerb83eb642006-10-20 07:07:24 +00002062 assert(CI->getZExtValue() < ATy->getNumElements());
2063 Elts[CI->getZExtValue()] =
2064 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00002065 return ConstantArray::get(ATy, Elts);
2066 }
2067}
2068
Chris Lattner79c11012005-09-26 04:44:35 +00002069/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2070/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2071static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002072 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2073 assert(GV->hasInitializer());
2074 GV->setInitializer(Val);
2075 return;
2076 }
2077
2078 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2079 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2080
2081 Constant *Init = GV->getInitializer();
2082 Init = EvaluateStoreInto(Init, Val, CE, 2);
2083 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00002084}
2085
Chris Lattner562a0552005-09-26 05:16:34 +00002086/// ComputeLoadResult - Return the value that would be computed by a load from
2087/// P after the stores reflected by 'memory' have been performed. If we can't
2088/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002089static Constant *ComputeLoadResult(Constant *P,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002090 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002091 // If this memory location has been recently stored, use the stored value: it
2092 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002093 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002094 if (I != Memory.end()) return I->second;
2095
2096 // Access it.
2097 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2098 if (GV->hasInitializer())
2099 return GV->getInitializer();
2100 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002101 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002102
2103 // Handle a constantexpr getelementptr.
2104 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2105 if (CE->getOpcode() == Instruction::GetElementPtr &&
2106 isa<GlobalVariable>(CE->getOperand(0))) {
2107 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2108 if (GV->hasInitializer())
2109 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2110 }
2111
2112 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002113}
2114
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002115/// EvaluateFunction - Evaluate a call to function F, returning true if
2116/// successful, false if we can't evaluate it. ActualArgs contains the formal
2117/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002118static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002119 const std::vector<Constant*> &ActualArgs,
2120 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002121 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002122 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002123 // Check to see if this function is already executing (recursion). If so,
2124 // bail out. TODO: we might want to accept limited recursion.
2125 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2126 return false;
2127
2128 CallStack.push_back(F);
2129
Chris Lattner79c11012005-09-26 04:44:35 +00002130 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002131 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002132
2133 // Initialize arguments to the incoming values specified.
2134 unsigned ArgNo = 0;
2135 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2136 ++AI, ++ArgNo)
2137 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002138
Chris Lattnercdf98be2005-09-26 04:57:38 +00002139 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2140 /// we can only evaluate any one basic block at most once. This set keeps
2141 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002142 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002143
Chris Lattner79c11012005-09-26 04:44:35 +00002144 // CurInst - The current instruction we're evaluating.
2145 BasicBlock::iterator CurInst = F->begin()->begin();
2146
2147 // This is the main evaluation loop.
2148 while (1) {
2149 Constant *InstResult = 0;
2150
2151 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002152 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002153 Constant *Ptr = getVal(Values, SI->getOperand(1));
2154 if (!isSimpleEnoughPointerToCommit(Ptr))
2155 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002156 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002157 Constant *Val = getVal(Values, SI->getOperand(0));
2158 MutatedMemory[Ptr] = Val;
2159 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2160 InstResult = ConstantExpr::get(BO->getOpcode(),
2161 getVal(Values, BO->getOperand(0)),
2162 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002163 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2164 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2165 getVal(Values, CI->getOperand(0)),
2166 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002167 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Chris Lattner9a989f02006-11-30 17:26:08 +00002168 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2169 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002170 CI->getType());
2171 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2172 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2173 getVal(Values, SI->getOperand(1)),
2174 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002175 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2176 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002177 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002178 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2179 i != e; ++i)
2180 GEPOps.push_back(getVal(Values, *i));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002181 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002182 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002183 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002184 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2185 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002186 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002187 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002188 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002189 const Type *Ty = AI->getType()->getElementType();
2190 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2191 GlobalValue::InternalLinkage,
2192 UndefValue::get(Ty),
2193 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002194 InstResult = AllocaTmps.back();
2195 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattner7cd580f2006-07-07 21:37:01 +00002196 // Cannot handle inline asm.
2197 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2198
Chris Lattnercd271422005-09-27 04:45:34 +00002199 // Resolve function pointers.
2200 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2201 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002202
Chris Lattnercd271422005-09-27 04:45:34 +00002203 std::vector<Constant*> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002204 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2205 i != e; ++i)
2206 Formals.push_back(getVal(Values, *i));
Chris Lattnercd271422005-09-27 04:45:34 +00002207
Reid Spencer5cbf9852007-01-30 20:08:39 +00002208 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002209 // If this is a function we can constant fold, do it.
Chris Lattner6c1f5652007-01-30 23:14:52 +00002210 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2211 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002212 InstResult = C;
2213 } else {
2214 return false;
2215 }
2216 } else {
2217 if (Callee->getFunctionType()->isVarArg())
2218 return false;
2219
2220 Constant *RetVal;
2221
2222 // Execute the call, if successful, use the return value.
2223 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2224 MutatedMemory, AllocaTmps))
2225 return false;
2226 InstResult = RetVal;
2227 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002228 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002229 BasicBlock *NewBB = 0;
2230 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2231 if (BI->isUnconditional()) {
2232 NewBB = BI->getSuccessor(0);
2233 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002234 ConstantInt *Cond =
2235 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002236 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002237
Reid Spencer579dca12007-01-12 04:24:46 +00002238 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002239 }
2240 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2241 ConstantInt *Val =
2242 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002243 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002244 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2245 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002246 if (RI->getNumOperands())
2247 RetVal = getVal(Values, RI->getOperand(0));
2248
2249 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002250 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002251 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002252 // invoke, unwind, unreachable.
2253 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002254 }
2255
2256 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002257 // executed the new block before. If so, we have a looping function,
2258 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002259 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002260 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002261
2262 // Okay, we have never been in this block before. Check to see if there
2263 // are any PHI nodes. If so, evaluate them with information about where
2264 // we came from.
2265 BasicBlock *OldBB = CurInst->getParent();
2266 CurInst = NewBB->begin();
2267 PHINode *PN;
2268 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2269 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2270
2271 // Do NOT increment CurInst. We know that the terminator had no value.
2272 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002273 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002274 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002275 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002276 }
2277
2278 if (!CurInst->use_empty())
2279 Values[CurInst] = InstResult;
2280
2281 // Advance program counter.
2282 ++CurInst;
2283 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002284}
2285
2286/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2287/// we can. Return true if we can, false otherwise.
2288static bool EvaluateStaticConstructor(Function *F) {
2289 /// MutatedMemory - For each store we execute, we update this map. Loads
2290 /// check this to get the most up-to-date value. If evaluation is successful,
2291 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002292 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002293
2294 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2295 /// to represent its body. This vector is needed so we can delete the
2296 /// temporary globals when we are done.
2297 std::vector<GlobalVariable*> AllocaTmps;
2298
2299 /// CallStack - This is used to detect recursion. In pathological situations
2300 /// we could hit exponential behavior, but at least there is nothing
2301 /// unbounded.
2302 std::vector<Function*> CallStack;
2303
2304 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002305 Constant *RetValDummy;
2306 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2307 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002308 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002309 // We succeeded at evaluation: commit the result.
Bill Wendling0a81aac2006-11-26 10:02:32 +00002310 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2311 << F->getName() << "' to " << MutatedMemory.size()
2312 << " stores.\n";
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002313 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002314 E = MutatedMemory.end(); I != E; ++I)
2315 CommitValueTo(I->second, I->first);
2316 }
Chris Lattner79c11012005-09-26 04:44:35 +00002317
Chris Lattnera22fdb02005-09-26 17:07:09 +00002318 // At this point, we are done interpreting. If we created any 'alloca'
2319 // temporaries, release them now.
2320 while (!AllocaTmps.empty()) {
2321 GlobalVariable *Tmp = AllocaTmps.back();
2322 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002323
Chris Lattnera22fdb02005-09-26 17:07:09 +00002324 // If there are still users of the alloca, the program is doing something
2325 // silly, e.g. storing the address of the alloca somewhere and using it
2326 // later. Since this is undefined, we'll just make it be null.
2327 if (!Tmp->use_empty())
2328 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2329 delete Tmp;
2330 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002331
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002332 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002333}
2334
Chris Lattnerdb973e62005-09-26 02:31:18 +00002335
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002336
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002337/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2338/// Return true if anything changed.
2339bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2340 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2341 bool MadeChange = false;
2342 if (Ctors.empty()) return false;
2343
2344 // Loop over global ctors, optimizing them when we can.
2345 for (unsigned i = 0; i != Ctors.size(); ++i) {
2346 Function *F = Ctors[i];
2347 // Found a null terminator in the middle of the list, prune off the rest of
2348 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002349 if (F == 0) {
2350 if (i != Ctors.size()-1) {
2351 Ctors.resize(i+1);
2352 MadeChange = true;
2353 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002354 break;
2355 }
2356
Chris Lattner79c11012005-09-26 04:44:35 +00002357 // We cannot simplify external ctor functions.
2358 if (F->empty()) continue;
2359
2360 // If we can evaluate the ctor at compile time, do.
2361 if (EvaluateStaticConstructor(F)) {
2362 Ctors.erase(Ctors.begin()+i);
2363 MadeChange = true;
2364 --i;
2365 ++NumCtorsEvaluated;
2366 continue;
2367 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002368 }
2369
2370 if (!MadeChange) return false;
2371
Chris Lattnerdb973e62005-09-26 02:31:18 +00002372 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002373 return true;
2374}
2375
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002376bool GlobalOpt::ResolveAliases(Module &M) {
2377 bool Changed = false;
2378
Duncan Sands177d84e2009-01-07 20:01:06 +00002379 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002380 I != E;) {
2381 Module::alias_iterator J = I++;
2382 // If the aliasee may change at link time, nothing can be done - bail out.
2383 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002384 continue;
2385
Duncan Sands4782b302009-02-15 09:56:08 +00002386 Constant *Aliasee = J->getAliasee();
2387 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002388 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002389 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2390
2391 // Make all users of the alias use the aliasee instead.
2392 if (!J->use_empty()) {
2393 J->replaceAllUsesWith(Aliasee);
2394 ++NumAliasesResolved;
2395 Changed = true;
2396 }
2397
2398 // If the aliasee has internal linkage, give it the name and linkage
2399 // of the alias, and delete the alias. This turns:
2400 // define internal ... @f(...)
2401 // @a = alias ... @f
2402 // into:
2403 // define ... @a(...)
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002404 if (!Target->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002405 continue;
2406
2407 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002408 if (J->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002409 continue;
2410
Duncan Sandsa37d1192009-02-15 11:54:49 +00002411 // Do not perform the transform if multiple aliases potentially target the
2412 // aliasee. This check also ensures that it is safe to replace the section
2413 // and other attributes of the aliasee with those of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002414 if (!hasOneUse)
2415 continue;
2416
Duncan Sandsa37d1192009-02-15 11:54:49 +00002417 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002418 Target->takeName(J);
2419 Target->setLinkage(J->getLinkage());
Duncan Sandsa37d1192009-02-15 11:54:49 +00002420 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sands4782b302009-02-15 09:56:08 +00002421
2422 // Delete the alias.
2423 M.getAliasList().erase(J);
2424 ++NumAliasesRemoved;
2425 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002426 }
2427
2428 return Changed;
2429}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002430
Chris Lattner7a90b682004-10-07 04:16:33 +00002431bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002432 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002433
2434 // Try to find the llvm.globalctors list.
2435 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002436
Chris Lattner7a90b682004-10-07 04:16:33 +00002437 bool LocalChange = true;
2438 while (LocalChange) {
2439 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002440
2441 // Delete functions that are trivially dead, ccc -> fastcc
2442 LocalChange |= OptimizeFunctions(M);
2443
2444 // Optimize global_ctors list.
2445 if (GlobalCtors)
2446 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2447
2448 // Optimize non-address-taken globals.
2449 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002450
2451 // Resolve aliases, when possible.
2452 LocalChange |= ResolveAliases(M);
2453 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002454 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002455
2456 // TODO: Move all global ctors functions to the end of the module for code
2457 // layout.
2458
Chris Lattner079236d2004-02-25 21:34:36 +00002459 return Changed;
2460}