blob: 2f9eb689185fce36b84209a0111ddb744b1002b1 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// 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.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "globalopt"
17#include "llvm/Transforms/IPO.h"
18#include "llvm/CallingConv.h"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Instructions.h"
22#include "llvm/IntrinsicInst.h"
23#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/Target/TargetData.h"
Duncan Sands551ec902008-02-18 17:32:13 +000028#include "llvm/Support/CallSite.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattner7bd79da2008-01-14 02:09:12 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner20846272008-04-26 07:40:11 +000032#include "llvm/Support/MathExtras.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000033#include "llvm/Support/raw_ostream.h"
Chris Lattner4cd08c22008-12-16 07:34:30 +000034#include "llvm/ADT/DenseMap.h"
Chris Lattnerbdf77462007-09-13 16:30:19 +000035#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/ADT/SmallVector.h"
37#include "llvm/ADT/Statistic.h"
Chris Lattner8a2d32e2008-12-17 05:28:49 +000038#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040using namespace llvm;
41
42STATISTIC(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 Sandsafa10bf2008-02-16 20:56:04 +000053STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sandse7f431f2009-02-15 09:56:08 +000054STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
55STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056
57namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000058 struct GlobalOpt : public ModulePass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060 }
61 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000062 GlobalOpt() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063
64 bool runOnModule(Module &M);
65
66 private:
67 GlobalVariable *FindGlobalCtors(Module &M);
68 bool OptimizeFunctions(Module &M);
69 bool OptimizeGlobalVars(Module &M);
Duncan Sands0c7b6332009-03-06 10:21:56 +000070 bool OptimizeGlobalAliases(Module &M);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
72 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
73 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074}
75
Dan Gohman089efff2008-05-13 00:00:25 +000076char GlobalOpt::ID = 0;
77static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
78
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
80
Dan Gohman089efff2008-05-13 00:00:25 +000081namespace {
82
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083/// GlobalStatus - As we analyze each global, keep track of some information
84/// about it. If we find out that the address of the global is taken, none of
85/// this info will be accurate.
Nick Lewycky492d06e2009-10-25 06:33:48 +000086struct GlobalStatus {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087 /// isLoaded - True if the global is ever loaded. If the global isn't ever
88 /// loaded it can be deleted.
89 bool isLoaded;
90
91 /// StoredType - Keep track of what stores to the global look like.
92 ///
93 enum StoredType {
94 /// NotStored - There is no store to this global. It can thus be marked
95 /// constant.
96 NotStored,
97
98 /// isInitializerStored - This global is stored to, but the only thing
99 /// stored is the constant it was initialized with. This is only tracked
100 /// for scalar globals.
101 isInitializerStored,
102
103 /// isStoredOnce - This global is stored to, but only its initializer and
104 /// one other value is ever stored to it. If this global isStoredOnce, we
105 /// track the value stored to it in StoredOnceValue below. This is only
106 /// tracked for scalar globals.
107 isStoredOnce,
108
109 /// isStored - This global is stored to by multiple values or something else
110 /// that we cannot track.
111 isStored
112 } StoredType;
113
114 /// StoredOnceValue - If only one value (besides the initializer constant) is
115 /// ever stored to this global, keep track of what value it is.
116 Value *StoredOnceValue;
117
118 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
119 /// null/false. When the first accessing function is noticed, it is recorded.
120 /// When a second different accessing function is noticed,
121 /// HasMultipleAccessingFunctions is set to true.
Gabor Greif0fbd0302010-04-01 08:21:08 +0000122 const Function *AccessingFunction;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 bool HasMultipleAccessingFunctions;
124
125 /// HasNonInstructionUser - Set to true if this global has a user that is not
126 /// an instruction (e.g. a constant expr or GV initializer).
127 bool HasNonInstructionUser;
128
129 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
130 bool HasPHIUser;
131
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
133 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattnercad76212008-01-14 01:32:52 +0000134 HasNonInstructionUser(false), HasPHIUser(false) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135};
136
Dan Gohman089efff2008-05-13 00:00:25 +0000137}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138
Jay Foade4914352009-06-09 21:37:11 +0000139// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
140// by constants itself. Note that constants cannot be cyclic, so this test is
141// pretty easy to implement recursively.
142//
Gabor Greif0fbd0302010-04-01 08:21:08 +0000143static bool SafeToDestroyConstant(const Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 if (isa<GlobalValue>(C)) return false;
145
Gabor Greif0fbd0302010-04-01 08:21:08 +0000146 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
147 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade4914352009-06-09 21:37:11 +0000148 if (!SafeToDestroyConstant(CU)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149 } else
150 return false;
151 return true;
152}
153
154
155/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
156/// structure. If the global has its address taken, return true to indicate we
157/// can't do anything with it.
158///
Gabor Greif0fbd0302010-04-01 08:21:08 +0000159static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
160 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
161 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
162 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 GS.HasNonInstructionUser = true;
164
165 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166
Gabor Greif0fbd0302010-04-01 08:21:08 +0000167 } else if (const Instruction *I = dyn_cast<Instruction>(*UI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greif0fbd0302010-04-01 08:21:08 +0000169 const Function *F = I->getParent()->getParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 if (GS.AccessingFunction == 0)
171 GS.AccessingFunction = F;
172 else if (GS.AccessingFunction != F)
173 GS.HasMultipleAccessingFunctions = true;
174 }
Gabor Greif0fbd0302010-04-01 08:21:08 +0000175 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 GS.isLoaded = true;
Chris Lattner75a2db82008-01-29 19:01:37 +0000177 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Gabor Greif0fbd0302010-04-01 08:21:08 +0000178 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 // Don't allow a store OF the address, only stores TO the address.
180 if (SI->getOperand(0) == V) return true;
181
Chris Lattner75a2db82008-01-29 19:01:37 +0000182 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
183
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 // If this is a direct store to the global (i.e., the global is a scalar
185 // value, not an aggregate), keep more specific information about
186 // stores.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000187 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif0fbd0302010-04-01 08:21:08 +0000188 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 Value *StoredVal = SI->getOperand(0);
190 if (StoredVal == GV->getInitializer()) {
191 if (GS.StoredType < GlobalStatus::isInitializerStored)
192 GS.StoredType = GlobalStatus::isInitializerStored;
193 } else if (isa<LoadInst>(StoredVal) &&
194 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 if (GS.StoredType < GlobalStatus::isInitializerStored)
196 GS.StoredType = GlobalStatus::isInitializerStored;
197 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
198 GS.StoredType = GlobalStatus::isStoredOnce;
199 GS.StoredOnceValue = StoredVal;
200 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
201 GS.StoredOnceValue == StoredVal) {
202 // noop.
203 } else {
204 GS.StoredType = GlobalStatus::isStored;
205 }
206 } else {
207 GS.StoredType = GlobalStatus::isStored;
208 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000209 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 } else if (isa<GetElementPtrInst>(I)) {
211 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 } else if (isa<SelectInst>(I)) {
213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greif0fbd0302010-04-01 08:21:08 +0000214 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 // PHI nodes we can check just like select or GEP instructions, but we
216 // have to be careful about infinite recursion.
Chris Lattner4cd08c22008-12-16 07:34:30 +0000217 if (PHIUsers.insert(PN)) // Not already visited.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 GS.HasPHIUser = true;
220 } else if (isa<CmpInst>(I)) {
Chris Lattnerb914b952009-03-08 03:37:35 +0000221 } else if (isa<MemTransferInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 if (I->getOperand(1) == V)
223 GS.StoredType = GlobalStatus::isStored;
224 if (I->getOperand(2) == V)
225 GS.isLoaded = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 } else if (isa<MemSetInst>(I)) {
227 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
228 GS.StoredType = GlobalStatus::isStored;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229 } else {
230 return true; // Any other non-load instruction might take address!
231 }
Gabor Greif0fbd0302010-04-01 08:21:08 +0000232 } else if (const Constant *C = dyn_cast<Constant>(*UI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 GS.HasNonInstructionUser = true;
234 // We might have a dead and dangling constant hanging off of here.
Jay Foade4914352009-06-09 21:37:11 +0000235 if (!SafeToDestroyConstant(C))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 return true;
237 } else {
238 GS.HasNonInstructionUser = true;
239 // Otherwise must be some other user.
240 return true;
241 }
242
243 return false;
244}
245
Chris Lattner6070c012009-11-06 04:27:31 +0000246static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
248 if (!CI) return 0;
249 unsigned IdxV = CI->getZExtValue();
250
251 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
252 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
253 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
254 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
255 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
256 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
257 } else if (isa<ConstantAggregateZero>(Agg)) {
258 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
259 if (IdxV < STy->getNumElements())
Owen Andersonaac28372009-07-31 20:28:14 +0000260 return Constant::getNullValue(STy->getElementType(IdxV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261 } else if (const SequentialType *STy =
262 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersonaac28372009-07-31 20:28:14 +0000263 return Constant::getNullValue(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 }
265 } else if (isa<UndefValue>(Agg)) {
266 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
267 if (IdxV < STy->getNumElements())
Owen Andersonb99ecca2009-07-30 23:03:37 +0000268 return UndefValue::get(STy->getElementType(IdxV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 } else if (const SequentialType *STy =
270 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersonb99ecca2009-07-30 23:03:37 +0000271 return UndefValue::get(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 }
273 }
274 return 0;
275}
276
277
278/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
279/// users of the global, cleaning up the obvious ones. This is largely just a
280/// quick scan over the use list to clean up the easy and obvious cruft. This
281/// returns true if it made a change.
Chris Lattner6070c012009-11-06 04:27:31 +0000282static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 bool Changed = false;
284 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
285 User *U = *UI++;
286
287 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
288 if (Init) {
289 // Replace the load with the initializer.
290 LI->replaceAllUsesWith(Init);
291 LI->eraseFromParent();
292 Changed = true;
293 }
294 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
295 // Store must be unreachable or storing Init into the global.
296 SI->eraseFromParent();
297 Changed = true;
298 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
299 if (CE->getOpcode() == Instruction::GetElementPtr) {
300 Constant *SubInit = 0;
301 if (Init)
Dan Gohmanf49f7b02009-10-05 16:36:26 +0000302 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner6070c012009-11-06 04:27:31 +0000303 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands10343d92010-02-16 11:11:14 +0000305 CE->getType()->isPointerTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner6070c012009-11-06 04:27:31 +0000307 Changed |= CleanupConstantGlobalUsers(CE, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 }
309
310 if (CE->use_empty()) {
311 CE->destroyConstant();
312 Changed = true;
313 }
314 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7ebafca2007-11-09 17:33:02 +0000315 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
316 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
317 // and will invalidate our notion of what Init is.
Chris Lattner2dd9c042007-11-13 21:46:23 +0000318 Constant *SubInit = 0;
Chris Lattner7ebafca2007-11-09 17:33:02 +0000319 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
320 ConstantExpr *CE =
Chris Lattner6070c012009-11-06 04:27:31 +0000321 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7ebafca2007-11-09 17:33:02 +0000322 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanf49f7b02009-10-05 16:36:26 +0000323 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7ebafca2007-11-09 17:33:02 +0000324 }
Chris Lattner6070c012009-11-06 04:27:31 +0000325 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326
327 if (GEP->use_empty()) {
328 GEP->eraseFromParent();
329 Changed = true;
330 }
331 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
332 if (MI->getRawDest() == V) {
333 MI->eraseFromParent();
334 Changed = true;
335 }
336
337 } else if (Constant *C = dyn_cast<Constant>(U)) {
338 // If we have a chain of dead constantexprs or other things dangling from
339 // us, and if they are all dead, nuke them without remorse.
Jay Foade4914352009-06-09 21:37:11 +0000340 if (SafeToDestroyConstant(C)) {
Devang Patel3b6b19e2009-03-06 01:37:41 +0000341 C->destroyConstant();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 // This could have invalidated UI, start over from scratch.
Chris Lattner6070c012009-11-06 04:27:31 +0000343 CleanupConstantGlobalUsers(V, Init);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 return true;
345 }
346 }
347 }
348 return Changed;
349}
350
Chris Lattner7bd79da2008-01-14 02:09:12 +0000351/// isSafeSROAElementUse - Return true if the specified instruction is a safe
352/// user of a derived expression from a global that we want to SROA.
353static bool isSafeSROAElementUse(Value *V) {
354 // We might have a dead and dangling constant hanging off of here.
355 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade4914352009-06-09 21:37:11 +0000356 return SafeToDestroyConstant(C);
Chris Lattner7329c662008-01-14 01:31:05 +0000357
Chris Lattner7bd79da2008-01-14 02:09:12 +0000358 Instruction *I = dyn_cast<Instruction>(V);
359 if (!I) return false;
360
361 // Loads are ok.
362 if (isa<LoadInst>(I)) return true;
363
364 // Stores *to* the pointer are ok.
365 if (StoreInst *SI = dyn_cast<StoreInst>(I))
366 return SI->getOperand(0) != V;
367
368 // Otherwise, it must be a GEP.
369 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
370 if (GEPI == 0) return false;
371
372 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
373 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
374 return false;
375
376 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
377 I != E; ++I)
378 if (!isSafeSROAElementUse(*I))
379 return false;
Chris Lattner7329c662008-01-14 01:31:05 +0000380 return true;
381}
382
Chris Lattner7bd79da2008-01-14 02:09:12 +0000383
384/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
385/// Look at it and its uses and decide whether it is safe to SROA this global.
386///
387static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
388 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
389 if (!isa<GetElementPtrInst>(U) &&
390 (!isa<ConstantExpr>(U) ||
391 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
392 return false;
393
394 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
395 // don't like < 3 operand CE's, and we don't like non-constant integer
396 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
397 // value of C.
398 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
399 !cast<Constant>(U->getOperand(1))->isNullValue() ||
400 !isa<ConstantInt>(U->getOperand(2)))
401 return false;
402
403 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
404 ++GEPI; // Skip over the pointer index.
405
406 // If this is a use of an array allocation, do a bit more checking for sanity.
407 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
408 uint64_t NumElements = AT->getNumElements();
409 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
410
411 // Check to make sure that index falls within the array. If not,
412 // something funny is going on, so we won't do the optimization.
413 //
414 if (Idx->getZExtValue() >= NumElements)
415 return false;
416
417 // We cannot scalar repl this level of the array unless any array
418 // sub-indices are in-range constants. In particular, consider:
419 // A[0][i]. We cannot know that the user isn't doing invalid things like
420 // allowing i to index an out-of-range subscript that accesses A[1].
421 //
422 // Scalar replacing *just* the outer index of the array is probably not
423 // going to be a win anyway, so just give up.
424 for (++GEPI; // Skip array index.
Dan Gohmanf0080a12009-08-18 14:58:19 +0000425 GEPI != E;
Chris Lattner7bd79da2008-01-14 02:09:12 +0000426 ++GEPI) {
427 uint64_t NumElements;
428 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
429 NumElements = SubArrayTy->getNumElements();
Dan Gohmanf0080a12009-08-18 14:58:19 +0000430 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
431 NumElements = SubVectorTy->getNumElements();
432 else {
Duncan Sands10343d92010-02-16 11:11:14 +0000433 assert((*GEPI)->isStructTy() &&
Dan Gohmanf0080a12009-08-18 14:58:19 +0000434 "Indexed GEP type is not array, vector, or struct!");
435 continue;
436 }
Chris Lattner7bd79da2008-01-14 02:09:12 +0000437
438 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
439 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
440 return false;
441 }
442 }
443
444 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
445 if (!isSafeSROAElementUse(*I))
446 return false;
447 return true;
448}
449
450/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
451/// is safe for us to perform this transformation.
452///
453static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
454 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
455 UI != E; ++UI) {
456 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
457 return false;
458 }
459 return true;
460}
461
462
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000463/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
464/// variable. This opens the door for other optimizations by exposing the
465/// behavior of the program in a more fine-grained way. We have determined that
466/// this transformation is safe already. We return the first global variable we
467/// insert so that the caller can reprocess it.
Chris Lattner6070c012009-11-06 04:27:31 +0000468static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner7329c662008-01-14 01:31:05 +0000469 // Make sure this global only has simple uses that we can SRA.
Chris Lattner7bd79da2008-01-14 02:09:12 +0000470 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner7329c662008-01-14 01:31:05 +0000471 return 0;
472
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000473 assert(GV->hasLocalLinkage() && !GV->isConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 Constant *Init = GV->getInitializer();
475 const Type *Ty = Init->getType();
476
477 std::vector<GlobalVariable*> NewGlobals;
478 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
479
Chris Lattner20846272008-04-26 07:40:11 +0000480 // Get the alignment of the global, either explicit or target-specific.
481 unsigned StartAlignment = GV->getAlignment();
482 if (StartAlignment == 0)
483 StartAlignment = TD.getABITypeAlignment(GV->getType());
484
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
486 NewGlobals.reserve(STy->getNumElements());
Chris Lattner20846272008-04-26 07:40:11 +0000487 const StructLayout &Layout = *TD.getStructLayout(STy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
489 Constant *In = getAggregateConstantElement(Init,
Chris Lattner6070c012009-11-06 04:27:31 +0000490 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000491 assert(In && "Couldn't get element of initializer?");
Chris Lattner6070c012009-11-06 04:27:31 +0000492 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000493 GlobalVariable::InternalLinkage,
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000494 In, GV->getName()+"."+Twine(i),
Matthijs Kooijman36693bb2008-07-17 11:59:53 +0000495 GV->isThreadLocal(),
Owen Andersone0f136d2009-07-08 01:26:06 +0000496 GV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 Globals.insert(GV, NGV);
498 NewGlobals.push_back(NGV);
Chris Lattner20846272008-04-26 07:40:11 +0000499
500 // Calculate the known alignment of the field. If the original aggregate
501 // had 256 byte alignment for example, something might depend on that:
502 // propagate info to each field.
503 uint64_t FieldOffset = Layout.getElementOffset(i);
504 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
505 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
506 NGV->setAlignment(NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507 }
508 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
509 unsigned NumElements = 0;
510 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
511 NumElements = ATy->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512 else
Chris Lattner20846272008-04-26 07:40:11 +0000513 NumElements = cast<VectorType>(STy)->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514
515 if (NumElements > 16 && GV->hasNUsesOrMore(16))
516 return 0; // It's not worth it.
517 NewGlobals.reserve(NumElements);
Chris Lattner20846272008-04-26 07:40:11 +0000518
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000519 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner20846272008-04-26 07:40:11 +0000520 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521 for (unsigned i = 0, e = NumElements; i != e; ++i) {
522 Constant *In = getAggregateConstantElement(Init,
Chris Lattner6070c012009-11-06 04:27:31 +0000523 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524 assert(In && "Couldn't get element of initializer?");
525
Chris Lattner6070c012009-11-06 04:27:31 +0000526 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 GlobalVariable::InternalLinkage,
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000528 In, GV->getName()+"."+Twine(i),
Matthijs Kooijman36693bb2008-07-17 11:59:53 +0000529 GV->isThreadLocal(),
Owen Andersone17fc1d2009-07-08 19:03:57 +0000530 GV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531 Globals.insert(GV, NGV);
532 NewGlobals.push_back(NGV);
Chris Lattner20846272008-04-26 07:40:11 +0000533
534 // Calculate the known alignment of the field. If the original aggregate
535 // had 256 byte alignment for example, something might depend on that:
536 // propagate info to each field.
537 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
538 if (NewAlign > EltAlign)
539 NGV->setAlignment(NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540 }
541 }
542
543 if (NewGlobals.empty())
544 return 0;
Chris Lattner7d91dc82010-02-26 23:35:25 +0000545
David Greenef26def42010-01-05 01:28:05 +0000546 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547
Chris Lattner6070c012009-11-06 04:27:31 +0000548 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549
550 // Loop over all of the uses of the global, replacing the constantexpr geps,
551 // with smaller constantexpr geps or direct references.
552 while (!GV->use_empty()) {
553 User *GEP = GV->use_back();
554 assert(((isa<ConstantExpr>(GEP) &&
555 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
556 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
557
558 // Ignore the 1th operand, which has to be zero or else the program is quite
559 // broken (undefined). Get the 2nd operand, which is the structure or array
560 // index.
561 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
562 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
563
564 Value *NewPtr = NewGlobals[Val];
565
566 // Form a shorter GEP if needed.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000567 if (GEP->getNumOperands() > 3) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
569 SmallVector<Constant*, 8> Idxs;
570 Idxs.push_back(NullInt);
571 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
572 Idxs.push_back(CE->getOperand(i));
Owen Anderson02b48c32009-07-29 18:55:55 +0000573 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000574 &Idxs[0], Idxs.size());
575 } else {
576 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
577 SmallVector<Value*, 8> Idxs;
578 Idxs.push_back(NullInt);
579 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
580 Idxs.push_back(GEPI->getOperand(i));
Gabor Greifd6da1d02008-04-06 20:25:17 +0000581 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000582 GEPI->getName()+"."+Twine(Val),GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000584 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 GEP->replaceAllUsesWith(NewPtr);
586
587 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
588 GEPI->eraseFromParent();
589 else
590 cast<ConstantExpr>(GEP)->destroyConstant();
591 }
592
593 // Delete the old global, now that it is dead.
594 Globals.erase(GV);
595 ++NumSRA;
596
597 // Loop over the new globals array deleting any globals that are obviously
598 // dead. This can arise due to scalarization of a structure or an array that
599 // has elements that are dead.
600 unsigned FirstGlobal = 0;
601 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
602 if (NewGlobals[i]->use_empty()) {
603 Globals.erase(NewGlobals[i]);
604 if (FirstGlobal == i) ++FirstGlobal;
605 }
606
607 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
608}
609
610/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattnerbdf77462007-09-13 16:30:19 +0000611/// value will trap if the value is dynamically null. PHIs keeps track of any
612/// phi nodes we've seen to avoid reprocessing them.
613static bool AllUsesOfValueWillTrapIfNull(Value *V,
614 SmallPtrSet<PHINode*, 8> &PHIs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
616 if (isa<LoadInst>(*UI)) {
617 // Will trap.
618 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
619 if (SI->getOperand(0) == V) {
620 //cerr << "NONTRAPPING USE: " << **UI;
621 return false; // Storing the value.
622 }
623 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
Gabor Greif85c4cc22010-03-20 21:00:25 +0000624 if (CI->getCalledValue() != V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 //cerr << "NONTRAPPING USE: " << **UI;
626 return false; // Not calling the ptr
627 }
628 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
Gabor Greif85c4cc22010-03-20 21:00:25 +0000629 if (II->getCalledValue() != V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 //cerr << "NONTRAPPING USE: " << **UI;
631 return false; // Not calling the ptr
632 }
Chris Lattnerbdf77462007-09-13 16:30:19 +0000633 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
634 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattnerbdf77462007-09-13 16:30:19 +0000636 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
637 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
638 // If we've already seen this phi node, ignore it, it has already been
639 // checked.
Jakob Stoklund Olesena734c6c2010-01-29 23:54:14 +0000640 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
641 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 } else if (isa<ICmpInst>(*UI) &&
643 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckyadcffdd2010-02-25 06:39:10 +0000644 // Ignore icmp X, null
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000645 } else {
646 //cerr << "NONTRAPPING USE: " << **UI;
647 return false;
648 }
649 return true;
650}
651
652/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
653/// from GV will trap if the loaded value is null. Note that this also permits
654/// comparisons of the loaded value against null, as a special case.
655static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
656 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
657 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattnerbdf77462007-09-13 16:30:19 +0000658 SmallPtrSet<PHINode*, 8> PHIs;
659 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660 return false;
661 } else if (isa<StoreInst>(*UI)) {
662 // Ignore stores to the global.
663 } else {
664 // We don't know or understand this user, bail out.
665 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
666 return false;
667 }
668
669 return true;
670}
671
Chris Lattner6070c012009-11-06 04:27:31 +0000672static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 bool Changed = false;
674 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
675 Instruction *I = cast<Instruction>(*UI++);
676 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
677 LI->setOperand(0, NewV);
678 Changed = true;
679 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
680 if (SI->getOperand(1) == V) {
681 SI->setOperand(1, NewV);
682 Changed = true;
683 }
684 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greif3be3ab72010-04-06 18:45:08 +0000685 CallSite CS(I);
686 if (CS.getCalledValue() == V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687 // Calling through the pointer! Turn into a direct call, but be careful
688 // that the pointer is not also being passed as an argument.
Gabor Greif3be3ab72010-04-06 18:45:08 +0000689 CS.setCalledFunction(NewV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 Changed = true;
691 bool PassedAsArg = false;
Gabor Greif3be3ab72010-04-06 18:45:08 +0000692 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
693 if (CS.getArgument(i) == V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 PassedAsArg = true;
Gabor Greif3be3ab72010-04-06 18:45:08 +0000695 CS.setArgument(i, NewV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696 }
697
698 if (PassedAsArg) {
699 // Being passed as an argument also. Be careful to not invalidate UI!
700 UI = V->use_begin();
701 }
702 }
703 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
704 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson02b48c32009-07-29 18:55:55 +0000705 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner6070c012009-11-06 04:27:31 +0000706 NewV, CI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 if (CI->use_empty()) {
708 Changed = true;
709 CI->eraseFromParent();
710 }
711 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
712 // Should handle GEP here.
713 SmallVector<Constant*, 8> Idxs;
714 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif20f03f52008-05-29 01:59:18 +0000715 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
716 i != e; ++i)
717 if (Constant *C = dyn_cast<Constant>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 Idxs.push_back(C);
719 else
720 break;
721 if (Idxs.size() == GEPI->getNumOperands()-1)
722 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Anderson02b48c32009-07-29 18:55:55 +0000723 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Chris Lattner6070c012009-11-06 04:27:31 +0000724 Idxs.size()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 if (GEPI->use_empty()) {
726 Changed = true;
727 GEPI->eraseFromParent();
728 }
729 }
730 }
731
732 return Changed;
733}
734
735
736/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
737/// value stored into it. If there are uses of the loaded value that would trap
738/// if the loaded value is dynamically null, then we know that they cannot be
739/// reachable with a null optimize away the load.
Chris Lattner6070c012009-11-06 04:27:31 +0000740static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 bool Changed = false;
742
Chris Lattner9806cc12009-01-14 00:12:58 +0000743 // Keep track of whether we are able to remove all the uses of the global
744 // other than the store that defines it.
745 bool AllNonStoreUsesGone = true;
746
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner9806cc12009-01-14 00:12:58 +0000748 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
749 User *GlobalUser = *GUI++;
750 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner6070c012009-11-06 04:27:31 +0000751 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner9806cc12009-01-14 00:12:58 +0000752 // If we were able to delete all uses of the loads
753 if (LI->use_empty()) {
754 LI->eraseFromParent();
755 Changed = true;
756 } else {
757 AllNonStoreUsesGone = false;
758 }
759 } else if (isa<StoreInst>(GlobalUser)) {
760 // Ignore the store that stores "LV" to the global.
761 assert(GlobalUser->getOperand(1) == GV &&
762 "Must be storing *to* the global");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763 } else {
Chris Lattner9806cc12009-01-14 00:12:58 +0000764 AllNonStoreUsesGone = false;
765
766 // If we get here we could have other crazy uses that are transitively
767 // loaded.
768 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
769 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 }
Chris Lattner9806cc12009-01-14 00:12:58 +0000771 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772
773 if (Changed) {
David Greenef26def42010-01-05 01:28:05 +0000774 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 ++NumGlobUses;
776 }
777
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000778 // If we nuked all of the loads, then none of the stores are needed either,
779 // nor is the global.
Chris Lattner9806cc12009-01-14 00:12:58 +0000780 if (AllNonStoreUsesGone) {
David Greenef26def42010-01-05 01:28:05 +0000781 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner6070c012009-11-06 04:27:31 +0000782 CleanupConstantGlobalUsers(GV, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783 if (GV->use_empty()) {
784 GV->eraseFromParent();
785 ++NumDeleted;
786 }
787 Changed = true;
788 }
789 return Changed;
790}
791
792/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
793/// instructions that are foldable.
Chris Lattner6070c012009-11-06 04:27:31 +0000794static void ConstantPropUsersOf(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
796 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chris Lattner6070c012009-11-06 04:27:31 +0000797 if (Constant *NewC = ConstantFoldInstruction(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000798 I->replaceAllUsesWith(NewC);
799
800 // Advance UI to the next non-I use to avoid invalidating it!
801 // Instructions could multiply use V.
802 while (UI != E && *UI == I)
803 ++UI;
804 I->eraseFromParent();
805 }
806}
807
808/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
809/// variable, and transforms the program as if it always contained the result of
810/// the specified malloc. Because it is always the result of the specified
811/// malloc, there is no reason to actually DO the malloc. Instead, turn the
812/// malloc into a global, and any loads of GV as uses of the new global.
813static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez48c3c542009-09-18 22:35:49 +0000814 CallInst *CI,
Victor Hernandez955449e2009-11-07 00:16:28 +0000815 const Type *AllocTy,
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +0000816 ConstantInt *NElements,
Victor Hernandez48c3c542009-09-18 22:35:49 +0000817 TargetData* TD) {
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +0000818 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Victor Hernandez48c3c542009-09-18 22:35:49 +0000819
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +0000820 const Type *GlobalType;
821 if (NElements->getZExtValue() == 1)
822 GlobalType = AllocTy;
823 else
824 // If we have an array allocation, the global variable is of an array.
825 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez48c3c542009-09-18 22:35:49 +0000826
827 // Create the new global variable. The contents of the malloc'd memory is
828 // undefined, so initialize with an undef value.
Victor Hernandez48c3c542009-09-18 22:35:49 +0000829 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattner57c75f82010-02-26 23:42:13 +0000830 GlobalType, false,
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +0000831 GlobalValue::InternalLinkage,
Chris Lattner57c75f82010-02-26 23:42:13 +0000832 UndefValue::get(GlobalType),
Victor Hernandez48c3c542009-09-18 22:35:49 +0000833 GV->getName()+".body",
834 GV,
835 GV->isThreadLocal());
836
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +0000837 // If there are bitcast users of the malloc (which is typical, usually we have
838 // a malloc + bitcast) then replace them with uses of the new global. Update
839 // other users to use the global as well.
840 BitCastInst *TheBC = 0;
841 while (!CI->use_empty()) {
842 Instruction *User = cast<Instruction>(CI->use_back());
843 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
844 if (BCI->getType() == NewGV->getType()) {
845 BCI->replaceAllUsesWith(NewGV);
846 BCI->eraseFromParent();
847 } else {
848 BCI->setOperand(0, NewGV);
849 }
850 } else {
851 if (TheBC == 0)
852 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
853 User->replaceUsesOfWith(CI, TheBC);
854 }
855 }
856
Victor Hernandez48c3c542009-09-18 22:35:49 +0000857 Constant *RepValue = NewGV;
858 if (NewGV->getType() != GV->getType()->getElementType())
859 RepValue = ConstantExpr::getBitCast(RepValue,
860 GV->getType()->getElementType());
861
862 // If there is a comparison against null, we will insert a global bool to
863 // keep track of whether the global was initialized yet or not.
864 GlobalVariable *InitBool =
Chris Lattner6070c012009-11-06 04:27:31 +0000865 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez48c3c542009-09-18 22:35:49 +0000866 GlobalValue::InternalLinkage,
Chris Lattner6070c012009-11-06 04:27:31 +0000867 ConstantInt::getFalse(GV->getContext()),
868 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez48c3c542009-09-18 22:35:49 +0000869 bool InitBoolUsed = false;
870
871 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +0000872 while (!GV->use_empty()) {
873 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez48c3c542009-09-18 22:35:49 +0000874 // The global is initialized when the store to it occurs.
Chris Lattner6070c012009-11-06 04:27:31 +0000875 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez48c3c542009-09-18 22:35:49 +0000876 SI->eraseFromParent();
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +0000877 continue;
Victor Hernandez48c3c542009-09-18 22:35:49 +0000878 }
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +0000879
880 LoadInst *LI = cast<LoadInst>(GV->use_back());
881 while (!LI->use_empty()) {
882 Use &LoadUse = LI->use_begin().getUse();
883 if (!isa<ICmpInst>(LoadUse.getUser())) {
884 LoadUse = RepValue;
885 continue;
886 }
887
888 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
889 // Replace the cmp X, 0 with a use of the bool value.
890 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
891 InitBoolUsed = true;
892 switch (ICI->getPredicate()) {
893 default: llvm_unreachable("Unknown ICmp Predicate!");
894 case ICmpInst::ICMP_ULT:
895 case ICmpInst::ICMP_SLT: // X < null -> always false
896 LV = ConstantInt::getFalse(GV->getContext());
897 break;
898 case ICmpInst::ICMP_ULE:
899 case ICmpInst::ICMP_SLE:
900 case ICmpInst::ICMP_EQ:
901 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
902 break;
903 case ICmpInst::ICMP_NE:
904 case ICmpInst::ICMP_UGE:
905 case ICmpInst::ICMP_SGE:
906 case ICmpInst::ICMP_UGT:
907 case ICmpInst::ICMP_SGT:
908 break; // no change.
909 }
910 ICI->replaceAllUsesWith(LV);
911 ICI->eraseFromParent();
912 }
913 LI->eraseFromParent();
914 }
Victor Hernandez48c3c542009-09-18 22:35:49 +0000915
916 // If the initialization boolean was used, insert it, otherwise delete it.
917 if (!InitBoolUsed) {
918 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +0000919 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez48c3c542009-09-18 22:35:49 +0000920 delete InitBool;
921 } else
922 GV->getParent()->getGlobalList().insert(GV, InitBool);
923
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +0000924 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez48c3c542009-09-18 22:35:49 +0000925 GV->eraseFromParent();
Victor Hernandez48c3c542009-09-18 22:35:49 +0000926 CI->eraseFromParent();
927
928 // To further other optimizations, loop over all users of NewGV and try to
929 // constant prop them. This will promote GEP instructions with constant
930 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner6070c012009-11-06 04:27:31 +0000931 ConstantPropUsersOf(NewGV);
Victor Hernandez48c3c542009-09-18 22:35:49 +0000932 if (RepValue != NewGV)
Chris Lattner6070c012009-11-06 04:27:31 +0000933 ConstantPropUsersOf(RepValue);
Victor Hernandez48c3c542009-09-18 22:35:49 +0000934
935 return NewGV;
936}
937
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
939/// to make sure that there are no complex uses of V. We permit simple things
940/// like dereferencing the pointer, but not storing through the address, unless
941/// it is to the specified global.
Gabor Greif2dedb5f2010-04-06 18:58:22 +0000942static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
943 const GlobalVariable *GV,
944 SmallPtrSet<const PHINode*, 8> &PHIs) {
945 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
946 UI != E;++UI){
947 const Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner183b0cf2008-12-15 21:08:54 +0000948
949 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
950 continue; // Fine, ignore.
951 }
952
Gabor Greif2dedb5f2010-04-06 18:58:22 +0000953 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
955 return false; // Storing the pointer itself... bad.
Chris Lattner183b0cf2008-12-15 21:08:54 +0000956 continue; // Otherwise, storing through it, or storing into GV... fine.
957 }
958
959 if (isa<GetElementPtrInst>(Inst)) {
960 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961 return false;
Chris Lattner183b0cf2008-12-15 21:08:54 +0000962 continue;
963 }
964
Gabor Greif2dedb5f2010-04-06 18:58:22 +0000965 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnere7606f42007-09-13 16:37:20 +0000966 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
967 // cycles.
968 if (PHIs.insert(PN))
Chris Lattner4bde3c42007-09-14 03:41:21 +0000969 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
970 return false;
Chris Lattner183b0cf2008-12-15 21:08:54 +0000971 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 }
Chris Lattner183b0cf2008-12-15 21:08:54 +0000973
Gabor Greif2dedb5f2010-04-06 18:58:22 +0000974 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner183b0cf2008-12-15 21:08:54 +0000975 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
976 return false;
977 continue;
978 }
979
980 return false;
981 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 return true;
983}
984
985/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
986/// somewhere. Transform all uses of the allocation into loads from the
987/// global and uses of the resultant pointer. Further, delete the store into
988/// GV. This assumes that these value pass the
989/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
990static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
991 GlobalVariable *GV) {
992 while (!Alloc->use_empty()) {
Chris Lattner20eef0f2007-09-13 18:00:31 +0000993 Instruction *U = cast<Instruction>(*Alloc->use_begin());
994 Instruction *InsertPt = U;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
996 // If this is the store of the allocation into the global, remove it.
997 if (SI->getOperand(1) == GV) {
998 SI->eraseFromParent();
999 continue;
1000 }
Chris Lattner20eef0f2007-09-13 18:00:31 +00001001 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1002 // Insert the load in the corresponding predecessor, not right before the
1003 // PHI.
Gabor Greif261734d2009-01-23 19:40:15 +00001004 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner27ef89e2008-12-15 21:44:34 +00001005 } else if (isa<BitCastInst>(U)) {
1006 // Must be bitcast between the malloc and store to initialize the global.
1007 ReplaceUsesOfMallocWithGlobal(U, GV);
1008 U->eraseFromParent();
1009 continue;
1010 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1011 // If this is a "GEP bitcast" and the user is a store to the global, then
1012 // just process it as a bitcast.
1013 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1014 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1015 if (SI->getOperand(1) == GV) {
1016 // Must be bitcast GEP between the malloc and store to initialize
1017 // the global.
1018 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1019 GEPI->eraseFromParent();
1020 continue;
1021 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022 }
Chris Lattner27ef89e2008-12-15 21:44:34 +00001023
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 // Insert a load from the global, and use it instead of the malloc.
Chris Lattner20eef0f2007-09-13 18:00:31 +00001025 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001026 U->replaceUsesOfWith(Alloc, NL);
1027 }
1028}
1029
Chris Lattner7f252db2008-12-16 21:24:51 +00001030/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1031/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1032/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greif0fbd0302010-04-01 08:21:08 +00001033static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1034 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1035 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner7f252db2008-12-16 21:24:51 +00001036 // We permit two users of the load: setcc comparing against the null
1037 // pointer, and a getelementptr of a specific form.
Gabor Greif0fbd0302010-04-01 08:21:08 +00001038 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1039 const Instruction *User = cast<Instruction>(*UI);
Chris Lattner7f252db2008-12-16 21:24:51 +00001040
1041 // Comparison against null is ok.
Gabor Greif0fbd0302010-04-01 08:21:08 +00001042 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner7f252db2008-12-16 21:24:51 +00001043 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1044 return false;
1045 continue;
1046 }
1047
1048 // getelementptr is also ok, but only a simple form.
Gabor Greif0fbd0302010-04-01 08:21:08 +00001049 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner7f252db2008-12-16 21:24:51 +00001050 // Must index into the array and into the struct.
1051 if (GEPI->getNumOperands() < 3)
1052 return false;
1053
1054 // Otherwise the GEP is ok.
1055 continue;
1056 }
1057
Gabor Greif0fbd0302010-04-01 08:21:08 +00001058 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Chengb00d9282009-06-02 00:56:07 +00001059 if (!LoadUsingPHIsPerLoad.insert(PN))
1060 // This means some phi nodes are dependent on each other.
1061 // Avoid infinite looping!
1062 return false;
1063 if (!LoadUsingPHIs.insert(PN))
1064 // If we have already analyzed this PHI, then it is safe.
Chris Lattner7f252db2008-12-16 21:24:51 +00001065 continue;
1066
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001067 // Make sure all uses of the PHI are simple enough to transform.
Evan Chengb00d9282009-06-02 00:56:07 +00001068 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1069 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner7f252db2008-12-16 21:24:51 +00001070 return false;
1071
1072 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073 }
Chris Lattner7f252db2008-12-16 21:24:51 +00001074
1075 // Otherwise we don't know what this is, not ok.
1076 return false;
1077 }
1078
1079 return true;
1080}
1081
1082
1083/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1084/// GV are simple enough to perform HeapSRA, return true.
Gabor Greif0fbd0302010-04-01 08:21:08 +00001085static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez48c3c542009-09-18 22:35:49 +00001086 Instruction *StoredVal) {
Gabor Greif0fbd0302010-04-01 08:21:08 +00001087 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1088 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1089 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
Chris Lattner7f252db2008-12-16 21:24:51 +00001090 ++UI)
Gabor Greif0fbd0302010-04-01 08:21:08 +00001091 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Chengb00d9282009-06-02 00:56:07 +00001092 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1093 LoadUsingPHIsPerLoad))
Chris Lattner7f252db2008-12-16 21:24:51 +00001094 return false;
Evan Chengb00d9282009-06-02 00:56:07 +00001095 LoadUsingPHIsPerLoad.clear();
1096 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001097
1098 // If we reach here, we know that all uses of the loads and transitive uses
1099 // (through PHI nodes) are simple enough to transform. However, we don't know
1100 // that all inputs the to the PHI nodes are in the same equivalence sets.
1101 // Check to verify that all operands of the PHIs are either PHIS that can be
1102 // transformed, loads from GV, or MI itself.
Gabor Greif0fbd0302010-04-01 08:21:08 +00001103 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin(),
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001104 E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greif0fbd0302010-04-01 08:21:08 +00001105 const PHINode *PN = *I;
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001106 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1107 Value *InVal = PN->getIncomingValue(op);
1108
1109 // PHI of the stored value itself is ok.
Victor Hernandez48c3c542009-09-18 22:35:49 +00001110 if (InVal == StoredVal) continue;
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001111
Gabor Greif0fbd0302010-04-01 08:21:08 +00001112 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001113 // One of the PHIs in our set is (optimistically) ok.
1114 if (LoadUsingPHIs.count(InPN))
1115 continue;
1116 return false;
1117 }
1118
1119 // Load from GV is ok.
Gabor Greif0fbd0302010-04-01 08:21:08 +00001120 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001121 if (LI->getOperand(0) == GV)
1122 continue;
1123
1124 // UNDEF? NULL?
1125
1126 // Anything else is rejected.
1127 return false;
1128 }
1129 }
1130
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 return true;
1132}
1133
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001134static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1135 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner6070c012009-11-06 04:27:31 +00001136 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001137 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1138
1139 if (FieldNo >= FieldVals.size())
1140 FieldVals.resize(FieldNo+1);
1141
1142 // If we already have this value, just reuse the previously scalarized
1143 // version.
1144 if (Value *FieldVal = FieldVals[FieldNo])
1145 return FieldVal;
1146
1147 // Depending on what instruction this is, we have several cases.
1148 Value *Result;
1149 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1150 // This is a scalarized version of the load from the global. Just create
1151 // a new Load of the scalarized global.
1152 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1153 InsertedScalarizedValues,
Chris Lattner6070c012009-11-06 04:27:31 +00001154 PHIsToRewrite),
Daniel Dunbar15676ac2009-07-30 17:37:43 +00001155 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001156 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1157 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1158 // field.
1159 const StructType *ST =
1160 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1161
Owen Anderson086ea052009-07-06 01:34:54 +00001162 Result =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001163 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Daniel Dunbar15676ac2009-07-30 17:37:43 +00001164 PN->getName()+".f"+Twine(FieldNo), PN);
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001165 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1166 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001167 llvm_unreachable("Unknown usable value");
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001168 Result = 0;
1169 }
1170
1171 return FieldVals[FieldNo] = Result;
Chris Lattner20eef0f2007-09-13 18:00:31 +00001172}
1173
Chris Lattneraf82fb82007-09-13 17:29:05 +00001174/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1175/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001176static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1177 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner6070c012009-11-06 04:27:31 +00001178 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattneraf82fb82007-09-13 17:29:05 +00001179 // If this is a comparison against null, handle it.
1180 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1181 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1182 // If we have a setcc of the loaded pointer, we can use a setcc of any
1183 // field.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001184 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner6070c012009-11-06 04:27:31 +00001185 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattneraf82fb82007-09-13 17:29:05 +00001186
Owen Anderson6601fcd2009-07-09 23:48:35 +00001187 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Owen Andersonaac28372009-07-31 20:28:14 +00001188 Constant::getNullValue(NPtr->getType()),
Owen Anderson6601fcd2009-07-09 23:48:35 +00001189 SCI->getName());
Chris Lattneraf82fb82007-09-13 17:29:05 +00001190 SCI->replaceAllUsesWith(New);
1191 SCI->eraseFromParent();
1192 return;
1193 }
1194
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001195 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattner20eef0f2007-09-13 18:00:31 +00001196 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1197 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1198 && "Unexpected GEPI!");
Chris Lattneraf82fb82007-09-13 17:29:05 +00001199
Chris Lattner20eef0f2007-09-13 18:00:31 +00001200 // Load the pointer for this field.
1201 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001202 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner6070c012009-11-06 04:27:31 +00001203 InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner20eef0f2007-09-13 18:00:31 +00001204
1205 // Create the new GEP idx vector.
1206 SmallVector<Value*, 8> GEPIdx;
1207 GEPIdx.push_back(GEPI->getOperand(1));
1208 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1209
Gabor Greifb91ea9d2008-05-15 10:04:30 +00001210 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1211 GEPIdx.begin(), GEPIdx.end(),
Gabor Greifd6da1d02008-04-06 20:25:17 +00001212 GEPI->getName(), GEPI);
Chris Lattner20eef0f2007-09-13 18:00:31 +00001213 GEPI->replaceAllUsesWith(NGEPI);
1214 GEPI->eraseFromParent();
1215 return;
1216 }
Chris Lattnereefff982007-09-13 21:31:36 +00001217
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001218 // Recursively transform the users of PHI nodes. This will lazily create the
1219 // PHIs that are needed for individual elements. Keep track of what PHIs we
1220 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1221 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1222 // already been seen first by another load, so its uses have already been
1223 // processed.
1224 PHINode *PN = cast<PHINode>(LoadUser);
1225 bool Inserted;
1226 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1227 tie(InsertPos, Inserted) =
1228 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1229 if (!Inserted) return;
Chris Lattnereefff982007-09-13 21:31:36 +00001230
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001231 // If this is the first time we've seen this PHI, recursively process all
1232 // users.
Chris Lattnera5e124b2008-12-17 05:42:08 +00001233 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1234 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner6070c012009-11-06 04:27:31 +00001235 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnera5e124b2008-12-17 05:42:08 +00001236 }
Chris Lattneraf82fb82007-09-13 17:29:05 +00001237}
1238
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1240/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1241/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner7f252db2008-12-16 21:24:51 +00001242/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattneraf82fb82007-09-13 17:29:05 +00001243static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001244 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner6070c012009-11-06 04:27:31 +00001245 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001246 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnera5e124b2008-12-17 05:42:08 +00001247 UI != E; ) {
1248 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner6070c012009-11-06 04:27:31 +00001249 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnera5e124b2008-12-17 05:42:08 +00001250 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001251
1252 if (Load->use_empty()) {
1253 Load->eraseFromParent();
1254 InsertedScalarizedValues.erase(Load);
1255 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256}
1257
Victor Hernandez48c3c542009-09-18 22:35:49 +00001258/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1259/// it up into multiple allocations of arrays of the fields.
Victor Hernandez955449e2009-11-07 00:16:28 +00001260static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1261 Value* NElems, TargetData *TD) {
David Greenef26def42010-01-05 01:28:05 +00001262 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Victor Hernandez48c3c542009-09-18 22:35:49 +00001263 const Type* MAT = getMallocAllocatedType(CI);
1264 const StructType *STy = cast<StructType>(MAT);
1265
1266 // There is guaranteed to be at least one use of the malloc (storing
1267 // it into GV). If there are other uses, change them to be uses of
1268 // the global to simplify later code. This also deletes the store
1269 // into GV.
Victor Hernandez955449e2009-11-07 00:16:28 +00001270 ReplaceUsesOfMallocWithGlobal(CI, GV);
1271
Victor Hernandez48c3c542009-09-18 22:35:49 +00001272 // Okay, at this point, there are no users of the malloc. Insert N
1273 // new mallocs at the same place as CI, and N globals.
1274 std::vector<Value*> FieldGlobals;
1275 std::vector<Value*> FieldMallocs;
1276
1277 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1278 const Type *FieldTy = STy->getElementType(FieldNo);
1279 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1280
1281 GlobalVariable *NGV =
1282 new GlobalVariable(*GV->getParent(),
1283 PFieldTy, false, GlobalValue::InternalLinkage,
1284 Constant::getNullValue(PFieldTy),
1285 GV->getName() + ".f" + Twine(FieldNo), GV,
1286 GV->isThreadLocal());
1287 FieldGlobals.push_back(NGV);
1288
Victor Hernandez955449e2009-11-07 00:16:28 +00001289 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Victor Hernandezf1e1f4c2009-11-07 00:41:19 +00001290 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez955449e2009-11-07 00:16:28 +00001291 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandezf1e1f4c2009-11-07 00:41:19 +00001292 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez955449e2009-11-07 00:16:28 +00001293 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1294 ConstantInt::get(IntPtrTy, TypeSize),
1295 NElems,
1296 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner9c75b332010-02-26 18:23:13 +00001297 FieldMallocs.push_back(NMI);
Victor Hernandez955449e2009-11-07 00:16:28 +00001298 new StoreInst(NMI, NGV, CI);
Victor Hernandez48c3c542009-09-18 22:35:49 +00001299 }
1300
1301 // The tricky aspect of this transformation is handling the case when malloc
1302 // fails. In the original code, malloc failing would set the result pointer
1303 // of malloc to null. In this case, some mallocs could succeed and others
1304 // could fail. As such, we emit code that looks like this:
1305 // F0 = malloc(field0)
1306 // F1 = malloc(field1)
1307 // F2 = malloc(field2)
1308 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1309 // if (F0) { free(F0); F0 = 0; }
1310 // if (F1) { free(F1); F1 = 0; }
1311 // if (F2) { free(F2); F2 = 0; }
1312 // }
Victor Hernandez43af76a2009-11-10 08:32:25 +00001313 // The malloc can also fail if its argument is too large.
1314 Constant *ConstantZero = ConstantInt::get(CI->getOperand(1)->getType(), 0);
1315 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getOperand(1),
1316 ConstantZero, "isneg");
Victor Hernandez48c3c542009-09-18 22:35:49 +00001317 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez955449e2009-11-07 00:16:28 +00001318 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1319 Constant::getNullValue(FieldMallocs[i]->getType()),
1320 "isnull");
Victor Hernandez43af76a2009-11-10 08:32:25 +00001321 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez48c3c542009-09-18 22:35:49 +00001322 }
1323
1324 // Split the basic block at the old malloc.
Victor Hernandez955449e2009-11-07 00:16:28 +00001325 BasicBlock *OrigBB = CI->getParent();
1326 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Victor Hernandez48c3c542009-09-18 22:35:49 +00001327
1328 // Create the block to check the first condition. Put all these blocks at the
1329 // end of the function as they are unlikely to be executed.
Chris Lattner6070c012009-11-06 04:27:31 +00001330 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1331 "malloc_ret_null",
Victor Hernandez48c3c542009-09-18 22:35:49 +00001332 OrigBB->getParent());
1333
1334 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1335 // branch on RunningOr.
1336 OrigBB->getTerminator()->eraseFromParent();
1337 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1338
1339 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1340 // pointer, because some may be null while others are not.
1341 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1342 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1343 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1344 Constant::getNullValue(GVVal->getType()),
1345 "tmp");
Chris Lattner6070c012009-11-06 04:27:31 +00001346 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez48c3c542009-09-18 22:35:49 +00001347 OrigBB->getParent());
Chris Lattner6070c012009-11-06 04:27:31 +00001348 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez48c3c542009-09-18 22:35:49 +00001349 OrigBB->getParent());
Victor Hernandez93946082009-10-24 04:23:03 +00001350 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1351 Cmp, NullPtrBlock);
Victor Hernandez48c3c542009-09-18 22:35:49 +00001352
1353 // Fill in FreeBlock.
Victor Hernandez93946082009-10-24 04:23:03 +00001354 CallInst::CreateFree(GVVal, BI);
Victor Hernandez48c3c542009-09-18 22:35:49 +00001355 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1356 FreeBlock);
1357 BranchInst::Create(NextBlock, FreeBlock);
1358
1359 NullPtrBlock = NextBlock;
1360 }
1361
1362 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez955449e2009-11-07 00:16:28 +00001363
1364 // CI is no longer needed, remove it.
Victor Hernandez48c3c542009-09-18 22:35:49 +00001365 CI->eraseFromParent();
1366
1367 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1368 /// update all uses of the load, keep track of what scalarized loads are
1369 /// inserted for a given load.
1370 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1371 InsertedScalarizedValues[GV] = FieldGlobals;
1372
1373 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1374
1375 // Okay, the malloc site is completely handled. All of the uses of GV are now
1376 // loads, and all uses of those loads are simple. Rewrite them to use loads
1377 // of the per-field globals instead.
1378 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1379 Instruction *User = cast<Instruction>(*UI++);
1380
1381 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6070c012009-11-06 04:27:31 +00001382 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez48c3c542009-09-18 22:35:49 +00001383 continue;
1384 }
1385
1386 // Must be a store of null.
1387 StoreInst *SI = cast<StoreInst>(User);
1388 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1389 "Unexpected heap-sra user!");
1390
1391 // Insert a store of null into each global.
1392 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1393 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1394 Constant *Null = Constant::getNullValue(PT->getElementType());
1395 new StoreInst(Null, FieldGlobals[i], SI);
1396 }
1397 // Erase the original store.
1398 SI->eraseFromParent();
1399 }
1400
1401 // While we have PHIs that are interesting to rewrite, do it.
1402 while (!PHIsToRewrite.empty()) {
1403 PHINode *PN = PHIsToRewrite.back().first;
1404 unsigned FieldNo = PHIsToRewrite.back().second;
1405 PHIsToRewrite.pop_back();
1406 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1407 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1408
1409 // Add all the incoming values. This can materialize more phis.
1410 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1411 Value *InVal = PN->getIncomingValue(i);
1412 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner6070c012009-11-06 04:27:31 +00001413 PHIsToRewrite);
Victor Hernandez48c3c542009-09-18 22:35:49 +00001414 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1415 }
1416 }
1417
1418 // Drop all inter-phi links and any loads that made it this far.
1419 for (DenseMap<Value*, std::vector<Value*> >::iterator
1420 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1421 I != E; ++I) {
1422 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1423 PN->dropAllReferences();
1424 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1425 LI->dropAllReferences();
1426 }
1427
1428 // Delete all the phis and loads now that inter-references are dead.
1429 for (DenseMap<Value*, std::vector<Value*> >::iterator
1430 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1431 I != E; ++I) {
1432 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1433 PN->eraseFromParent();
1434 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1435 LI->eraseFromParent();
1436 }
1437
1438 // The old global is now dead, remove it.
1439 GV->eraseFromParent();
1440
1441 ++NumHeapSRA;
1442 return cast<GlobalVariable>(FieldGlobals[0]);
1443}
1444
Chris Lattner78e568b2008-12-15 21:02:25 +00001445/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1446/// pointer global variable with a single value stored it that is a malloc or
1447/// cast of malloc.
1448static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez48c3c542009-09-18 22:35:49 +00001449 CallInst *CI,
Victor Hernandez955449e2009-11-07 00:16:28 +00001450 const Type *AllocTy,
Victor Hernandez48c3c542009-09-18 22:35:49 +00001451 Module::global_iterator &GVI,
Chris Lattner6070c012009-11-06 04:27:31 +00001452 TargetData *TD) {
Victor Hernandez48c3c542009-09-18 22:35:49 +00001453 // If this is a malloc of an abstract type, don't touch it.
1454 if (!AllocTy->isSized())
1455 return false;
1456
1457 // We can't optimize this global unless all uses of it are *known* to be
1458 // of the malloc value, not of the null initializer value (consider a use
1459 // that compares the global's value against zero to see if the malloc has
1460 // been reached). To do this, we check to see if all uses of the global
1461 // would trap if the global were null: this proves that they must all
1462 // happen after the malloc.
1463 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1464 return false;
1465
1466 // We can't optimize this if the malloc itself is used in a complex way,
1467 // for example, being stored into multiple globals. This allows the
1468 // malloc to be stored into the specified global, loaded setcc'd, and
1469 // GEP'd. These are all things we could transform to using the global
1470 // for.
1471 {
Gabor Greif2dedb5f2010-04-06 18:58:22 +00001472 SmallPtrSet<const PHINode*, 8> PHIs;
Victor Hernandez955449e2009-11-07 00:16:28 +00001473 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
Victor Hernandez48c3c542009-09-18 22:35:49 +00001474 return false;
1475 }
1476
1477 // If we have a global that is only initialized with a fixed size malloc,
1478 // transform the program to use global memory instead of malloc'd memory.
1479 // This eliminates dynamic allocation, avoids an indirection accessing the
1480 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001481 // We cannot optimize the malloc if we cannot determine malloc array size.
Victor Hernandez43af76a2009-11-10 08:32:25 +00001482 if (Value *NElems = getMallocArraySize(CI, TD, true)) {
Victor Hernandez89058912009-10-15 20:14:52 +00001483 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1484 // Restrict this transformation to only working on small allocations
1485 // (2048 bytes currently), as we don't want to introduce a 16M global or
1486 // something.
1487 if (TD &&
1488 NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Chris Lattnerbaf1dcf2010-02-25 22:33:52 +00001489 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
Victor Hernandez89058912009-10-15 20:14:52 +00001490 return true;
1491 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00001492
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001493 // If the allocation is an array of structures, consider transforming this
1494 // into multiple malloc'd arrays, one for each field. This is basically
1495 // SRoA for malloc'd memory.
Victor Hernandez48c3c542009-09-18 22:35:49 +00001496
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001497 // If this is an allocation of a fixed size array of structs, analyze as a
1498 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Victor Hernandez9d632b62009-10-28 20:18:55 +00001499 if (NElems == ConstantInt::get(CI->getOperand(1)->getType(), 1))
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001500 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1501 AllocTy = AT->getElementType();
Victor Hernandez48c3c542009-09-18 22:35:49 +00001502
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001503 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1504 // This the structure has an unreasonable number of fields, leave it
1505 // alone.
1506 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Victor Hernandez955449e2009-11-07 00:16:28 +00001507 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
Victor Hernandez48c3c542009-09-18 22:35:49 +00001508
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001509 // If this is a fixed size array, transform the Malloc to be an alloc of
1510 // structs. malloc [100 x struct],1 -> malloc struct, 100
1511 if (const ArrayType *AT =
1512 dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
Victor Hernandez955449e2009-11-07 00:16:28 +00001513 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1514 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1515 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1516 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1517 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1518 AllocSize, NumElements,
1519 CI->getName());
1520 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1521 CI->replaceAllUsesWith(Cast);
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001522 CI->eraseFromParent();
Victor Hernandez955449e2009-11-07 00:16:28 +00001523 CI = dyn_cast<BitCastInst>(Malloc) ?
Victor Hernandezf1e1f4c2009-11-07 00:41:19 +00001524 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001525 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00001526
Victor Hernandez43af76a2009-11-10 08:32:25 +00001527 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001528 return true;
1529 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00001530 }
1531 }
1532
1533 return false;
1534}
1535
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001536// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1537// that only one value (besides its initializer) is ever stored to the global.
1538static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1539 Module::global_iterator &GVI,
Chris Lattner6070c012009-11-06 04:27:31 +00001540 TargetData *TD) {
Chris Lattner2e729112008-12-15 21:20:32 +00001541 // Ignore no-op GEPs and bitcasts.
1542 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543
1544 // If we are dealing with a pointer global that is initialized to null and
1545 // only has one (non-null) value stored into it, then we can optimize any
1546 // users of the loaded value (often calls and loads) that would trap if the
1547 // value was null.
Duncan Sands10343d92010-02-16 11:11:14 +00001548 if (GV->getInitializer()->getType()->isPointerTy() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001549 GV->getInitializer()->isNullValue()) {
1550 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1551 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson086ea052009-07-06 01:34:54 +00001552 SOVC =
Owen Anderson02b48c32009-07-29 18:55:55 +00001553 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001554
1555 // Optimize away any trapping uses of the loaded value.
Chris Lattner6070c012009-11-06 04:27:31 +00001556 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001557 return true;
Victor Hernandez48c3c542009-09-18 22:35:49 +00001558 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Victor Hernandez955449e2009-11-07 00:16:28 +00001559 const Type* MallocType = getMallocAllocatedType(CI);
1560 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
1561 GVI, TD))
1562 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001563 }
1564 }
1565
1566 return false;
1567}
1568
Chris Lattnerece46db2008-01-14 01:17:44 +00001569/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1570/// two values ever stored into GV are its initializer and OtherVal. See if we
1571/// can shrink the global into a boolean and select between the two values
1572/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner6070c012009-11-06 04:27:31 +00001573static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerece46db2008-01-14 01:17:44 +00001574 const Type *GVElType = GV->getType()->getElementType();
1575
1576 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattnere1d0fa12009-03-07 23:32:02 +00001577 // an FP value, pointer or vector, don't do this optimization because a select
1578 // between them is very expensive and unlikely to lead to later
1579 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1580 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner6070c012009-11-06 04:27:31 +00001581 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandse92dee12010-02-15 16:12:20 +00001582 GVElType->isFloatingPointTy() ||
Duncan Sands10343d92010-02-16 11:11:14 +00001583 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattnerece46db2008-01-14 01:17:44 +00001584 return false;
1585
1586 // Walk the use list of the global seeing if all the uses are load or store.
1587 // If there is anything else, bail out.
1588 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel9b951552009-03-06 01:39:36 +00001589 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattnerece46db2008-01-14 01:17:44 +00001590 return false;
1591
David Greenef26def42010-01-05 01:28:05 +00001592 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Chris Lattnerece46db2008-01-14 01:17:44 +00001593
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001594 // Create the new global, initializing it to false.
Chris Lattner6070c012009-11-06 04:27:31 +00001595 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1596 false,
1597 GlobalValue::InternalLinkage,
1598 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky74e96b72009-05-03 03:49:08 +00001599 GV->getName()+".b",
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001600 GV->isThreadLocal());
1601 GV->getParent()->getGlobalList().insert(GV, NewGV);
1602
1603 Constant *InitVal = GV->getInitializer();
Chris Lattner6070c012009-11-06 04:27:31 +00001604 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson35b47072009-08-13 21:58:54 +00001605 "No reason to shrink to bool!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606
1607 // If initialized to zero and storing one into the global, we can use a cast
1608 // instead of a select to synthesize the desired value.
1609 bool IsOneZero = false;
1610 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1611 IsOneZero = InitVal->isNullValue() && CI->isOne();
1612
1613 while (!GV->use_empty()) {
Devang Patel9b951552009-03-06 01:39:36 +00001614 Instruction *UI = cast<Instruction>(GV->use_back());
1615 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001616 // Change the store into a boolean store.
1617 bool StoringOther = SI->getOperand(0) == OtherVal;
1618 // Only do this if we weren't storing a loaded value.
1619 Value *StoreVal;
1620 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner6070c012009-11-06 04:27:31 +00001621 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1622 StoringOther);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001623 else {
1624 // Otherwise, we are storing a previously loaded copy. To do this,
1625 // change the copy from copying the original value to just copying the
1626 // bool.
1627 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1628
1629 // If we're already replaced the input, StoredVal will be a cast or
1630 // select instruction. If not, it will be a load of the original
1631 // global.
1632 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1633 assert(LI->getOperand(0) == GV && "Not a copy!");
1634 // Insert a new load, to preserve the saved value.
1635 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1636 } else {
1637 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1638 "This is not a form that we understand!");
1639 StoreVal = StoredVal->getOperand(0);
1640 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1641 }
1642 }
1643 new StoreInst(StoreVal, NewGV, SI);
Devang Patel9b951552009-03-06 01:39:36 +00001644 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645 // Change the load into a load of bool then a select.
Devang Patel9b951552009-03-06 01:39:36 +00001646 LoadInst *LI = cast<LoadInst>(UI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001647 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1648 Value *NSI;
1649 if (IsOneZero)
1650 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1651 else
Gabor Greifd6da1d02008-04-06 20:25:17 +00001652 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001653 NSI->takeName(LI);
1654 LI->replaceAllUsesWith(NSI);
Devang Patel9b951552009-03-06 01:39:36 +00001655 }
1656 UI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657 }
1658
1659 GV->eraseFromParent();
Chris Lattnerece46db2008-01-14 01:17:44 +00001660 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001661}
1662
1663
1664/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1665/// it if possible. If we make a change, return true.
1666bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1667 Module::global_iterator &GVI) {
Gabor Greif0fbd0302010-04-01 08:21:08 +00001668 SmallPtrSet<const PHINode*, 16> PHIUsers;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001669 GlobalStatus GS;
1670 GV->removeDeadConstantUsers();
1671
1672 if (GV->use_empty()) {
David Greenef26def42010-01-05 01:28:05 +00001673 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674 GV->eraseFromParent();
1675 ++NumDeleted;
1676 return true;
1677 }
1678
1679 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1680#if 0
David Greenef26def42010-01-05 01:28:05 +00001681 DEBUG(dbgs() << "Global: " << *GV);
1682 DEBUG(dbgs() << " isLoaded = " << GS.isLoaded << "\n");
1683 DEBUG(dbgs() << " StoredType = ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001684 switch (GS.StoredType) {
David Greenef26def42010-01-05 01:28:05 +00001685 case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break;
1686 case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n");
Victor Hernandezf1e1f4c2009-11-07 00:41:19 +00001687 break;
David Greenef26def42010-01-05 01:28:05 +00001688 case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break;
1689 case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001690 }
1691 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
David Greenef26def42010-01-05 01:28:05 +00001692 DEBUG(dbgs() << " StoredOnceValue = " << *GS.StoredOnceValue << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001693 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
David Greenef26def42010-01-05 01:28:05 +00001694 DEBUG(dbgs() << " AccessingFunction = " << GS.AccessingFunction->getName()
Victor Hernandezf1e1f4c2009-11-07 00:41:19 +00001695 << "\n");
David Greenef26def42010-01-05 01:28:05 +00001696 DEBUG(dbgs() << " HasMultipleAccessingFunctions = "
Victor Hernandezf1e1f4c2009-11-07 00:41:19 +00001697 << GS.HasMultipleAccessingFunctions << "\n");
David Greenef26def42010-01-05 01:28:05 +00001698 DEBUG(dbgs() << " HasNonInstructionUser = "
Victor Hernandezf1e1f4c2009-11-07 00:41:19 +00001699 << GS.HasNonInstructionUser<<"\n");
David Greenef26def42010-01-05 01:28:05 +00001700 DEBUG(dbgs() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001701#endif
1702
1703 // If this is a first class global and has only one accessing function
1704 // and this function is main (which we know is not recursive we can make
1705 // this global a local variable) we replace the global with a local alloca
1706 // in this function.
1707 //
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001708 // NOTE: It doesn't make sense to promote non single-value types since we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001709 // are just replacing static memory to stack memory.
Sanjiv Gupta961b5d22009-06-17 06:47:15 +00001710 //
1711 // If the global is in different address space, don't bring it to stack.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 if (!GS.HasMultipleAccessingFunctions &&
1713 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001714 GV->getType()->getElementType()->isSingleValueType() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001715 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta961b5d22009-06-17 06:47:15 +00001716 GS.AccessingFunction->hasExternalLinkage() &&
1717 GV->getType()->getAddressSpace() == 0) {
David Greenef26def42010-01-05 01:28:05 +00001718 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Gabor Greif0fbd0302010-04-01 08:21:08 +00001719 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1720 ->getEntryBlock().begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001721 const Type* ElemTy = GV->getType()->getElementType();
1722 // FIXME: Pass Global's alignment when globals have alignment
Gabor Greif0fbd0302010-04-01 08:21:08 +00001723 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001724 if (!isa<UndefValue>(GV->getInitializer()))
Gabor Greif0fbd0302010-04-01 08:21:08 +00001725 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001726
1727 GV->replaceAllUsesWith(Alloca);
1728 GV->eraseFromParent();
1729 ++NumLocalized;
1730 return true;
1731 }
1732
1733 // If the global is never loaded (but may be stored to), it is dead.
1734 // Delete it now.
1735 if (!GS.isLoaded) {
David Greenef26def42010-01-05 01:28:05 +00001736 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001737
1738 // Delete any stores we can find to the global. We may not be able to
1739 // make it completely dead though.
Chris Lattner6070c012009-11-06 04:27:31 +00001740 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001741
1742 // If the global is dead now, delete it.
1743 if (GV->use_empty()) {
1744 GV->eraseFromParent();
1745 ++NumDeleted;
1746 Changed = true;
1747 }
1748 return Changed;
1749
1750 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
David Greenef26def42010-01-05 01:28:05 +00001751 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001752 GV->setConstant(true);
1753
1754 // Clean up any obviously simplifiable users now.
Chris Lattner6070c012009-11-06 04:27:31 +00001755 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001756
1757 // If the global is dead now, just nuke it.
1758 if (GV->use_empty()) {
David Greenef26def42010-01-05 01:28:05 +00001759 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
Chris Lattner8a6411c2009-08-23 04:37:46 +00001760 << "all users and delete global!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761 GV->eraseFromParent();
1762 ++NumDeleted;
1763 }
1764
1765 ++NumMarked;
1766 return true;
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001767 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Dan Gohmanf657fcd2009-08-14 00:11:03 +00001768 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
Chris Lattner6070c012009-11-06 04:27:31 +00001769 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
Dan Gohmanf657fcd2009-08-14 00:11:03 +00001770 GVI = FirstNewGV; // Don't skip the newly produced globals!
1771 return true;
1772 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1774 // If the initial value for the global was an undef value, and if only
1775 // one other value was stored into it, we can just change the
Duncan Sands25464152009-01-13 13:48:44 +00001776 // initializer to be the stored value, then delete all stores to the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001777 // global. This allows us to mark it constant.
1778 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1779 if (isa<UndefValue>(GV->getInitializer())) {
1780 // Change the initial value here.
1781 GV->setInitializer(SOVConstant);
1782
1783 // Clean up any obviously simplifiable users now.
Chris Lattner6070c012009-11-06 04:27:31 +00001784 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785
1786 if (GV->use_empty()) {
David Greenef26def42010-01-05 01:28:05 +00001787 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Chris Lattner8a6411c2009-08-23 04:37:46 +00001788 << "simplify all users and delete global!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001789 GV->eraseFromParent();
1790 ++NumDeleted;
1791 } else {
1792 GVI = GV;
1793 }
1794 ++NumSubstitute;
1795 return true;
1796 }
1797
1798 // Try to optimize globals based on the knowledge that only one value
1799 // (besides its initializer) is ever stored to the global.
1800 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Chris Lattner6070c012009-11-06 04:27:31 +00001801 getAnalysisIfAvailable<TargetData>()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001802 return true;
1803
1804 // Otherwise, if the global was not a boolean, we can shrink it to be a
1805 // boolean.
1806 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner6070c012009-11-06 04:27:31 +00001807 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001808 ++NumShrunkToBool;
1809 return true;
1810 }
1811 }
1812 }
1813 return false;
1814}
1815
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001816/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1817/// function, changing them to FastCC.
1818static void ChangeCalleesToFastCall(Function *F) {
1819 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands551ec902008-02-18 17:32:13 +00001820 CallSite User(cast<Instruction>(*UI));
1821 User.setCallingConv(CallingConv::Fast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001822 }
1823}
1824
Devang Pateld222f862008-09-25 21:00:45 +00001825static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner1c8733e2008-03-12 17:45:29 +00001826 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Pateld222f862008-09-25 21:00:45 +00001827 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands551ec902008-02-18 17:32:13 +00001828 continue;
1829
Duncan Sands551ec902008-02-18 17:32:13 +00001830 // There can be only one.
Devang Pateld222f862008-09-25 21:00:45 +00001831 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001832 }
1833
1834 return Attrs;
1835}
1836
1837static void RemoveNestAttribute(Function *F) {
Devang Pateld222f862008-09-25 21:00:45 +00001838 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001839 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands551ec902008-02-18 17:32:13 +00001840 CallSite User(cast<Instruction>(*UI));
Devang Pateld222f862008-09-25 21:00:45 +00001841 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001842 }
1843}
1844
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001845bool GlobalOpt::OptimizeFunctions(Module &M) {
1846 bool Changed = false;
1847 // Optimize functions.
1848 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1849 Function *F = FI++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00001850 // Functions without names cannot be referenced outside this module.
1851 if (!F->hasName() && !F->isDeclaration())
1852 F->setLinkage(GlobalValue::InternalLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001853 F->removeDeadConstantUsers();
Chris Lattner3f2e8ec2009-11-01 19:03:42 +00001854 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1855 F->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001856 Changed = true;
1857 ++NumFnDeleted;
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001858 } else if (F->hasLocalLinkage()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001859 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad1379d592009-06-10 08:41:11 +00001860 !F->hasAddressTaken()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001861 // If this function has C calling conventions, is not a varargs
1862 // function, and is only called directly, promote it to use the Fast
1863 // calling convention.
1864 F->setCallingConv(CallingConv::Fast);
1865 ChangeCalleesToFastCall(F);
1866 ++NumFastCallFns;
1867 Changed = true;
1868 }
1869
Devang Pateld222f862008-09-25 21:00:45 +00001870 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad1379d592009-06-10 08:41:11 +00001871 !F->hasAddressTaken()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001872 // The function is not used by a trampoline intrinsic, so it is safe
1873 // to remove the 'nest' attribute.
1874 RemoveNestAttribute(F);
1875 ++NumNestRemoved;
1876 Changed = true;
1877 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001878 }
1879 }
1880 return Changed;
1881}
1882
1883bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1884 bool Changed = false;
1885 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1886 GVI != E; ) {
1887 GlobalVariable *GV = GVI++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00001888 // Global variables without names cannot be referenced outside this module.
1889 if (!GV->hasName() && !GV->isDeclaration())
1890 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman4f77c3e2009-11-23 16:22:21 +00001891 // Simplify the initializer.
1892 if (GV->hasInitializer())
1893 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohman3ed470d2010-04-02 03:04:37 +00001894 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman4f77c3e2009-11-23 16:22:21 +00001895 Constant *New = ConstantFoldConstantExpression(CE, TD);
1896 if (New && New != CE)
1897 GV->setInitializer(New);
1898 }
1899 // Do more involved optimizations if the global is internal.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001900 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901 GV->hasInitializer())
1902 Changed |= ProcessInternalGlobal(GV, GVI);
1903 }
1904 return Changed;
1905}
1906
1907/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1908/// initializers have an init priority of 65535.
1909GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1910 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1911 I != E; ++I)
1912 if (I->getName() == "llvm.global_ctors") {
1913 // Found it, verify it's an array of { int, void()* }.
1914 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1915 if (!ATy) return 0;
1916 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1917 if (!STy || STy->getNumElements() != 2 ||
Duncan Sandse92dee12010-02-15 16:12:20 +00001918 !STy->getElementType(0)->isIntegerTy(32)) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001919 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1920 if (!PFTy) return 0;
1921 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
Benjamin Kramerf2052d52010-01-05 13:12:22 +00001922 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
Owen Anderson35b47072009-08-13 21:58:54 +00001923 FTy->isVarArg() || FTy->getNumParams() != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001924 return 0;
1925
1926 // Verify that the initializer is simple enough for us to handle.
Dan Gohman5e423ed2009-08-19 18:20:44 +00001927 if (!I->hasDefinitiveInitializer()) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001928 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1929 if (!CA) return 0;
Gabor Greif20f03f52008-05-29 01:59:18 +00001930 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1931 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001932 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1933 continue;
1934
1935 // Must have a function or null ptr.
1936 if (!isa<Function>(CS->getOperand(1)))
1937 return 0;
1938
1939 // Init priority must be standard.
1940 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1941 if (!CI || CI->getZExtValue() != 65535)
1942 return 0;
1943 } else {
1944 return 0;
1945 }
1946
1947 return I;
1948 }
1949 return 0;
1950}
1951
1952/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1953/// return a list of the functions and null terminator as a vector.
1954static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1955 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1956 std::vector<Function*> Result;
1957 Result.reserve(CA->getNumOperands());
Gabor Greif20f03f52008-05-29 01:59:18 +00001958 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1959 ConstantStruct *CS = cast<ConstantStruct>(*i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001960 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1961 }
1962 return Result;
1963}
1964
1965/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1966/// specified array, returning the new global to use.
1967static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner6070c012009-11-06 04:27:31 +00001968 const std::vector<Function*> &Ctors) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001969 // If we made a change, reassemble the initializer list.
1970 std::vector<Constant*> CSVals;
Chris Lattner6070c012009-11-06 04:27:31 +00001971 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001972 CSVals.push_back(0);
1973
1974 // Create the new init list.
1975 std::vector<Constant*> CAList;
1976 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1977 if (Ctors[i]) {
1978 CSVals[1] = Ctors[i];
1979 } else {
Chris Lattner6070c012009-11-06 04:27:31 +00001980 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
1981 false);
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001982 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersonaac28372009-07-31 20:28:14 +00001983 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner6070c012009-11-06 04:27:31 +00001984 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
1985 2147483647);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001986 }
Chris Lattner6070c012009-11-06 04:27:31 +00001987 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988 }
1989
1990 // Create the array initializer.
1991 const Type *StructTy =
Nick Lewycky9229fdb2009-09-19 20:30:26 +00001992 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson7b4f9f82009-07-28 18:32:17 +00001993 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewycky9229fdb2009-09-19 20:30:26 +00001994 CAList.size()), CAList);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001995
1996 // If we didn't change the number of elements, don't create a new GV.
1997 if (CA->getType() == GCL->getInitializer()->getType()) {
1998 GCL->setInitializer(CA);
1999 return GCL;
2000 }
2001
2002 // Create the new global and insert it next to the existing list.
Chris Lattner6070c012009-11-06 04:27:31 +00002003 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004 GCL->getLinkage(), CA, "",
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002005 GCL->isThreadLocal());
2006 GCL->getParent()->getGlobalList().insert(GCL, NGV);
2007 NGV->takeName(GCL);
2008
2009 // Nuke the old list, replacing any uses with the new one.
2010 if (!GCL->use_empty()) {
2011 Constant *V = NGV;
2012 if (V->getType() != GCL->getType())
Owen Anderson02b48c32009-07-29 18:55:55 +00002013 V = ConstantExpr::getBitCast(V, GCL->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002014 GCL->replaceAllUsesWith(V);
2015 }
2016 GCL->eraseFromParent();
2017
2018 if (Ctors.size())
2019 return NGV;
2020 else
2021 return 0;
2022}
2023
2024
Chris Lattner4cd08c22008-12-16 07:34:30 +00002025static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002026 Value *V) {
2027 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2028 Constant *R = ComputedValues[V];
2029 assert(R && "Reference to an uncomputed value!");
2030 return R;
2031}
2032
2033/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2034/// enough for us to understand. In particular, if it is a cast of something,
2035/// we punt. We basically just support direct accesses to globals and GEP's of
2036/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner6070c012009-11-06 04:27:31 +00002037static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohman9524ee62009-09-07 22:42:05 +00002038 // Conservatively, avoid aggregate types. This is because we don't
2039 // want to worry about them partially overlapping other stores.
2040 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2041 return false;
2042
Dan Gohman278fbe62009-09-07 22:31:26 +00002043 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2044 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2045 // external globals.
2046 return GV->hasDefinitiveInitializer();
2047
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2049 // Handle a constantexpr gep.
2050 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohman0c834c02009-09-07 22:40:13 +00002051 isa<GlobalVariable>(CE->getOperand(0)) &&
2052 cast<GEPOperator>(CE)->isInBounds()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002053 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman278fbe62009-09-07 22:31:26 +00002054 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2055 // external globals.
2056 if (!GV->hasDefinitiveInitializer())
2057 return false;
Dan Gohmanc2723ad2009-09-07 22:44:55 +00002058
Dan Gohmanc2723ad2009-09-07 22:44:55 +00002059 // The first index must be zero.
Dan Gohmandb050e92009-09-10 23:37:55 +00002060 ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
Dan Gohmanc2723ad2009-09-07 22:44:55 +00002061 if (!CI || !CI->isZero()) return false;
Dan Gohmanc2723ad2009-09-07 22:44:55 +00002062
2063 // The remaining indices must be compile-time known integers within the
Dan Gohmandb050e92009-09-10 23:37:55 +00002064 // notional bounds of the corresponding static array types.
2065 if (!CE->isGEPWithNoNotionalOverIndexing())
2066 return false;
Dan Gohmanc2723ad2009-09-07 22:44:55 +00002067
Dan Gohmanf49f7b02009-10-05 16:36:26 +00002068 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002069 }
2070 return false;
2071}
2072
2073/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2074/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2075/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2076static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner6070c012009-11-06 04:27:31 +00002077 ConstantExpr *Addr, unsigned OpNo) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002078 // Base case of the recursion.
2079 if (OpNo == Addr->getNumOperands()) {
2080 assert(Val->getType() == Init->getType() && "Type mismatch!");
2081 return Val;
2082 }
2083
Chris Lattnere07d77d2010-01-07 01:16:21 +00002084 std::vector<Constant*> Elts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002086
2087 // Break up the constant into its elements.
2088 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif20f03f52008-05-29 01:59:18 +00002089 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2090 Elts.push_back(cast<Constant>(*i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002091 } else if (isa<ConstantAggregateZero>(Init)) {
2092 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersonaac28372009-07-31 20:28:14 +00002093 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002094 } else if (isa<UndefValue>(Init)) {
2095 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersonb99ecca2009-07-30 23:03:37 +00002096 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002097 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00002098 llvm_unreachable("This code is out of sync with "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099 " ConstantFoldLoadThroughGEPConstantExpr");
2100 }
2101
2102 // Replace the element that we are supposed to.
2103 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2104 unsigned Idx = CU->getZExtValue();
2105 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner6070c012009-11-06 04:27:31 +00002106 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002107
2108 // Return the modified struct.
Chris Lattner6070c012009-11-06 04:27:31 +00002109 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2110 STy->isPacked());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002111 } else {
2112 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnere07d77d2010-01-07 01:16:21 +00002113 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002114
Chris Lattnere07d77d2010-01-07 01:16:21 +00002115 uint64_t NumElts;
2116 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2117 NumElts = ATy->getNumElements();
2118 else
2119 NumElts = cast<VectorType>(InitTy)->getNumElements();
2120
2121
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002122 // Break up the array into elements.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002123 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif20f03f52008-05-29 01:59:18 +00002124 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2125 Elts.push_back(cast<Constant>(*i));
Chris Lattner003b65f2010-01-07 01:20:20 +00002126 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2127 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2128 Elts.push_back(cast<Constant>(*i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002129 } else if (isa<ConstantAggregateZero>(Init)) {
Chris Lattnere07d77d2010-01-07 01:16:21 +00002130 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002131 } else {
Chris Lattnere07d77d2010-01-07 01:16:21 +00002132 assert(isa<UndefValue>(Init) && "This code is out of sync with "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002133 " ConstantFoldLoadThroughGEPConstantExpr");
Chris Lattnere07d77d2010-01-07 01:16:21 +00002134 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002135 }
2136
Chris Lattnere07d77d2010-01-07 01:16:21 +00002137 assert(CI->getZExtValue() < NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002138 Elts[CI->getZExtValue()] =
Chris Lattner6070c012009-11-06 04:27:31 +00002139 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnere07d77d2010-01-07 01:16:21 +00002140
Duncan Sands10343d92010-02-16 11:11:14 +00002141 if (Init->getType()->isArrayTy())
Chris Lattnere07d77d2010-01-07 01:16:21 +00002142 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2143 else
2144 return ConstantVector::get(&Elts[0], Elts.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002145 }
2146}
2147
2148/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2149/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner6070c012009-11-06 04:27:31 +00002150static void CommitValueTo(Constant *Val, Constant *Addr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002151 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2152 assert(GV->hasInitializer());
2153 GV->setInitializer(Val);
2154 return;
2155 }
Chris Lattnere07d77d2010-01-07 01:16:21 +00002156
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002157 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2158 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnere07d77d2010-01-07 01:16:21 +00002159 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002160}
2161
2162/// ComputeLoadResult - Return the value that would be computed by a load from
2163/// P after the stores reflected by 'memory' have been performed. If we can't
2164/// decide, return null.
2165static Constant *ComputeLoadResult(Constant *P,
Chris Lattner6070c012009-11-06 04:27:31 +00002166 const DenseMap<Constant*, Constant*> &Memory) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002167 // If this memory location has been recently stored, use the stored value: it
2168 // is the most up-to-date.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002169 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002170 if (I != Memory.end()) return I->second;
2171
2172 // Access it.
2173 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman5e423ed2009-08-19 18:20:44 +00002174 if (GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002175 return GV->getInitializer();
2176 return 0;
2177 }
2178
2179 // Handle a constantexpr getelementptr.
2180 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2181 if (CE->getOpcode() == Instruction::GetElementPtr &&
2182 isa<GlobalVariable>(CE->getOperand(0))) {
2183 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman5e423ed2009-08-19 18:20:44 +00002184 if (GV->hasDefinitiveInitializer())
Dan Gohmanf49f7b02009-10-05 16:36:26 +00002185 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002186 }
2187
2188 return 0; // don't know how to evaluate.
2189}
2190
2191/// EvaluateFunction - Evaluate a call to function F, returning true if
2192/// successful, false if we can't evaluate it. ActualArgs contains the formal
2193/// arguments for the function.
2194static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sands408bbf32009-08-17 14:33:27 +00002195 const SmallVectorImpl<Constant*> &ActualArgs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002196 std::vector<Function*> &CallStack,
Chris Lattner4cd08c22008-12-16 07:34:30 +00002197 DenseMap<Constant*, Constant*> &MutatedMemory,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002198 std::vector<GlobalVariable*> &AllocaTmps) {
2199 // Check to see if this function is already executing (recursion). If so,
2200 // bail out. TODO: we might want to accept limited recursion.
2201 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2202 return false;
2203
2204 CallStack.push_back(F);
2205
2206 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002207 DenseMap<Value*, Constant*> Values;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002208
2209 // Initialize arguments to the incoming values specified.
2210 unsigned ArgNo = 0;
2211 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2212 ++AI, ++ArgNo)
2213 Values[AI] = ActualArgs[ArgNo];
2214
2215 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2216 /// we can only evaluate any one basic block at most once. This set keeps
2217 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002218 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002219
2220 // CurInst - The current instruction we're evaluating.
2221 BasicBlock::iterator CurInst = F->begin()->begin();
2222
2223 // This is the main evaluation loop.
2224 while (1) {
2225 Constant *InstResult = 0;
2226
2227 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2228 if (SI->isVolatile()) return false; // no volatile accesses.
2229 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner6070c012009-11-06 04:27:31 +00002230 if (!isSimpleEnoughPointerToCommit(Ptr))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002231 // If this is too complex for us to commit, reject it.
2232 return false;
2233 Constant *Val = getVal(Values, SI->getOperand(0));
2234 MutatedMemory[Ptr] = Val;
2235 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002236 InstResult = ConstantExpr::get(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002237 getVal(Values, BO->getOperand(0)),
2238 getVal(Values, BO->getOperand(1)));
2239 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002240 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002241 getVal(Values, CI->getOperand(0)),
2242 getVal(Values, CI->getOperand(1)));
2243 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002244 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002245 getVal(Values, CI->getOperand(0)),
2246 CI->getType());
2247 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002248 InstResult =
Owen Anderson02b48c32009-07-29 18:55:55 +00002249 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002250 getVal(Values, SI->getOperand(1)),
2251 getVal(Values, SI->getOperand(2)));
2252 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2253 Constant *P = getVal(Values, GEP->getOperand(0));
2254 SmallVector<Constant*, 8> GEPOps;
Gabor Greif20f03f52008-05-29 01:59:18 +00002255 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2256 i != e; ++i)
2257 GEPOps.push_back(getVal(Values, *i));
Dan Gohman6d907d02009-09-07 22:34:43 +00002258 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2259 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2260 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002261 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2262 if (LI->isVolatile()) return false; // no volatile accesses.
2263 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner6070c012009-11-06 04:27:31 +00002264 MutatedMemory);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002265 if (InstResult == 0) return false; // Could not evaluate load.
2266 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2267 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2268 const Type *Ty = AI->getType()->getElementType();
Chris Lattner6070c012009-11-06 04:27:31 +00002269 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002270 GlobalValue::InternalLinkage,
Owen Andersonb99ecca2009-07-30 23:03:37 +00002271 UndefValue::get(Ty),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272 AI->getName()));
2273 InstResult = AllocaTmps.back();
2274 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel5b1082b2009-03-09 23:04:12 +00002275
2276 // Debug info can safely be ignored here.
2277 if (isa<DbgInfoIntrinsic>(CI)) {
2278 ++CurInst;
2279 continue;
2280 }
2281
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002282 // Cannot handle inline asm.
2283 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2284
2285 // Resolve function pointers.
2286 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2287 if (!Callee) return false; // Cannot resolve.
2288
Duncan Sands408bbf32009-08-17 14:33:27 +00002289 SmallVector<Constant*, 8> Formals;
Gabor Greif20f03f52008-05-29 01:59:18 +00002290 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2291 i != e; ++i)
2292 Formals.push_back(getVal(Values, *i));
Duncan Sands408bbf32009-08-17 14:33:27 +00002293
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002294 if (Callee->isDeclaration()) {
2295 // If this is a function we can constant fold, do it.
Duncan Sands408bbf32009-08-17 14:33:27 +00002296 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002297 Formals.size())) {
2298 InstResult = C;
2299 } else {
2300 return false;
2301 }
2302 } else {
2303 if (Callee->getFunctionType()->isVarArg())
2304 return false;
2305
2306 Constant *RetVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002307 // Execute the call, if successful, use the return value.
2308 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2309 MutatedMemory, AllocaTmps))
2310 return false;
2311 InstResult = RetVal;
2312 }
2313 } else if (isa<TerminatorInst>(CurInst)) {
2314 BasicBlock *NewBB = 0;
2315 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2316 if (BI->isUnconditional()) {
2317 NewBB = BI->getSuccessor(0);
2318 } else {
2319 ConstantInt *Cond =
2320 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2321 if (!Cond) return false; // Cannot determine.
2322
2323 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2324 }
2325 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2326 ConstantInt *Val =
2327 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2328 if (!Val) return false; // Cannot determine.
2329 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattner4f2bbd62009-10-29 05:51:50 +00002330 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2331 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2332 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2333 NewBB = BA->getBasicBlock();
Chris Lattner620cead2009-11-01 01:27:45 +00002334 else
2335 return false; // Cannot determine.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002336 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2337 if (RI->getNumOperands())
2338 RetVal = getVal(Values, RI->getOperand(0));
2339
2340 CallStack.pop_back(); // return from fn.
2341 return true; // We succeeded at evaluating this ctor!
2342 } else {
2343 // invoke, unwind, unreachable.
2344 return false; // Cannot handle this terminator.
2345 }
2346
2347 // Okay, we succeeded in evaluating this control flow. See if we have
2348 // executed the new block before. If so, we have a looping function,
2349 // which we cannot evaluate in reasonable time.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002350 if (!ExecutedBlocks.insert(NewBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002351 return false; // looped!
2352
2353 // Okay, we have never been in this block before. Check to see if there
2354 // are any PHI nodes. If so, evaluate them with information about where
2355 // we came from.
2356 BasicBlock *OldBB = CurInst->getParent();
2357 CurInst = NewBB->begin();
2358 PHINode *PN;
2359 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2360 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2361
2362 // Do NOT increment CurInst. We know that the terminator had no value.
2363 continue;
2364 } else {
2365 // Did not know how to evaluate this!
2366 return false;
2367 }
2368
2369 if (!CurInst->use_empty())
2370 Values[CurInst] = InstResult;
2371
2372 // Advance program counter.
2373 ++CurInst;
2374 }
2375}
2376
2377/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2378/// we can. Return true if we can, false otherwise.
2379static bool EvaluateStaticConstructor(Function *F) {
2380 /// MutatedMemory - For each store we execute, we update this map. Loads
2381 /// check this to get the most up-to-date value. If evaluation is successful,
2382 /// this state is committed to the process.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002383 DenseMap<Constant*, Constant*> MutatedMemory;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002384
2385 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2386 /// to represent its body. This vector is needed so we can delete the
2387 /// temporary globals when we are done.
2388 std::vector<GlobalVariable*> AllocaTmps;
2389
2390 /// CallStack - This is used to detect recursion. In pathological situations
2391 /// we could hit exponential behavior, but at least there is nothing
2392 /// unbounded.
2393 std::vector<Function*> CallStack;
2394
2395 // Call the function.
2396 Constant *RetValDummy;
Duncan Sands408bbf32009-08-17 14:33:27 +00002397 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2398 SmallVector<Constant*, 0>(), CallStack,
2399 MutatedMemory, AllocaTmps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002400 if (EvalSuccess) {
2401 // We succeeded at evaluation: commit the result.
David Greenef26def42010-01-05 01:28:05 +00002402 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbar005975c2009-07-25 00:23:56 +00002403 << F->getName() << "' to " << MutatedMemory.size()
2404 << " stores.\n");
Chris Lattner4cd08c22008-12-16 07:34:30 +00002405 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002406 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner6070c012009-11-06 04:27:31 +00002407 CommitValueTo(I->second, I->first);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002408 }
2409
2410 // At this point, we are done interpreting. If we created any 'alloca'
2411 // temporaries, release them now.
2412 while (!AllocaTmps.empty()) {
2413 GlobalVariable *Tmp = AllocaTmps.back();
2414 AllocaTmps.pop_back();
2415
2416 // If there are still users of the alloca, the program is doing something
2417 // silly, e.g. storing the address of the alloca somewhere and using it
2418 // later. Since this is undefined, we'll just make it be null.
2419 if (!Tmp->use_empty())
Owen Andersonaac28372009-07-31 20:28:14 +00002420 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002421 delete Tmp;
2422 }
2423
2424 return EvalSuccess;
2425}
2426
2427
2428
2429/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2430/// Return true if anything changed.
2431bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2432 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2433 bool MadeChange = false;
2434 if (Ctors.empty()) return false;
2435
2436 // Loop over global ctors, optimizing them when we can.
2437 for (unsigned i = 0; i != Ctors.size(); ++i) {
2438 Function *F = Ctors[i];
2439 // Found a null terminator in the middle of the list, prune off the rest of
2440 // the list.
2441 if (F == 0) {
2442 if (i != Ctors.size()-1) {
2443 Ctors.resize(i+1);
2444 MadeChange = true;
2445 }
2446 break;
2447 }
2448
2449 // We cannot simplify external ctor functions.
2450 if (F->empty()) continue;
2451
2452 // If we can evaluate the ctor at compile time, do.
2453 if (EvaluateStaticConstructor(F)) {
2454 Ctors.erase(Ctors.begin()+i);
2455 MadeChange = true;
2456 --i;
2457 ++NumCtorsEvaluated;
2458 continue;
2459 }
2460 }
2461
2462 if (!MadeChange) return false;
2463
Chris Lattner6070c012009-11-06 04:27:31 +00002464 GCL = InstallGlobalCtors(GCL, Ctors);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002465 return true;
2466}
2467
Duncan Sands0c7b6332009-03-06 10:21:56 +00002468bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002469 bool Changed = false;
2470
Duncan Sands0f064b92009-01-07 20:01:06 +00002471 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandse7f431f2009-02-15 09:56:08 +00002472 I != E;) {
2473 Module::alias_iterator J = I++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00002474 // Aliases without names cannot be referenced outside this module.
2475 if (!J->hasName() && !J->isDeclaration())
2476 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandse7f431f2009-02-15 09:56:08 +00002477 // If the aliasee may change at link time, nothing can be done - bail out.
2478 if (J->mayBeOverridden())
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002479 continue;
2480
Duncan Sandse7f431f2009-02-15 09:56:08 +00002481 Constant *Aliasee = J->getAliasee();
2482 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands7531ad62009-02-18 17:55:38 +00002483 Target->removeDeadConstantUsers();
Duncan Sandse7f431f2009-02-15 09:56:08 +00002484 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2485
2486 // Make all users of the alias use the aliasee instead.
2487 if (!J->use_empty()) {
2488 J->replaceAllUsesWith(Aliasee);
2489 ++NumAliasesResolved;
2490 Changed = true;
2491 }
2492
Duncan Sands35138e32009-12-08 10:10:20 +00002493 // If the alias is externally visible, we may still be able to simplify it.
2494 if (!J->hasLocalLinkage()) {
2495 // If the aliasee has internal linkage, give it the name and linkage
2496 // of the alias, and delete the alias. This turns:
2497 // define internal ... @f(...)
2498 // @a = alias ... @f
2499 // into:
2500 // define ... @a(...)
2501 if (!Target->hasLocalLinkage())
2502 continue;
Duncan Sandse7f431f2009-02-15 09:56:08 +00002503
Duncan Sands35138e32009-12-08 10:10:20 +00002504 // Do not perform the transform if multiple aliases potentially target the
2505 // aliasee. This check also ensures that it is safe to replace the section
2506 // and other attributes of the aliasee with those of the alias.
2507 if (!hasOneUse)
2508 continue;
Duncan Sandse7f431f2009-02-15 09:56:08 +00002509
Duncan Sands35138e32009-12-08 10:10:20 +00002510 // Give the aliasee the name, linkage and other attributes of the alias.
2511 Target->takeName(J);
2512 Target->setLinkage(J->getLinkage());
2513 Target->GlobalValue::copyAttributesFrom(J);
2514 }
Duncan Sandse7f431f2009-02-15 09:56:08 +00002515
2516 // Delete the alias.
2517 M.getAliasList().erase(J);
2518 ++NumAliasesRemoved;
2519 Changed = true;
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002520 }
2521
2522 return Changed;
2523}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002524
2525bool GlobalOpt::runOnModule(Module &M) {
2526 bool Changed = false;
2527
2528 // Try to find the llvm.globalctors list.
2529 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2530
2531 bool LocalChange = true;
2532 while (LocalChange) {
2533 LocalChange = false;
2534
2535 // Delete functions that are trivially dead, ccc -> fastcc
2536 LocalChange |= OptimizeFunctions(M);
2537
2538 // Optimize global_ctors list.
2539 if (GlobalCtors)
2540 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2541
2542 // Optimize non-address-taken globals.
2543 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002544
2545 // Resolve aliases, when possible.
Duncan Sands0c7b6332009-03-06 10:21:56 +00002546 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002547 Changed |= LocalChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548 }
2549
2550 // TODO: Move all global ctors functions to the end of the module for code
2551 // layout.
2552
2553 return Changed;
2554}