blob: 3d10649c95bd5bbf05c64a810fad7952d3f38787 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000023#include "llvm/LLVMContext.h"
Chris Lattner079236d2004-02-25 21:34:36 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez83d63912009-09-18 22:35:49 +000027#include "llvm/Analysis/MallocHelper.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000028#include "llvm/Target/TargetData.h"
Duncan Sands548448a2008-02-18 17:32:13 +000029#include "llvm/Support/CallSite.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000030#include "llvm/Support/Compiler.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000034#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000040#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000041#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000042using namespace llvm;
43
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumMarked , "Number of globals marked constant");
45STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
46STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
47STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
48STATISTIC(NumDeleted , "Number of globals deleted");
49STATISTIC(NumFnDeleted , "Number of functions deleted");
50STATISTIC(NumGlobUses , "Number of global uses devirtualized");
51STATISTIC(NumLocalized , "Number of globals localized");
52STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
53STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
54STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000055STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000056STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
57STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Chris Lattner079236d2004-02-25 21:34:36 +000058
Chris Lattner86453c52006-12-19 22:09:18 +000059namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000060 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000061 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner30ba5692004-10-11 05:54:41 +000062 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000063 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000064 GlobalOpt() : ModulePass(&ID) {}
Misha Brukmanfd939082005-04-21 23:48:37 +000065
Chris Lattnerb12914b2004-09-20 04:48:05 +000066 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000067
68 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000069 GlobalVariable *FindGlobalCtors(Module &M);
70 bool OptimizeFunctions(Module &M);
71 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000072 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000073 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000074 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000075 };
Chris Lattner079236d2004-02-25 21:34:36 +000076}
77
Dan Gohman844731a2008-05-13 00:00:25 +000078char GlobalOpt::ID = 0;
79static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
80
Chris Lattner7a90b682004-10-07 04:16:33 +000081ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000082
Dan Gohman844731a2008-05-13 00:00:25 +000083namespace {
84
Chris Lattner7a90b682004-10-07 04:16:33 +000085/// GlobalStatus - As we analyze each global, keep track of some information
86/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000087/// this info will be accurate.
Reid Spencer9133fe22007-02-05 23:32:05 +000088struct VISIBILITY_HIDDEN GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000089 /// isLoaded - True if the global is ever loaded. If the global isn't ever
90 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000091 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000092
93 /// StoredType - Keep track of what stores to the global look like.
94 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000095 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000096 /// NotStored - There is no store to this global. It can thus be marked
97 /// constant.
98 NotStored,
99
100 /// isInitializerStored - This global is stored to, but the only thing
101 /// stored is the constant it was initialized with. This is only tracked
102 /// for scalar globals.
103 isInitializerStored,
104
105 /// isStoredOnce - This global is stored to, but only its initializer and
106 /// one other value is ever stored to it. If this global isStoredOnce, we
107 /// track the value stored to it in StoredOnceValue below. This is only
108 /// tracked for scalar globals.
109 isStoredOnce,
110
111 /// isStored - This global is stored to by multiple values or something else
112 /// that we cannot track.
113 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000114 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000115
116 /// StoredOnceValue - If only one value (besides the initializer constant) is
117 /// ever stored to this global, keep track of what value it is.
118 Value *StoredOnceValue;
119
Chris Lattner25de4e52006-11-01 18:03:33 +0000120 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
121 /// null/false. When the first accessing function is noticed, it is recorded.
122 /// When a second different accessing function is noticed,
123 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000124 Function *AccessingFunction;
125 bool HasMultipleAccessingFunctions;
126
Chris Lattner25de4e52006-11-01 18:03:33 +0000127 /// HasNonInstructionUser - Set to true if this global has a user that is not
128 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000129 bool HasNonInstructionUser;
130
Chris Lattner25de4e52006-11-01 18:03:33 +0000131 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
132 bool HasPHIUser;
133
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000134 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000135 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner6a93fc02008-01-14 01:32:52 +0000136 HasNonInstructionUser(false), HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000137};
Chris Lattnere47ba742004-10-06 20:57:02 +0000138
Dan Gohman844731a2008-05-13 00:00:25 +0000139}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000140
Jay Foade3acf152009-06-09 21:37:11 +0000141// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
142// by constants itself. Note that constants cannot be cyclic, so this test is
143// pretty easy to implement recursively.
144//
145static bool SafeToDestroyConstant(Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000146 if (isa<GlobalValue>(C)) return false;
147
Devang Patel743cdf82009-03-06 01:37:41 +0000148 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
149 if (Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000150 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000151 } else
152 return false;
153 return true;
154}
155
156
Chris Lattner7a90b682004-10-07 04:16:33 +0000157/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
158/// structure. If the global has its address taken, return true to indicate we
159/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000160///
Chris Lattner7a90b682004-10-07 04:16:33 +0000161static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000162 SmallPtrSet<PHINode*, 16> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000163 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000164 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000165 GS.HasNonInstructionUser = true;
166
Chris Lattner7a90b682004-10-07 04:16:33 +0000167 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Chris Lattner670c8892004-10-08 17:32:09 +0000168
Chris Lattner079236d2004-02-25 21:34:36 +0000169 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000170 if (!GS.HasMultipleAccessingFunctions) {
171 Function *F = I->getParent()->getParent();
172 if (GS.AccessingFunction == 0)
173 GS.AccessingFunction = F;
174 else if (GS.AccessingFunction != F)
175 GS.HasMultipleAccessingFunctions = true;
176 }
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000177 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000178 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000179 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Chris Lattner7a90b682004-10-07 04:16:33 +0000180 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000181 // Don't allow a store OF the address, only stores TO the address.
182 if (SI->getOperand(0) == V) return true;
183
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000184 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
185
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000186 // If this is a direct store to the global (i.e., the global is a scalar
187 // value, not an aggregate), keep more specific information about
188 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000189 if (GS.StoredType != GlobalStatus::isStored) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000190 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000191 Value *StoredVal = SI->getOperand(0);
192 if (StoredVal == GV->getInitializer()) {
193 if (GS.StoredType < GlobalStatus::isInitializerStored)
194 GS.StoredType = GlobalStatus::isInitializerStored;
195 } else if (isa<LoadInst>(StoredVal) &&
196 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
197 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000198 if (GS.StoredType < GlobalStatus::isInitializerStored)
199 GS.StoredType = GlobalStatus::isInitializerStored;
200 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
201 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000202 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000203 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000204 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000205 // noop.
206 } else {
207 GS.StoredType = GlobalStatus::isStored;
208 }
209 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000210 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000211 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000212 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000213 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000214 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000215 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000216 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000217 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
218 // PHI nodes we can check just like select or GEP instructions, but we
219 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000220 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000221 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000222 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000223 } else if (isa<CmpInst>(I)) {
Chris Lattner8e108442009-03-08 03:37:35 +0000224 } else if (isa<MemTransferInst>(I)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000225 if (I->getOperand(1) == V)
226 GS.StoredType = GlobalStatus::isStored;
227 if (I->getOperand(2) == V)
228 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000229 } else if (isa<MemSetInst>(I)) {
230 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
231 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000232 } else {
233 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000234 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000235 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000236 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000237 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000238 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000239 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000240 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000241 GS.HasNonInstructionUser = true;
242 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000243 return true;
244 }
245
246 return false;
247}
248
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000249static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx,
Owen Andersone922c022009-07-22 00:24:57 +0000250 LLVMContext &Context) {
Chris Lattner670c8892004-10-08 17:32:09 +0000251 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
252 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000253 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000254
Chris Lattner670c8892004-10-08 17:32:09 +0000255 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
256 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
257 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
258 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000259 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000260 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000261 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000262 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
263 if (IdxV < STy->getNumElements())
Owen Andersona7235ea2009-07-31 20:28:14 +0000264 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000265 } else if (const SequentialType *STy =
266 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000267 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000268 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000269 } else if (isa<UndefValue>(Agg)) {
270 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
271 if (IdxV < STy->getNumElements())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000272 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000273 } else if (const SequentialType *STy =
274 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000275 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000276 }
Chris Lattner670c8892004-10-08 17:32:09 +0000277 }
278 return 0;
279}
Chris Lattner7a90b682004-10-07 04:16:33 +0000280
Chris Lattner7a90b682004-10-07 04:16:33 +0000281
Chris Lattnere47ba742004-10-06 20:57:02 +0000282/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
283/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000284/// quick scan over the use list to clean up the easy and obvious cruft. This
285/// returns true if it made a change.
Owen Anderson50895512009-07-06 18:42:36 +0000286static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Owen Andersone922c022009-07-22 00:24:57 +0000287 LLVMContext &Context) {
Chris Lattner031955d2004-10-10 16:43:46 +0000288 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000289 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
290 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000291
Chris Lattner7a90b682004-10-07 04:16:33 +0000292 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000293 if (Init) {
294 // Replace the load with the initializer.
295 LI->replaceAllUsesWith(Init);
296 LI->eraseFromParent();
297 Changed = true;
298 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000299 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000300 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000301 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000302 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000303 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
304 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000305 Constant *SubInit = 0;
306 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000307 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Owen Anderson50895512009-07-06 18:42:36 +0000308 Changed |= CleanupConstantGlobalUsers(CE, SubInit, Context);
Reid Spencer3da59db2006-11-27 01:05:10 +0000309 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000310 isa<PointerType>(CE->getType())) {
311 // Pointer cast, delete any stores and memsets to the global.
Owen Anderson50895512009-07-06 18:42:36 +0000312 Changed |= CleanupConstantGlobalUsers(CE, 0, Context);
Chris Lattner35c81b02005-02-27 18:58:52 +0000313 }
314
315 if (CE->use_empty()) {
316 CE->destroyConstant();
317 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000318 }
319 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000320 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
321 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
322 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000323 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000324 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
325 ConstantExpr *CE =
Owen Anderson50895512009-07-06 18:42:36 +0000326 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, Context));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000327 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000328 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000329 }
Owen Anderson50895512009-07-06 18:42:36 +0000330 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, Context);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000331
Chris Lattner031955d2004-10-10 16:43:46 +0000332 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000333 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000334 Changed = true;
335 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000336 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
337 if (MI->getRawDest() == V) {
338 MI->eraseFromParent();
339 Changed = true;
340 }
341
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000342 } else if (Constant *C = dyn_cast<Constant>(U)) {
343 // If we have a chain of dead constantexprs or other things dangling from
344 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000345 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000346 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000347 // This could have invalidated UI, start over from scratch.
Owen Anderson50895512009-07-06 18:42:36 +0000348 CleanupConstantGlobalUsers(V, Init, Context);
Chris Lattner031955d2004-10-10 16:43:46 +0000349 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000350 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000351 }
352 }
Chris Lattner031955d2004-10-10 16:43:46 +0000353 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000354}
355
Chris Lattner941db492008-01-14 02:09:12 +0000356/// isSafeSROAElementUse - Return true if the specified instruction is a safe
357/// user of a derived expression from a global that we want to SROA.
358static bool isSafeSROAElementUse(Value *V) {
359 // We might have a dead and dangling constant hanging off of here.
360 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000361 return SafeToDestroyConstant(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000362
Chris Lattner941db492008-01-14 02:09:12 +0000363 Instruction *I = dyn_cast<Instruction>(V);
364 if (!I) return false;
365
366 // Loads are ok.
367 if (isa<LoadInst>(I)) return true;
368
369 // Stores *to* the pointer are ok.
370 if (StoreInst *SI = dyn_cast<StoreInst>(I))
371 return SI->getOperand(0) != V;
372
373 // Otherwise, it must be a GEP.
374 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
375 if (GEPI == 0) return false;
376
377 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
378 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
379 return false;
380
381 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
382 I != E; ++I)
383 if (!isSafeSROAElementUse(*I))
384 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000385 return true;
386}
387
Chris Lattner941db492008-01-14 02:09:12 +0000388
389/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
390/// Look at it and its uses and decide whether it is safe to SROA this global.
391///
392static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
393 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
394 if (!isa<GetElementPtrInst>(U) &&
395 (!isa<ConstantExpr>(U) ||
396 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
397 return false;
398
399 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
400 // don't like < 3 operand CE's, and we don't like non-constant integer
401 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
402 // value of C.
403 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
404 !cast<Constant>(U->getOperand(1))->isNullValue() ||
405 !isa<ConstantInt>(U->getOperand(2)))
406 return false;
407
408 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
409 ++GEPI; // Skip over the pointer index.
410
411 // If this is a use of an array allocation, do a bit more checking for sanity.
412 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
413 uint64_t NumElements = AT->getNumElements();
414 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
415
416 // Check to make sure that index falls within the array. If not,
417 // something funny is going on, so we won't do the optimization.
418 //
419 if (Idx->getZExtValue() >= NumElements)
420 return false;
421
422 // We cannot scalar repl this level of the array unless any array
423 // sub-indices are in-range constants. In particular, consider:
424 // A[0][i]. We cannot know that the user isn't doing invalid things like
425 // allowing i to index an out-of-range subscript that accesses A[1].
426 //
427 // Scalar replacing *just* the outer index of the array is probably not
428 // going to be a win anyway, so just give up.
429 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000430 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000431 ++GEPI) {
432 uint64_t NumElements;
433 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
434 NumElements = SubArrayTy->getNumElements();
Dan Gohman6874a2a2009-08-18 14:58:19 +0000435 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
436 NumElements = SubVectorTy->getNumElements();
437 else {
438 assert(isa<StructType>(*GEPI) &&
439 "Indexed GEP type is not array, vector, or struct!");
440 continue;
441 }
Chris Lattner941db492008-01-14 02:09:12 +0000442
443 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
444 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
445 return false;
446 }
447 }
448
449 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
450 if (!isSafeSROAElementUse(*I))
451 return false;
452 return true;
453}
454
455/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
456/// is safe for us to perform this transformation.
457///
458static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
459 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
460 UI != E; ++UI) {
461 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
462 return false;
463 }
464 return true;
465}
466
467
Chris Lattner670c8892004-10-08 17:32:09 +0000468/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
469/// variable. This opens the door for other optimizations by exposing the
470/// behavior of the program in a more fine-grained way. We have determined that
471/// this transformation is safe already. We return the first global variable we
472/// insert so that the caller can reprocess it.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000473static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +0000474 LLVMContext &Context) {
Chris Lattner727c2102008-01-14 01:31:05 +0000475 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000476 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000477 return 0;
478
Rafael Espindolabb46f522009-01-15 20:18:42 +0000479 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000480 Constant *Init = GV->getInitializer();
481 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000482
Chris Lattner670c8892004-10-08 17:32:09 +0000483 std::vector<GlobalVariable*> NewGlobals;
484 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
485
Chris Lattner998182b2008-04-26 07:40:11 +0000486 // Get the alignment of the global, either explicit or target-specific.
487 unsigned StartAlignment = GV->getAlignment();
488 if (StartAlignment == 0)
489 StartAlignment = TD.getABITypeAlignment(GV->getType());
490
Chris Lattner670c8892004-10-08 17:32:09 +0000491 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
492 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000493 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000494 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
495 Constant *In = getAggregateConstantElement(Init,
Owen Anderson1d0be152009-08-13 21:58:54 +0000496 ConstantInt::get(Type::getInt32Ty(Context), i),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000497 Context);
Chris Lattner670c8892004-10-08 17:32:09 +0000498 assert(In && "Couldn't get element of initializer?");
Owen Andersone922c022009-07-22 00:24:57 +0000499 GlobalVariable *NGV = new GlobalVariable(Context,
Owen Andersone9b11b42009-07-08 19:03:57 +0000500 STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000501 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000502 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000503 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000504 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000505 Globals.insert(GV, NGV);
506 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000507
508 // Calculate the known alignment of the field. If the original aggregate
509 // had 256 byte alignment for example, something might depend on that:
510 // propagate info to each field.
511 uint64_t FieldOffset = Layout.getElementOffset(i);
512 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
513 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
514 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000515 }
516 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
517 unsigned NumElements = 0;
518 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
519 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000520 else
Chris Lattner998182b2008-04-26 07:40:11 +0000521 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000522
Chris Lattner1f21ef12005-02-23 16:53:04 +0000523 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000524 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000525 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000526
Duncan Sands777d2302009-05-09 07:06:46 +0000527 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000528 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000529 for (unsigned i = 0, e = NumElements; i != e; ++i) {
530 Constant *In = getAggregateConstantElement(Init,
Owen Anderson1d0be152009-08-13 21:58:54 +0000531 ConstantInt::get(Type::getInt32Ty(Context), i),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000532 Context);
Chris Lattner670c8892004-10-08 17:32:09 +0000533 assert(In && "Couldn't get element of initializer?");
534
Owen Andersone922c022009-07-22 00:24:57 +0000535 GlobalVariable *NGV = new GlobalVariable(Context,
Owen Andersone9b11b42009-07-08 19:03:57 +0000536 STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000537 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000538 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000539 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000540 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000541 Globals.insert(GV, NGV);
542 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000543
544 // Calculate the known alignment of the field. If the original aggregate
545 // had 256 byte alignment for example, something might depend on that:
546 // propagate info to each field.
547 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
548 if (NewAlign > EltAlign)
549 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000550 }
551 }
552
553 if (NewGlobals.empty())
554 return 0;
555
Chris Lattnerbdff5482009-08-23 04:37:46 +0000556 DEBUG(errs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000557
Owen Anderson1d0be152009-08-13 21:58:54 +0000558 Constant *NullInt = Constant::getNullValue(Type::getInt32Ty(Context));
Chris Lattner670c8892004-10-08 17:32:09 +0000559
560 // Loop over all of the uses of the global, replacing the constantexpr geps,
561 // with smaller constantexpr geps or direct references.
562 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000563 User *GEP = GV->use_back();
564 assert(((isa<ConstantExpr>(GEP) &&
565 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
566 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000567
Chris Lattner670c8892004-10-08 17:32:09 +0000568 // Ignore the 1th operand, which has to be zero or else the program is quite
569 // broken (undefined). Get the 2nd operand, which is the structure or array
570 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000571 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000572 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
573
Chris Lattner30ba5692004-10-11 05:54:41 +0000574 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000575
576 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000577 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000578 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000579 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000580 Idxs.push_back(NullInt);
581 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
582 Idxs.push_back(CE->getOperand(i));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000583 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000584 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000585 } else {
586 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000587 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000588 Idxs.push_back(NullInt);
589 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
590 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000591 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000592 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000593 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000594 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000595 GEP->replaceAllUsesWith(NewPtr);
596
597 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000598 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000599 else
600 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000601 }
602
Chris Lattnere40e2d12004-10-08 20:25:55 +0000603 // Delete the old global, now that it is dead.
604 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000605 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000606
607 // Loop over the new globals array deleting any globals that are obviously
608 // dead. This can arise due to scalarization of a structure or an array that
609 // has elements that are dead.
610 unsigned FirstGlobal = 0;
611 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
612 if (NewGlobals[i]->use_empty()) {
613 Globals.erase(NewGlobals[i]);
614 if (FirstGlobal == i) ++FirstGlobal;
615 }
616
617 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000618}
619
Chris Lattner9b34a612004-10-09 21:48:45 +0000620/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000621/// value will trap if the value is dynamically null. PHIs keeps track of any
622/// phi nodes we've seen to avoid reprocessing them.
623static bool AllUsesOfValueWillTrapIfNull(Value *V,
624 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000625 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
626 if (isa<LoadInst>(*UI)) {
627 // Will trap.
628 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
629 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000630 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000631 return false; // Storing the value.
632 }
633 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
634 if (CI->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000635 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000636 return false; // Not calling the ptr
637 }
638 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
639 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000640 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000641 return false; // Not calling the ptr
642 }
Chris Lattner81686182007-09-13 16:30:19 +0000643 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
644 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000645 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000646 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
647 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
648 // If we've already seen this phi node, ignore it, it has already been
649 // checked.
650 if (PHIs.insert(PN))
651 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000652 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000653 isa<ConstantPointerNull>(UI->getOperand(1))) {
654 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000655 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000656 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000657 return false;
658 }
659 return true;
660}
661
662/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000663/// from GV will trap if the loaded value is null. Note that this also permits
664/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000665static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
666 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
667 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000668 SmallPtrSet<PHINode*, 8> PHIs;
669 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000670 return false;
671 } else if (isa<StoreInst>(*UI)) {
672 // Ignore stores to the global.
673 } else {
674 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000675 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000676 return false;
677 }
678
679 return true;
680}
681
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000682static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
Owen Andersone922c022009-07-22 00:24:57 +0000683 LLVMContext &Context) {
Chris Lattner708148e2004-10-10 23:14:11 +0000684 bool Changed = false;
685 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
686 Instruction *I = cast<Instruction>(*UI++);
687 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
688 LI->setOperand(0, NewV);
689 Changed = true;
690 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
691 if (SI->getOperand(1) == V) {
692 SI->setOperand(1, NewV);
693 Changed = true;
694 }
695 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
696 if (I->getOperand(0) == V) {
697 // Calling through the pointer! Turn into a direct call, but be careful
698 // that the pointer is not also being passed as an argument.
699 I->setOperand(0, NewV);
700 Changed = true;
701 bool PassedAsArg = false;
702 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
703 if (I->getOperand(i) == V) {
704 PassedAsArg = true;
705 I->setOperand(i, NewV);
706 }
707
708 if (PassedAsArg) {
709 // Being passed as an argument also. Be careful to not invalidate UI!
710 UI = V->use_begin();
711 }
712 }
713 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
714 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000715 ConstantExpr::getCast(CI->getOpcode(),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000716 NewV, CI->getType()), Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000717 if (CI->use_empty()) {
718 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000719 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000720 }
721 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
722 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000723 SmallVector<Constant*, 8> Idxs;
724 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000725 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
726 i != e; ++i)
727 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000728 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000729 else
730 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000731 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000732 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000733 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000734 Idxs.size()), Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000735 if (GEPI->use_empty()) {
736 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000737 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000738 }
739 }
740 }
741
742 return Changed;
743}
744
745
746/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
747/// value stored into it. If there are uses of the loaded value that would trap
748/// if the loaded value is dynamically null, then we know that they cannot be
749/// reachable with a null optimize away the load.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000750static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Owen Andersone922c022009-07-22 00:24:57 +0000751 LLVMContext &Context) {
Chris Lattner708148e2004-10-10 23:14:11 +0000752 bool Changed = false;
753
Chris Lattner92c6bd22009-01-14 00:12:58 +0000754 // Keep track of whether we are able to remove all the uses of the global
755 // other than the store that defines it.
756 bool AllNonStoreUsesGone = true;
757
Chris Lattner708148e2004-10-10 23:14:11 +0000758 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000759 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
760 User *GlobalUser = *GUI++;
761 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000762 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000763 // If we were able to delete all uses of the loads
764 if (LI->use_empty()) {
765 LI->eraseFromParent();
766 Changed = true;
767 } else {
768 AllNonStoreUsesGone = false;
769 }
770 } else if (isa<StoreInst>(GlobalUser)) {
771 // Ignore the store that stores "LV" to the global.
772 assert(GlobalUser->getOperand(1) == GV &&
773 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000774 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000775 AllNonStoreUsesGone = false;
776
777 // If we get here we could have other crazy uses that are transitively
778 // loaded.
779 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
780 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000781 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000782 }
Chris Lattner708148e2004-10-10 23:14:11 +0000783
784 if (Changed) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000785 DEBUG(errs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000786 ++NumGlobUses;
787 }
788
Chris Lattner708148e2004-10-10 23:14:11 +0000789 // If we nuked all of the loads, then none of the stores are needed either,
790 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000791 if (AllNonStoreUsesGone) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000792 DEBUG(errs() << " *** GLOBAL NOW DEAD!\n");
Owen Anderson50895512009-07-06 18:42:36 +0000793 CleanupConstantGlobalUsers(GV, 0, Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000794 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000795 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000796 ++NumDeleted;
797 }
798 Changed = true;
799 }
800 return Changed;
801}
802
Chris Lattner30ba5692004-10-11 05:54:41 +0000803/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
804/// instructions that are foldable.
Owen Andersone922c022009-07-22 00:24:57 +0000805static void ConstantPropUsersOf(Value *V, LLVMContext &Context) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000806 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
807 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Owen Anderson50895512009-07-06 18:42:36 +0000808 if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000809 I->replaceAllUsesWith(NewC);
810
Chris Lattnerd514d822005-02-01 01:23:31 +0000811 // Advance UI to the next non-I use to avoid invalidating it!
812 // Instructions could multiply use V.
813 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000814 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000815 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000816 }
817}
818
819/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
820/// variable, and transforms the program as if it always contained the result of
821/// the specified malloc. Because it is always the result of the specified
822/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000823/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000824static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000825 MallocInst *MI,
Owen Andersone922c022009-07-22 00:24:57 +0000826 LLVMContext &Context) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000827 DEBUG(errs() << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000828 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
829
Reid Spencerb83eb642006-10-20 07:07:24 +0000830 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000831 // If we have an array allocation, transform it to a single element
832 // allocation to make the code below simpler.
Owen Andersondebcb012009-07-29 22:17:13 +0000833 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000834 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000835 MallocInst *NewMI =
Owen Anderson1d0be152009-08-13 21:58:54 +0000836 new MallocInst(NewTy, Constant::getNullValue(Type::getInt32Ty(Context)),
Nate Begeman14b05292005-11-05 09:21:28 +0000837 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000838 Value* Indices[2];
Owen Anderson1d0be152009-08-13 21:58:54 +0000839 Indices[0] = Indices[1] = Constant::getNullValue(Type::getInt32Ty(Context));
Gabor Greif051a9502008-04-06 20:25:17 +0000840 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
841 NewMI->getName()+".el0", MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000842 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000843 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000844 MI = NewMI;
845 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000846
Chris Lattner7a7ed022004-10-16 18:09:00 +0000847 // Create the new global variable. The contents of the malloc'd memory is
848 // undefined, so initialize with an undef value.
Chris Lattner998182b2008-04-26 07:40:11 +0000849 // FIXME: This new global should have the alignment returned by malloc. Code
850 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
851 // this would only guarantee some lower alignment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000852 Constant *Init = UndefValue::get(MI->getAllocatedType());
Owen Andersone9b11b42009-07-08 19:03:57 +0000853 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
854 MI->getAllocatedType(), false,
855 GlobalValue::InternalLinkage, Init,
856 GV->getName()+".body",
857 GV,
858 GV->isThreadLocal());
859
Chris Lattner30ba5692004-10-11 05:54:41 +0000860 // Anything that used the malloc now uses the global directly.
861 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000862
863 Constant *RepValue = NewGV;
864 if (NewGV->getType() != GV->getType()->getElementType())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000865 RepValue = ConstantExpr::getBitCast(RepValue,
Reid Spencerd977d862006-12-12 23:36:14 +0000866 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000867
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000868 // If there is a comparison against null, we will insert a global bool to
869 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000870 GlobalVariable *InitBool =
Owen Anderson1d0be152009-08-13 21:58:54 +0000871 new GlobalVariable(Context, Type::getInt1Ty(Context), false,
Owen Anderson3d29df32009-07-08 01:26:06 +0000872 GlobalValue::InternalLinkage,
Owen Anderson5defacc2009-07-31 17:39:07 +0000873 ConstantInt::getFalse(Context), GV->getName()+".init",
Owen Andersone9b11b42009-07-08 19:03:57 +0000874 GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000875 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000876
Chris Lattner30ba5692004-10-11 05:54:41 +0000877 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000878 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000879 while (!GV->use_empty())
880 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000881 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000882 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000883 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000884 LoadUse = RepValue;
885 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000886 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
887 // Replace the cmp X, 0 with a use of the bool value.
888 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000889 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000890 switch (CI->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000891 default: llvm_unreachable("Unknown ICmp Predicate!");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000892 case ICmpInst::ICMP_ULT:
893 case ICmpInst::ICMP_SLT:
Owen Anderson5defacc2009-07-31 17:39:07 +0000894 LV = ConstantInt::getFalse(Context); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000895 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000896 case ICmpInst::ICMP_ULE:
897 case ICmpInst::ICMP_SLE:
898 case ICmpInst::ICMP_EQ:
Dan Gohman4ae51262009-08-12 16:23:25 +0000899 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000900 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000901 case ICmpInst::ICMP_NE:
902 case ICmpInst::ICMP_UGE:
903 case ICmpInst::ICMP_SGE:
904 case ICmpInst::ICMP_UGT:
905 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000906 break; // no change.
907 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000908 CI->replaceAllUsesWith(LV);
909 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000910 }
911 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000912 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000913 } else {
914 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000915 // The global is initialized when the store to it occurs.
Owen Anderson5defacc2009-07-31 17:39:07 +0000916 new StoreInst(ConstantInt::getTrue(Context), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000917 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000918 }
919
Chris Lattnerbc965b92004-12-02 06:25:58 +0000920 // If the initialization boolean was used, insert it, otherwise delete it.
921 if (!InitBoolUsed) {
922 while (!InitBool->use_empty()) // Delete initializations
923 cast<Instruction>(InitBool->use_back())->eraseFromParent();
924 delete InitBool;
925 } else
926 GV->getParent()->getGlobalList().insert(GV, InitBool);
927
928
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000929 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000930 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000931 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000932
933 // To further other optimizations, loop over all users of NewGV and try to
934 // constant prop them. This will promote GEP instructions with constant
935 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Owen Anderson50895512009-07-06 18:42:36 +0000936 ConstantPropUsersOf(NewGV, Context);
Chris Lattner30ba5692004-10-11 05:54:41 +0000937 if (RepValue != NewGV)
Owen Anderson50895512009-07-06 18:42:36 +0000938 ConstantPropUsersOf(RepValue, Context);
Chris Lattner30ba5692004-10-11 05:54:41 +0000939
940 return NewGV;
941}
Chris Lattner708148e2004-10-10 23:14:11 +0000942
Victor Hernandez83d63912009-09-18 22:35:49 +0000943/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
944/// variable, and transforms the program as if it always contained the result of
945/// the specified malloc. Because it is always the result of the specified
946/// malloc, there is no reason to actually DO the malloc. Instead, turn the
947/// malloc into a global, and any loads of GV as uses of the new global.
948static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
949 CallInst *CI,
950 BitCastInst *BCI,
951 LLVMContext &Context,
952 TargetData* TD) {
Victor Hernandez2491ce02009-10-15 20:14:52 +0000953 DEBUG(errs() << "PROMOTING MALLOC GLOBAL: " << *GV
954 << " CALL = " << *CI << " BCI = " << *BCI << '\n');
955
Victor Hernandez83d63912009-09-18 22:35:49 +0000956 const Type *IntPtrTy = TD->getIntPtrType(Context);
957
Victor Hernandez2491ce02009-10-15 20:14:52 +0000958 Value* ArraySize = getMallocArraySize(CI, Context, TD);
959 assert(ArraySize && "not a malloc whose array size can be determined");
960 ConstantInt *NElements = cast<ConstantInt>(ArraySize);
Victor Hernandez83d63912009-09-18 22:35:49 +0000961 if (NElements->getZExtValue() != 1) {
962 // If we have an array allocation, transform it to a single element
963 // allocation to make the code below simpler.
964 Type *NewTy = ArrayType::get(getMallocAllocatedType(CI),
965 NElements->getZExtValue());
966 Value* NewM = CallInst::CreateMalloc(CI, IntPtrTy, NewTy);
967 Instruction* NewMI = cast<Instruction>(NewM);
968 Value* Indices[2];
969 Indices[0] = Indices[1] = Constant::getNullValue(IntPtrTy);
970 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
971 NewMI->getName()+".el0", CI);
972 BCI->replaceAllUsesWith(NewGEP);
973 BCI->eraseFromParent();
974 CI->eraseFromParent();
975 BCI = cast<BitCastInst>(NewMI);
976 CI = extractMallocCallFromBitCast(NewMI);
977 }
978
979 // Create the new global variable. The contents of the malloc'd memory is
980 // undefined, so initialize with an undef value.
Victor Hernandez83d63912009-09-18 22:35:49 +0000981 const Type *MAT = getMallocAllocatedType(CI);
982 Constant *Init = UndefValue::get(MAT);
983 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
984 MAT, false,
985 GlobalValue::InternalLinkage, Init,
986 GV->getName()+".body",
987 GV,
988 GV->isThreadLocal());
989
990 // Anything that used the malloc now uses the global directly.
991 BCI->replaceAllUsesWith(NewGV);
992
993 Constant *RepValue = NewGV;
994 if (NewGV->getType() != GV->getType()->getElementType())
995 RepValue = ConstantExpr::getBitCast(RepValue,
996 GV->getType()->getElementType());
997
998 // If there is a comparison against null, we will insert a global bool to
999 // keep track of whether the global was initialized yet or not.
1000 GlobalVariable *InitBool =
1001 new GlobalVariable(Context, Type::getInt1Ty(Context), false,
1002 GlobalValue::InternalLinkage,
1003 ConstantInt::getFalse(Context), GV->getName()+".init",
1004 GV->isThreadLocal());
1005 bool InitBoolUsed = false;
1006
1007 // Loop over all uses of GV, processing them in turn.
1008 std::vector<StoreInst*> Stores;
1009 while (!GV->use_empty())
1010 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1011 while (!LI->use_empty()) {
1012 Use &LoadUse = LI->use_begin().getUse();
1013 if (!isa<ICmpInst>(LoadUse.getUser()))
1014 LoadUse = RepValue;
1015 else {
1016 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1017 // Replace the cmp X, 0 with a use of the bool value.
1018 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
1019 InitBoolUsed = true;
1020 switch (ICI->getPredicate()) {
1021 default: llvm_unreachable("Unknown ICmp Predicate!");
1022 case ICmpInst::ICMP_ULT:
1023 case ICmpInst::ICMP_SLT:
1024 LV = ConstantInt::getFalse(Context); // X < null -> always false
1025 break;
1026 case ICmpInst::ICMP_ULE:
1027 case ICmpInst::ICMP_SLE:
1028 case ICmpInst::ICMP_EQ:
1029 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1030 break;
1031 case ICmpInst::ICMP_NE:
1032 case ICmpInst::ICMP_UGE:
1033 case ICmpInst::ICMP_SGE:
1034 case ICmpInst::ICMP_UGT:
1035 case ICmpInst::ICMP_SGT:
1036 break; // no change.
1037 }
1038 ICI->replaceAllUsesWith(LV);
1039 ICI->eraseFromParent();
1040 }
1041 }
1042 LI->eraseFromParent();
1043 } else {
1044 StoreInst *SI = cast<StoreInst>(GV->use_back());
1045 // The global is initialized when the store to it occurs.
1046 new StoreInst(ConstantInt::getTrue(Context), InitBool, SI);
1047 SI->eraseFromParent();
1048 }
1049
1050 // If the initialization boolean was used, insert it, otherwise delete it.
1051 if (!InitBoolUsed) {
1052 while (!InitBool->use_empty()) // Delete initializations
1053 cast<Instruction>(InitBool->use_back())->eraseFromParent();
1054 delete InitBool;
1055 } else
1056 GV->getParent()->getGlobalList().insert(GV, InitBool);
1057
1058
1059 // Now the GV is dead, nuke it and the malloc.
1060 GV->eraseFromParent();
1061 BCI->eraseFromParent();
1062 CI->eraseFromParent();
1063
1064 // To further other optimizations, loop over all users of NewGV and try to
1065 // constant prop them. This will promote GEP instructions with constant
1066 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
1067 ConstantPropUsersOf(NewGV, Context);
1068 if (RepValue != NewGV)
1069 ConstantPropUsersOf(RepValue, Context);
1070
1071 return NewGV;
1072}
1073
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001074/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1075/// to make sure that there are no complex uses of V. We permit simple things
1076/// like dereferencing the pointer, but not storing through the address, unless
1077/// it is to the specified global.
1078static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001079 GlobalVariable *GV,
1080 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001081 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foad0906b1b2009-06-06 17:49:35 +00001082 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001083
1084 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1085 continue; // Fine, ignore.
1086 }
1087
1088 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001089 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1090 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001091 continue; // Otherwise, storing through it, or storing into GV... fine.
1092 }
1093
1094 if (isa<GetElementPtrInst>(Inst)) {
1095 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001096 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001097 continue;
1098 }
1099
1100 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001101 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1102 // cycles.
1103 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001104 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1105 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001106 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001107 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001108
1109 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
1110 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1111 return false;
1112 continue;
1113 }
1114
1115 return false;
1116 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001117 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001118}
1119
Chris Lattner86395032006-09-30 23:32:09 +00001120/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1121/// somewhere. Transform all uses of the allocation into loads from the
1122/// global and uses of the resultant pointer. Further, delete the store into
1123/// GV. This assumes that these value pass the
1124/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1125static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1126 GlobalVariable *GV) {
1127 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001128 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1129 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001130 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1131 // If this is the store of the allocation into the global, remove it.
1132 if (SI->getOperand(1) == GV) {
1133 SI->eraseFromParent();
1134 continue;
1135 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001136 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1137 // Insert the load in the corresponding predecessor, not right before the
1138 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001139 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001140 } else if (isa<BitCastInst>(U)) {
1141 // Must be bitcast between the malloc and store to initialize the global.
1142 ReplaceUsesOfMallocWithGlobal(U, GV);
1143 U->eraseFromParent();
1144 continue;
1145 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1146 // If this is a "GEP bitcast" and the user is a store to the global, then
1147 // just process it as a bitcast.
1148 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1149 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1150 if (SI->getOperand(1) == GV) {
1151 // Must be bitcast GEP between the malloc and store to initialize
1152 // the global.
1153 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1154 GEPI->eraseFromParent();
1155 continue;
1156 }
Chris Lattner86395032006-09-30 23:32:09 +00001157 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001158
Chris Lattner86395032006-09-30 23:32:09 +00001159 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001160 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001161 U->replaceUsesOfWith(Alloc, NL);
1162 }
1163}
1164
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001165/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1166/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1167/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001168static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Cheng5d163962009-06-02 00:56:07 +00001169 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1170 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001171 // We permit two users of the load: setcc comparing against the null
1172 // pointer, and a getelementptr of a specific form.
1173 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1174 Instruction *User = cast<Instruction>(*UI);
1175
1176 // Comparison against null is ok.
1177 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1178 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1179 return false;
1180 continue;
1181 }
1182
1183 // getelementptr is also ok, but only a simple form.
1184 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1185 // Must index into the array and into the struct.
1186 if (GEPI->getNumOperands() < 3)
1187 return false;
1188
1189 // Otherwise the GEP is ok.
1190 continue;
1191 }
1192
1193 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001194 if (!LoadUsingPHIsPerLoad.insert(PN))
1195 // This means some phi nodes are dependent on each other.
1196 // Avoid infinite looping!
1197 return false;
1198 if (!LoadUsingPHIs.insert(PN))
1199 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001200 continue;
1201
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001202 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001203 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1204 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001205 return false;
1206
1207 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001208 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001209
1210 // Otherwise we don't know what this is, not ok.
1211 return false;
1212 }
1213
1214 return true;
1215}
1216
1217
1218/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1219/// GV are simple enough to perform HeapSRA, return true.
1220static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001221 Instruction *StoredVal) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001222 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Cheng5d163962009-06-02 00:56:07 +00001223 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001224 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1225 ++UI)
Evan Cheng5d163962009-06-02 00:56:07 +00001226 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1227 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1228 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001229 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001230 LoadUsingPHIsPerLoad.clear();
1231 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001232
1233 // If we reach here, we know that all uses of the loads and transitive uses
1234 // (through PHI nodes) are simple enough to transform. However, we don't know
1235 // that all inputs the to the PHI nodes are in the same equivalence sets.
1236 // Check to verify that all operands of the PHIs are either PHIS that can be
1237 // transformed, loads from GV, or MI itself.
1238 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1239 E = LoadUsingPHIs.end(); I != E; ++I) {
1240 PHINode *PN = *I;
1241 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1242 Value *InVal = PN->getIncomingValue(op);
1243
1244 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001245 if (InVal == StoredVal) continue;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001246
1247 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1248 // One of the PHIs in our set is (optimistically) ok.
1249 if (LoadUsingPHIs.count(InPN))
1250 continue;
1251 return false;
1252 }
1253
1254 // Load from GV is ok.
1255 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1256 if (LI->getOperand(0) == GV)
1257 continue;
1258
1259 // UNDEF? NULL?
1260
1261 // Anything else is rejected.
1262 return false;
1263 }
1264 }
1265
Chris Lattner86395032006-09-30 23:32:09 +00001266 return true;
1267}
1268
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001269static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1270 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001271 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Andersone922c022009-07-22 00:24:57 +00001272 LLVMContext &Context) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001273 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1274
1275 if (FieldNo >= FieldVals.size())
1276 FieldVals.resize(FieldNo+1);
1277
1278 // If we already have this value, just reuse the previously scalarized
1279 // version.
1280 if (Value *FieldVal = FieldVals[FieldNo])
1281 return FieldVal;
1282
1283 // Depending on what instruction this is, we have several cases.
1284 Value *Result;
1285 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1286 // This is a scalarized version of the load from the global. Just create
1287 // a new Load of the scalarized global.
1288 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1289 InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001290 PHIsToRewrite, Context),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001291 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001292 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1293 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1294 // field.
1295 const StructType *ST =
1296 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1297
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001298 Result =
Owen Andersondebcb012009-07-29 22:17:13 +00001299 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001300 PN->getName()+".f"+Twine(FieldNo), PN);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001301 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1302 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001303 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001304 Result = 0;
1305 }
1306
1307 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001308}
1309
Chris Lattner330245e2007-09-13 17:29:05 +00001310/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1311/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001312static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1313 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001314 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Andersone922c022009-07-22 00:24:57 +00001315 LLVMContext &Context) {
Chris Lattner330245e2007-09-13 17:29:05 +00001316 // If this is a comparison against null, handle it.
1317 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1318 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1319 // If we have a setcc of the loaded pointer, we can use a setcc of any
1320 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001321 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001322 InsertedScalarizedValues, PHIsToRewrite,
1323 Context);
Chris Lattner330245e2007-09-13 17:29:05 +00001324
Owen Anderson333c4002009-07-09 23:48:35 +00001325 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Owen Andersona7235ea2009-07-31 20:28:14 +00001326 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001327 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001328 SCI->replaceAllUsesWith(New);
1329 SCI->eraseFromParent();
1330 return;
1331 }
1332
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001333 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001334 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1335 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1336 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001337
Chris Lattnera637a8b2007-09-13 18:00:31 +00001338 // Load the pointer for this field.
1339 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001340 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001341 InsertedScalarizedValues, PHIsToRewrite,
1342 Context);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001343
1344 // Create the new GEP idx vector.
1345 SmallVector<Value*, 8> GEPIdx;
1346 GEPIdx.push_back(GEPI->getOperand(1));
1347 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1348
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001349 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1350 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001351 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001352 GEPI->replaceAllUsesWith(NGEPI);
1353 GEPI->eraseFromParent();
1354 return;
1355 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001356
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001357 // Recursively transform the users of PHI nodes. This will lazily create the
1358 // PHIs that are needed for individual elements. Keep track of what PHIs we
1359 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1360 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1361 // already been seen first by another load, so its uses have already been
1362 // processed.
1363 PHINode *PN = cast<PHINode>(LoadUser);
1364 bool Inserted;
1365 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1366 tie(InsertPos, Inserted) =
1367 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1368 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001369
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001370 // If this is the first time we've seen this PHI, recursively process all
1371 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001372 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1373 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001374 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1375 Context);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001376 }
Chris Lattner330245e2007-09-13 17:29:05 +00001377}
1378
Chris Lattner86395032006-09-30 23:32:09 +00001379/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1380/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1381/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001382/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001383static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001384 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001385 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Andersone922c022009-07-22 00:24:57 +00001386 LLVMContext &Context) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001387 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001388 UI != E; ) {
1389 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001390 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1391 Context);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001392 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001393
1394 if (Load->use_empty()) {
1395 Load->eraseFromParent();
1396 InsertedScalarizedValues.erase(Load);
1397 }
Chris Lattner86395032006-09-30 23:32:09 +00001398}
1399
1400/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1401/// it up into multiple allocations of arrays of the fields.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001402static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI,
Owen Andersone922c022009-07-22 00:24:57 +00001403 LLVMContext &Context){
Chris Lattnerbdff5482009-08-23 04:37:46 +00001404 DEBUG(errs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI);
Chris Lattner86395032006-09-30 23:32:09 +00001405 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1406
1407 // There is guaranteed to be at least one use of the malloc (storing
1408 // it into GV). If there are other uses, change them to be uses of
1409 // the global to simplify later code. This also deletes the store
1410 // into GV.
1411 ReplaceUsesOfMallocWithGlobal(MI, GV);
1412
1413 // Okay, at this point, there are no users of the malloc. Insert N
1414 // new mallocs at the same place as MI, and N globals.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001415 std::vector<Value*> FieldGlobals;
Chris Lattner86395032006-09-30 23:32:09 +00001416 std::vector<MallocInst*> FieldMallocs;
1417
1418 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1419 const Type *FieldTy = STy->getElementType(FieldNo);
Owen Andersondebcb012009-07-29 22:17:13 +00001420 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001421
1422 GlobalVariable *NGV =
Owen Andersone9b11b42009-07-08 19:03:57 +00001423 new GlobalVariable(*GV->getParent(),
1424 PFieldTy, false, GlobalValue::InternalLinkage,
Owen Andersona7235ea2009-07-31 20:28:14 +00001425 Constant::getNullValue(PFieldTy),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001426 GV->getName() + ".f" + Twine(FieldNo), GV,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001427 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001428 FieldGlobals.push_back(NGV);
1429
Owen Anderson50dead02009-07-15 23:53:25 +00001430 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001431 MI->getName() + ".f" + Twine(FieldNo), MI);
Chris Lattner86395032006-09-30 23:32:09 +00001432 FieldMallocs.push_back(NMI);
1433 new StoreInst(NMI, NGV, MI);
1434 }
1435
1436 // The tricky aspect of this transformation is handling the case when malloc
1437 // fails. In the original code, malloc failing would set the result pointer
1438 // of malloc to null. In this case, some mallocs could succeed and others
1439 // could fail. As such, we emit code that looks like this:
1440 // F0 = malloc(field0)
1441 // F1 = malloc(field1)
1442 // F2 = malloc(field2)
1443 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1444 // if (F0) { free(F0); F0 = 0; }
1445 // if (F1) { free(F1); F1 = 0; }
1446 // if (F2) { free(F2); F2 = 0; }
1447 // }
1448 Value *RunningOr = 0;
1449 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Owen Anderson333c4002009-07-09 23:48:35 +00001450 Value *Cond = new ICmpInst(MI, ICmpInst::ICMP_EQ, FieldMallocs[i],
Owen Andersona7235ea2009-07-31 20:28:14 +00001451 Constant::getNullValue(FieldMallocs[i]->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001452 "isnull");
Chris Lattner86395032006-09-30 23:32:09 +00001453 if (!RunningOr)
1454 RunningOr = Cond; // First seteq
1455 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001456 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Chris Lattner86395032006-09-30 23:32:09 +00001457 }
1458
1459 // Split the basic block at the old malloc.
1460 BasicBlock *OrigBB = MI->getParent();
1461 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1462
1463 // Create the block to check the first condition. Put all these blocks at the
1464 // end of the function as they are unlikely to be executed.
Owen Anderson1d0be152009-08-13 21:58:54 +00001465 BasicBlock *NullPtrBlock = BasicBlock::Create(Context, "malloc_ret_null",
Gabor Greif051a9502008-04-06 20:25:17 +00001466 OrigBB->getParent());
Chris Lattner86395032006-09-30 23:32:09 +00001467
1468 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1469 // branch on RunningOr.
1470 OrigBB->getTerminator()->eraseFromParent();
Gabor Greif051a9502008-04-06 20:25:17 +00001471 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Chris Lattner86395032006-09-30 23:32:09 +00001472
1473 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1474 // pointer, because some may be null while others are not.
1475 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1476 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Owen Anderson333c4002009-07-09 23:48:35 +00001477 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00001478 Constant::getNullValue(GVVal->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001479 "tmp");
Owen Anderson1d0be152009-08-13 21:58:54 +00001480 BasicBlock *FreeBlock = BasicBlock::Create(Context, "free_it",
1481 OrigBB->getParent());
1482 BasicBlock *NextBlock = BasicBlock::Create(Context, "next",
1483 OrigBB->getParent());
Gabor Greif051a9502008-04-06 20:25:17 +00001484 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001485
1486 // Fill in FreeBlock.
1487 new FreeInst(GVVal, FreeBlock);
Owen Andersona7235ea2009-07-31 20:28:14 +00001488 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
Chris Lattner86395032006-09-30 23:32:09 +00001489 FreeBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001490 BranchInst::Create(NextBlock, FreeBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001491
1492 NullPtrBlock = NextBlock;
1493 }
1494
Gabor Greif051a9502008-04-06 20:25:17 +00001495 BranchInst::Create(ContBB, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001496
1497 // MI is no longer needed, remove it.
1498 MI->eraseFromParent();
1499
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001500 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1501 /// update all uses of the load, keep track of what scalarized loads are
1502 /// inserted for a given load.
1503 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1504 InsertedScalarizedValues[GV] = FieldGlobals;
1505
1506 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Chris Lattner86395032006-09-30 23:32:09 +00001507
1508 // Okay, the malloc site is completely handled. All of the uses of GV are now
1509 // loads, and all uses of those loads are simple. Rewrite them to use loads
1510 // of the per-field globals instead.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001511 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1512 Instruction *User = cast<Instruction>(*UI++);
1513
1514 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001515 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1516 Context);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001517 continue;
Chris Lattner39ff1e22007-01-09 23:29:37 +00001518 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001519
1520 // Must be a store of null.
1521 StoreInst *SI = cast<StoreInst>(User);
1522 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1523 "Unexpected heap-sra user!");
1524
1525 // Insert a store of null into each global.
1526 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1527 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Owen Andersona7235ea2009-07-31 20:28:14 +00001528 Constant *Null = Constant::getNullValue(PT->getElementType());
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001529 new StoreInst(Null, FieldGlobals[i], SI);
1530 }
1531 // Erase the original store.
1532 SI->eraseFromParent();
Chris Lattner86395032006-09-30 23:32:09 +00001533 }
1534
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001535 // While we have PHIs that are interesting to rewrite, do it.
1536 while (!PHIsToRewrite.empty()) {
1537 PHINode *PN = PHIsToRewrite.back().first;
1538 unsigned FieldNo = PHIsToRewrite.back().second;
1539 PHIsToRewrite.pop_back();
1540 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1541 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1542
1543 // Add all the incoming values. This can materialize more phis.
1544 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1545 Value *InVal = PN->getIncomingValue(i);
1546 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001547 PHIsToRewrite, Context);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001548 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1549 }
1550 }
1551
1552 // Drop all inter-phi links and any loads that made it this far.
1553 for (DenseMap<Value*, std::vector<Value*> >::iterator
1554 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1555 I != E; ++I) {
1556 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1557 PN->dropAllReferences();
1558 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1559 LI->dropAllReferences();
1560 }
1561
1562 // Delete all the phis and loads now that inter-references are dead.
1563 for (DenseMap<Value*, std::vector<Value*> >::iterator
1564 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1565 I != E; ++I) {
1566 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1567 PN->eraseFromParent();
1568 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1569 LI->eraseFromParent();
1570 }
1571
Chris Lattner86395032006-09-30 23:32:09 +00001572 // The old global is now dead, remove it.
1573 GV->eraseFromParent();
1574
1575 ++NumHeapSRA;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001576 return cast<GlobalVariable>(FieldGlobals[0]);
Chris Lattner86395032006-09-30 23:32:09 +00001577}
1578
Victor Hernandez83d63912009-09-18 22:35:49 +00001579/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1580/// it up into multiple allocations of arrays of the fields.
1581static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV,
1582 CallInst *CI, BitCastInst* BCI,
1583 LLVMContext &Context,
1584 TargetData *TD){
1585 DEBUG(errs() << "SROA HEAP ALLOC: " << *GV << " MALLOC CALL = " << *CI
1586 << " BITCAST = " << *BCI << '\n');
1587 const Type* MAT = getMallocAllocatedType(CI);
1588 const StructType *STy = cast<StructType>(MAT);
Victor Hernandez8db42d22009-10-16 23:12:25 +00001589 Value* ArraySize = getMallocArraySize(CI, Context, TD);
1590 assert(ArraySize && "not a malloc whose array size can be determined");
Victor Hernandez83d63912009-09-18 22:35:49 +00001591
1592 // There is guaranteed to be at least one use of the malloc (storing
1593 // it into GV). If there are other uses, change them to be uses of
1594 // the global to simplify later code. This also deletes the store
1595 // into GV.
1596 ReplaceUsesOfMallocWithGlobal(BCI, GV);
1597
1598 // Okay, at this point, there are no users of the malloc. Insert N
1599 // new mallocs at the same place as CI, and N globals.
1600 std::vector<Value*> FieldGlobals;
1601 std::vector<Value*> FieldMallocs;
1602
1603 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1604 const Type *FieldTy = STy->getElementType(FieldNo);
1605 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1606
1607 GlobalVariable *NGV =
1608 new GlobalVariable(*GV->getParent(),
1609 PFieldTy, false, GlobalValue::InternalLinkage,
1610 Constant::getNullValue(PFieldTy),
1611 GV->getName() + ".f" + Twine(FieldNo), GV,
1612 GV->isThreadLocal());
1613 FieldGlobals.push_back(NGV);
1614
Victor Hernandez8db42d22009-10-16 23:12:25 +00001615 Value *NMI = CallInst::CreateMalloc(CI, TD->getIntPtrType(Context),
1616 FieldTy, ArraySize,
Victor Hernandez83d63912009-09-18 22:35:49 +00001617 BCI->getName() + ".f" + Twine(FieldNo));
1618 FieldMallocs.push_back(NMI);
1619 new StoreInst(NMI, NGV, BCI);
1620 }
1621
1622 // The tricky aspect of this transformation is handling the case when malloc
1623 // fails. In the original code, malloc failing would set the result pointer
1624 // of malloc to null. In this case, some mallocs could succeed and others
1625 // could fail. As such, we emit code that looks like this:
1626 // F0 = malloc(field0)
1627 // F1 = malloc(field1)
1628 // F2 = malloc(field2)
1629 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1630 // if (F0) { free(F0); F0 = 0; }
1631 // if (F1) { free(F1); F1 = 0; }
1632 // if (F2) { free(F2); F2 = 0; }
1633 // }
1634 Value *RunningOr = 0;
1635 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1636 Value *Cond = new ICmpInst(BCI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1637 Constant::getNullValue(FieldMallocs[i]->getType()),
1638 "isnull");
1639 if (!RunningOr)
1640 RunningOr = Cond; // First seteq
1641 else
1642 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", BCI);
1643 }
1644
1645 // Split the basic block at the old malloc.
1646 BasicBlock *OrigBB = BCI->getParent();
1647 BasicBlock *ContBB = OrigBB->splitBasicBlock(BCI, "malloc_cont");
1648
1649 // Create the block to check the first condition. Put all these blocks at the
1650 // end of the function as they are unlikely to be executed.
1651 BasicBlock *NullPtrBlock = BasicBlock::Create(Context, "malloc_ret_null",
1652 OrigBB->getParent());
1653
1654 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1655 // branch on RunningOr.
1656 OrigBB->getTerminator()->eraseFromParent();
1657 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1658
1659 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1660 // pointer, because some may be null while others are not.
1661 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1662 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1663 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1664 Constant::getNullValue(GVVal->getType()),
1665 "tmp");
1666 BasicBlock *FreeBlock = BasicBlock::Create(Context, "free_it",
1667 OrigBB->getParent());
1668 BasicBlock *NextBlock = BasicBlock::Create(Context, "next",
1669 OrigBB->getParent());
1670 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1671
1672 // Fill in FreeBlock.
1673 new FreeInst(GVVal, FreeBlock);
1674 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1675 FreeBlock);
1676 BranchInst::Create(NextBlock, FreeBlock);
1677
1678 NullPtrBlock = NextBlock;
1679 }
1680
1681 BranchInst::Create(ContBB, NullPtrBlock);
1682
1683 // CI and BCI are no longer needed, remove them.
1684 BCI->eraseFromParent();
1685 CI->eraseFromParent();
1686
1687 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1688 /// update all uses of the load, keep track of what scalarized loads are
1689 /// inserted for a given load.
1690 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1691 InsertedScalarizedValues[GV] = FieldGlobals;
1692
1693 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1694
1695 // Okay, the malloc site is completely handled. All of the uses of GV are now
1696 // loads, and all uses of those loads are simple. Rewrite them to use loads
1697 // of the per-field globals instead.
1698 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1699 Instruction *User = cast<Instruction>(*UI++);
1700
1701 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1702 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1703 Context);
1704 continue;
1705 }
1706
1707 // Must be a store of null.
1708 StoreInst *SI = cast<StoreInst>(User);
1709 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1710 "Unexpected heap-sra user!");
1711
1712 // Insert a store of null into each global.
1713 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1714 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1715 Constant *Null = Constant::getNullValue(PT->getElementType());
1716 new StoreInst(Null, FieldGlobals[i], SI);
1717 }
1718 // Erase the original store.
1719 SI->eraseFromParent();
1720 }
1721
1722 // While we have PHIs that are interesting to rewrite, do it.
1723 while (!PHIsToRewrite.empty()) {
1724 PHINode *PN = PHIsToRewrite.back().first;
1725 unsigned FieldNo = PHIsToRewrite.back().second;
1726 PHIsToRewrite.pop_back();
1727 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1728 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1729
1730 // Add all the incoming values. This can materialize more phis.
1731 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1732 Value *InVal = PN->getIncomingValue(i);
1733 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1734 PHIsToRewrite, Context);
1735 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1736 }
1737 }
1738
1739 // Drop all inter-phi links and any loads that made it this far.
1740 for (DenseMap<Value*, std::vector<Value*> >::iterator
1741 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1742 I != E; ++I) {
1743 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1744 PN->dropAllReferences();
1745 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1746 LI->dropAllReferences();
1747 }
1748
1749 // Delete all the phis and loads now that inter-references are dead.
1750 for (DenseMap<Value*, std::vector<Value*> >::iterator
1751 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1752 I != E; ++I) {
1753 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1754 PN->eraseFromParent();
1755 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1756 LI->eraseFromParent();
1757 }
1758
1759 // The old global is now dead, remove it.
1760 GV->eraseFromParent();
1761
1762 ++NumHeapSRA;
1763 return cast<GlobalVariable>(FieldGlobals[0]);
1764}
1765
Chris Lattnere61d0a62008-12-15 21:02:25 +00001766/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1767/// pointer global variable with a single value stored it that is a malloc or
1768/// cast of malloc.
1769static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1770 MallocInst *MI,
1771 Module::global_iterator &GVI,
Dan Gohman7eb28f32009-08-14 00:11:03 +00001772 TargetData *TD,
Owen Andersone922c022009-07-22 00:24:57 +00001773 LLVMContext &Context) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001774 // If this is a malloc of an abstract type, don't touch it.
1775 if (!MI->getAllocatedType()->isSized())
1776 return false;
1777
1778 // We can't optimize this global unless all uses of it are *known* to be
1779 // of the malloc value, not of the null initializer value (consider a use
1780 // that compares the global's value against zero to see if the malloc has
1781 // been reached). To do this, we check to see if all uses of the global
1782 // would trap if the global were null: this proves that they must all
1783 // happen after the malloc.
1784 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1785 return false;
1786
1787 // We can't optimize this if the malloc itself is used in a complex way,
1788 // for example, being stored into multiple globals. This allows the
1789 // malloc to be stored into the specified global, loaded setcc'd, and
1790 // GEP'd. These are all things we could transform to using the global
1791 // for.
1792 {
1793 SmallPtrSet<PHINode*, 8> PHIs;
1794 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1795 return false;
1796 }
1797
1798
1799 // If we have a global that is only initialized with a fixed size malloc,
1800 // transform the program to use global memory instead of malloc'd memory.
1801 // This eliminates dynamic allocation, avoids an indirection accessing the
1802 // data, and exposes the resultant global to further GlobalOpt.
1803 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1804 // Restrict this transformation to only working on small allocations
1805 // (2048 bytes currently), as we don't want to introduce a 16M global or
1806 // something.
Dan Gohman7eb28f32009-08-14 00:11:03 +00001807 if (TD &&
1808 NElements->getZExtValue()*
1809 TD->getTypeAllocSize(MI->getAllocatedType()) < 2048) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001810 GVI = OptimizeGlobalAddressOfMalloc(GV, MI, Context);
Chris Lattnere61d0a62008-12-15 21:02:25 +00001811 return true;
1812 }
1813 }
1814
1815 // If the allocation is an array of structures, consider transforming this
1816 // into multiple malloc'd arrays, one for each field. This is basically
1817 // SRoA for malloc'd memory.
Chris Lattner101f44e2008-12-15 21:44:34 +00001818 const Type *AllocTy = MI->getAllocatedType();
1819
1820 // If this is an allocation of a fixed size array of structs, analyze as a
1821 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1822 if (!MI->isArrayAllocation())
1823 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1824 AllocTy = AT->getElementType();
1825
1826 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001827 // This the structure has an unreasonable number of fields, leave it
1828 // alone.
Chris Lattner101f44e2008-12-15 21:44:34 +00001829 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001830 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner101f44e2008-12-15 21:44:34 +00001831
1832 // If this is a fixed size array, transform the Malloc to be an alloc of
1833 // structs. malloc [100 x struct],1 -> malloc struct, 100
1834 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1835 MallocInst *NewMI =
Owen Anderson50dead02009-07-15 23:53:25 +00001836 new MallocInst(AllocSTy,
Owen Anderson1d0be152009-08-13 21:58:54 +00001837 ConstantInt::get(Type::getInt32Ty(Context),
1838 AT->getNumElements()),
Chris Lattner101f44e2008-12-15 21:44:34 +00001839 "", MI);
1840 NewMI->takeName(MI);
1841 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1842 MI->replaceAllUsesWith(Cast);
1843 MI->eraseFromParent();
1844 MI = NewMI;
1845 }
1846
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001847 GVI = PerformHeapAllocSRoA(GV, MI, Context);
Chris Lattnere61d0a62008-12-15 21:02:25 +00001848 return true;
1849 }
1850 }
1851
1852 return false;
1853}
Chris Lattner86395032006-09-30 23:32:09 +00001854
Victor Hernandez83d63912009-09-18 22:35:49 +00001855/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1856/// pointer global variable with a single value stored it that is a malloc or
1857/// cast of malloc.
1858static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1859 CallInst *CI,
1860 BitCastInst *BCI,
1861 Module::global_iterator &GVI,
1862 TargetData *TD,
1863 LLVMContext &Context) {
1864 // If we can't figure out the type being malloced, then we can't optimize.
1865 const Type *AllocTy = getMallocAllocatedType(CI);
1866 assert(AllocTy);
1867
1868 // If this is a malloc of an abstract type, don't touch it.
1869 if (!AllocTy->isSized())
1870 return false;
1871
1872 // We can't optimize this global unless all uses of it are *known* to be
1873 // of the malloc value, not of the null initializer value (consider a use
1874 // that compares the global's value against zero to see if the malloc has
1875 // been reached). To do this, we check to see if all uses of the global
1876 // would trap if the global were null: this proves that they must all
1877 // happen after the malloc.
1878 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1879 return false;
1880
1881 // We can't optimize this if the malloc itself is used in a complex way,
1882 // for example, being stored into multiple globals. This allows the
1883 // malloc to be stored into the specified global, loaded setcc'd, and
1884 // GEP'd. These are all things we could transform to using the global
1885 // for.
1886 {
1887 SmallPtrSet<PHINode*, 8> PHIs;
1888 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1889 return false;
1890 }
1891
1892 // If we have a global that is only initialized with a fixed size malloc,
1893 // transform the program to use global memory instead of malloc'd memory.
1894 // This eliminates dynamic allocation, avoids an indirection accessing the
1895 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez2491ce02009-10-15 20:14:52 +00001896 Value *NElems = getMallocArraySize(CI, Context, TD);
Victor Hernandez8db42d22009-10-16 23:12:25 +00001897 // We cannot optimize the malloc if we cannot determine malloc array size.
Victor Hernandez2491ce02009-10-15 20:14:52 +00001898 if (NElems) {
1899 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1900 // Restrict this transformation to only working on small allocations
1901 // (2048 bytes currently), as we don't want to introduce a 16M global or
1902 // something.
1903 if (TD &&
1904 NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1905 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, BCI, Context, TD);
1906 return true;
1907 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001908
Victor Hernandez8db42d22009-10-16 23:12:25 +00001909 // If the allocation is an array of structures, consider transforming this
1910 // into multiple malloc'd arrays, one for each field. This is basically
1911 // SRoA for malloc'd memory.
Victor Hernandez83d63912009-09-18 22:35:49 +00001912
Victor Hernandez8db42d22009-10-16 23:12:25 +00001913 // If this is an allocation of a fixed size array of structs, analyze as a
1914 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1915 if (!isArrayMalloc(CI, Context, TD))
1916 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1917 AllocTy = AT->getElementType();
Victor Hernandez83d63912009-09-18 22:35:49 +00001918
Victor Hernandez8db42d22009-10-16 23:12:25 +00001919 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1920 // This the structure has an unreasonable number of fields, leave it
1921 // alone.
1922 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1923 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, BCI)) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001924
Victor Hernandez8db42d22009-10-16 23:12:25 +00001925 // If this is a fixed size array, transform the Malloc to be an alloc of
1926 // structs. malloc [100 x struct],1 -> malloc struct, 100
1927 if (const ArrayType *AT =
1928 dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1929 Value* NumElements = ConstantInt::get(Type::getInt32Ty(Context),
1930 AT->getNumElements());
1931 Value* NewMI = CallInst::CreateMalloc(CI, TD->getIntPtrType(Context),
1932 AllocSTy, NumElements,
1933 BCI->getName());
1934 Value *Cast = new BitCastInst(NewMI, getMallocType(CI), "tmp", CI);
1935 BCI->replaceAllUsesWith(Cast);
1936 BCI->eraseFromParent();
1937 CI->eraseFromParent();
1938 BCI = cast<BitCastInst>(NewMI);
1939 CI = extractMallocCallFromBitCast(NewMI);
1940 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001941
Victor Hernandez8db42d22009-10-16 23:12:25 +00001942 GVI = PerformHeapAllocSRoA(GV, CI, BCI, Context, TD);
1943 return true;
1944 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001945 }
1946 }
1947
1948 return false;
1949}
1950
Chris Lattner9b34a612004-10-09 21:48:45 +00001951// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1952// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001953static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001954 Module::global_iterator &GVI,
Dan Gohman7eb28f32009-08-14 00:11:03 +00001955 TargetData *TD, LLVMContext &Context) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001956 // Ignore no-op GEPs and bitcasts.
1957 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001958
Chris Lattner708148e2004-10-10 23:14:11 +00001959 // If we are dealing with a pointer global that is initialized to null and
1960 // only has one (non-null) value stored into it, then we can optimize any
1961 // users of the loaded value (often calls and loads) that would trap if the
1962 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001963 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1964 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001965 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1966 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001967 SOVC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001968 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001969
Chris Lattner708148e2004-10-10 23:14:11 +00001970 // Optimize away any trapping uses of the loaded value.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001971 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
Chris Lattner8be80122004-10-10 17:07:12 +00001972 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001973 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001974 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD, Context))
Chris Lattnere61d0a62008-12-15 21:02:25 +00001975 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001976 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1977 if (getMallocAllocatedType(CI)) {
1978 BitCastInst* BCI = NULL;
1979 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
1980 UI != E; )
1981 BCI = dyn_cast<BitCastInst>(cast<Instruction>(*UI++));
1982 if (BCI &&
1983 TryToOptimizeStoreOfMallocToGlobal(GV, CI, BCI, GVI, TD, Context))
1984 return true;
1985 }
Chris Lattner708148e2004-10-10 23:14:11 +00001986 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001987 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001988
Chris Lattner9b34a612004-10-09 21:48:45 +00001989 return false;
1990}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001991
Chris Lattner58e44f42008-01-14 01:17:44 +00001992/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1993/// two values ever stored into GV are its initializer and OtherVal. See if we
1994/// can shrink the global into a boolean and select between the two values
1995/// whenever it is used. This exposes the values to other scalar optimizations.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001996static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
Owen Andersone922c022009-07-22 00:24:57 +00001997 LLVMContext &Context) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001998 const Type *GVElType = GV->getType()->getElementType();
1999
2000 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00002001 // an FP value, pointer or vector, don't do this optimization because a select
2002 // between them is very expensive and unlikely to lead to later
2003 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
2004 // where v1 and v2 both require constant pool loads, a big loss.
Owen Anderson1d0be152009-08-13 21:58:54 +00002005 if (GVElType == Type::getInt1Ty(Context) || GVElType->isFloatingPoint() ||
Chris Lattner6f6923f2009-03-07 23:32:02 +00002006 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
Chris Lattner58e44f42008-01-14 01:17:44 +00002007 return false;
2008
2009 // Walk the use list of the global seeing if all the uses are load or store.
2010 // If there is anything else, bail out.
2011 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel771281f2009-03-06 01:39:36 +00002012 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattner58e44f42008-01-14 01:17:44 +00002013 return false;
2014
Chris Lattnerbdff5482009-08-23 04:37:46 +00002015 DEBUG(errs() << " *** SHRINKING TO BOOL: " << *GV);
Chris Lattner58e44f42008-01-14 01:17:44 +00002016
Chris Lattner96a86b22004-12-12 05:53:50 +00002017 // Create the new global, initializing it to false.
Owen Anderson1d0be152009-08-13 21:58:54 +00002018 GlobalVariable *NewGV = new GlobalVariable(Context,
2019 Type::getInt1Ty(Context), false,
Owen Anderson5defacc2009-07-31 17:39:07 +00002020 GlobalValue::InternalLinkage, ConstantInt::getFalse(Context),
Nick Lewycky0e670df2009-05-03 03:49:08 +00002021 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002022 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00002023 GV->getParent()->getGlobalList().insert(GV, NewGV);
2024
2025 Constant *InitVal = GV->getInitializer();
Owen Anderson1d0be152009-08-13 21:58:54 +00002026 assert(InitVal->getType() != Type::getInt1Ty(Context) &&
2027 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00002028
2029 // If initialized to zero and storing one into the global, we can use a cast
2030 // instead of a select to synthesize the desired value.
2031 bool IsOneZero = false;
2032 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00002033 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00002034
2035 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00002036 Instruction *UI = cast<Instruction>(GV->use_back());
2037 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00002038 // Change the store into a boolean store.
2039 bool StoringOther = SI->getOperand(0) == OtherVal;
2040 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00002041 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00002042 if (StoringOther || SI->getOperand(0) == InitVal)
Owen Anderson1d0be152009-08-13 21:58:54 +00002043 StoreVal = ConstantInt::get(Type::getInt1Ty(Context), StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00002044 else {
2045 // Otherwise, we are storing a previously loaded copy. To do this,
2046 // change the copy from copying the original value to just copying the
2047 // bool.
2048 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
2049
2050 // If we're already replaced the input, StoredVal will be a cast or
2051 // select instruction. If not, it will be a load of the original
2052 // global.
2053 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
2054 assert(LI->getOperand(0) == GV && "Not a copy!");
2055 // Insert a new load, to preserve the saved value.
2056 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
2057 } else {
2058 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
2059 "This is not a form that we understand!");
2060 StoreVal = StoredVal->getOperand(0);
2061 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
2062 }
2063 }
2064 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00002065 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00002066 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00002067 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00002068 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00002069 Value *NSI;
2070 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00002071 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00002072 else
Gabor Greif051a9502008-04-06 20:25:17 +00002073 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00002074 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00002075 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00002076 }
2077 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00002078 }
2079
2080 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00002081 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00002082}
2083
2084
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002085/// ProcessInternalGlobal - Analyze the specified global variable and optimize
2086/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00002087bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00002088 Module::global_iterator &GVI) {
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002089 SmallPtrSet<PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002090 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002091 GV->removeDeadConstantUsers();
2092
2093 if (GV->use_empty()) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00002094 DEBUG(errs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00002095 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002096 ++NumDeleted;
2097 return true;
2098 }
2099
2100 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00002101#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002102 cerr << "Global: " << *GV;
2103 cerr << " isLoaded = " << GS.isLoaded << "\n";
2104 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00002105 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002106 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
2107 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
2108 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
2109 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00002110 }
2111 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00002112 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00002113 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00002114 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00002115 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00002116 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00002117 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00002118 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00002119 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00002120#endif
2121
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00002122 // If this is a first class global and has only one accessing function
2123 // and this function is main (which we know is not recursive we can make
2124 // this global a local variable) we replace the global with a local alloca
2125 // in this function.
2126 //
Dan Gohman399101a2008-05-23 00:17:26 +00002127 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00002128 // are just replacing static memory to stack memory.
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00002129 //
2130 // If the global is in different address space, don't bring it to stack.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00002131 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00002132 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00002133 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00002134 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00002135 GS.AccessingFunction->hasExternalLinkage() &&
2136 GV->getType()->getAddressSpace() == 0) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00002137 DEBUG(errs() << "LOCALIZING GLOBAL: " << *GV);
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00002138 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
2139 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00002140 // FIXME: Pass Global's alignment when globals have alignment
Owen Anderson50dead02009-07-15 23:53:25 +00002141 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00002142 if (!isa<UndefValue>(GV->getInitializer()))
2143 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00002144
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00002145 GV->replaceAllUsesWith(Alloca);
2146 GV->eraseFromParent();
2147 ++NumLocalized;
2148 return true;
2149 }
Chris Lattnercff16732006-09-30 19:40:30 +00002150
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002151 // If the global is never loaded (but may be stored to), it is dead.
2152 // Delete it now.
2153 if (!GS.isLoaded) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00002154 DEBUG(errs() << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattner930f4752004-10-09 03:32:52 +00002155
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002156 // Delete any stores we can find to the global. We may not be able to
2157 // make it completely dead though.
Owen Anderson50895512009-07-06 18:42:36 +00002158 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
Owen Andersone922c022009-07-22 00:24:57 +00002159 GV->getContext());
Chris Lattner930f4752004-10-09 03:32:52 +00002160
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002161 // If the global is dead now, delete it.
2162 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00002163 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002164 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00002165 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002166 }
Chris Lattner930f4752004-10-09 03:32:52 +00002167 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00002168
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002169 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00002170 DEBUG(errs() << "MARKING CONSTANT: " << *GV);
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002171 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00002172
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002173 // Clean up any obviously simplifiable users now.
Owen Andersone922c022009-07-22 00:24:57 +00002174 CleanupConstantGlobalUsers(GV, GV->getInitializer(), GV->getContext());
Misha Brukmanfd939082005-04-21 23:48:37 +00002175
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002176 // If the global is dead now, just nuke it.
2177 if (GV->use_empty()) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00002178 DEBUG(errs() << " *** Marking constant allowed us to simplify "
2179 << "all users and delete global!\n");
Chris Lattner7a7ed022004-10-16 18:09:00 +00002180 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002181 ++NumDeleted;
2182 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002183
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002184 ++NumMarked;
2185 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00002186 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Dan Gohman7eb28f32009-08-14 00:11:03 +00002187 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
2188 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD,
2189 GV->getContext())) {
2190 GVI = FirstNewGV; // Don't skip the newly produced globals!
2191 return true;
2192 }
Chris Lattner9b34a612004-10-09 21:48:45 +00002193 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00002194 // If the initial value for the global was an undef value, and if only
2195 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00002196 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00002197 // global. This allows us to mark it constant.
2198 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2199 if (isa<UndefValue>(GV->getInitializer())) {
2200 // Change the initial value here.
2201 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00002202
Chris Lattner96a86b22004-12-12 05:53:50 +00002203 // Clean up any obviously simplifiable users now.
Owen Andersone922c022009-07-22 00:24:57 +00002204 CleanupConstantGlobalUsers(GV, GV->getInitializer(),
2205 GV->getContext());
Misha Brukmanfd939082005-04-21 23:48:37 +00002206
Chris Lattner96a86b22004-12-12 05:53:50 +00002207 if (GV->use_empty()) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00002208 DEBUG(errs() << " *** Substituting initializer allowed us to "
2209 << "simplify all users and delete global!\n");
Chris Lattner96a86b22004-12-12 05:53:50 +00002210 GV->eraseFromParent();
2211 ++NumDeleted;
2212 } else {
2213 GVI = GV;
2214 }
2215 ++NumSubstitute;
2216 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00002217 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00002218
Chris Lattner9b34a612004-10-09 21:48:45 +00002219 // Try to optimize globals based on the knowledge that only one value
2220 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00002221 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Dan Gohman7eb28f32009-08-14 00:11:03 +00002222 getAnalysisIfAvailable<TargetData>(),
2223 GV->getContext()))
Chris Lattner9b34a612004-10-09 21:48:45 +00002224 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00002225
2226 // Otherwise, if the global was not a boolean, we can shrink it to be a
2227 // boolean.
2228 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Owen Andersone922c022009-07-22 00:24:57 +00002229 if (TryToShrinkGlobalToBoolean(GV, SOVConstant, GV->getContext())) {
Chris Lattner96a86b22004-12-12 05:53:50 +00002230 ++NumShrunkToBool;
2231 return true;
2232 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002233 }
2234 }
2235 return false;
2236}
2237
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002238/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2239/// function, changing them to FastCC.
2240static void ChangeCalleesToFastCall(Function *F) {
2241 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00002242 CallSite User(cast<Instruction>(*UI));
2243 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002244 }
2245}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002246
Devang Patel05988662008-09-25 21:00:45 +00002247static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00002248 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00002249 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00002250 continue;
2251
Duncan Sands548448a2008-02-18 17:32:13 +00002252 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00002253 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00002254 }
2255
2256 return Attrs;
2257}
2258
2259static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00002260 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002261 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00002262 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00002263 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002264 }
2265}
2266
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002267bool GlobalOpt::OptimizeFunctions(Module &M) {
2268 bool Changed = false;
2269 // Optimize functions.
2270 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2271 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002272 // Functions without names cannot be referenced outside this module.
2273 if (!F->hasName() && !F->isDeclaration())
2274 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002275 F->removeDeadConstantUsers();
Rafael Espindolabb46f522009-01-15 20:18:42 +00002276 if (F->use_empty() && (F->hasLocalLinkage() ||
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002277 F->hasLinkOnceLinkage())) {
2278 M.getFunctionList().erase(F);
2279 Changed = true;
2280 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002281 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002282 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002283 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002284 // If this function has C calling conventions, is not a varargs
2285 // function, and is only called directly, promote it to use the Fast
2286 // calling convention.
2287 F->setCallingConv(CallingConv::Fast);
2288 ChangeCalleesToFastCall(F);
2289 ++NumFastCallFns;
2290 Changed = true;
2291 }
2292
Devang Patel05988662008-09-25 21:00:45 +00002293 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002294 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002295 // The function is not used by a trampoline intrinsic, so it is safe
2296 // to remove the 'nest' attribute.
2297 RemoveNestAttribute(F);
2298 ++NumNestRemoved;
2299 Changed = true;
2300 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002301 }
2302 }
2303 return Changed;
2304}
2305
2306bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2307 bool Changed = false;
2308 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2309 GVI != E; ) {
2310 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002311 // Global variables without names cannot be referenced outside this module.
2312 if (!GV->hasName() && !GV->isDeclaration())
2313 GV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolabb46f522009-01-15 20:18:42 +00002314 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002315 GV->hasInitializer())
2316 Changed |= ProcessInternalGlobal(GV, GVI);
2317 }
2318 return Changed;
2319}
2320
2321/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
2322/// initializers have an init priority of 65535.
2323GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00002324 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2325 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002326 if (I->getName() == "llvm.global_ctors") {
2327 // Found it, verify it's an array of { int, void()* }.
2328 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
2329 if (!ATy) return 0;
2330 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
2331 if (!STy || STy->getNumElements() != 2 ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002332 STy->getElementType(0) != Type::getInt32Ty(M.getContext())) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002333 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
2334 if (!PFTy) return 0;
2335 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00002336 if (!FTy || FTy->getReturnType() != Type::getVoidTy(M.getContext()) ||
2337 FTy->isVarArg() || FTy->getNumParams() != 0)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002338 return 0;
2339
2340 // Verify that the initializer is simple enough for us to handle.
Dan Gohman82555732009-08-19 18:20:44 +00002341 if (!I->hasDefinitiveInitializer()) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002342 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
2343 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00002344 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2345 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002346 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2347 continue;
2348
2349 // Must have a function or null ptr.
2350 if (!isa<Function>(CS->getOperand(1)))
2351 return 0;
2352
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002353 // Init priority must be standard.
2354 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00002355 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002356 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002357 } else {
2358 return 0;
2359 }
2360
2361 return I;
2362 }
2363 return 0;
2364}
2365
Chris Lattnerdb973e62005-09-26 02:31:18 +00002366/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2367/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002368static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
2369 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2370 std::vector<Function*> Result;
2371 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002372 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2373 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002374 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2375 }
2376 return Result;
2377}
2378
Chris Lattnerdb973e62005-09-26 02:31:18 +00002379/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2380/// specified array, returning the new global to use.
2381static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002382 const std::vector<Function*> &Ctors,
Owen Andersone922c022009-07-22 00:24:57 +00002383 LLVMContext &Context) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002384 // If we made a change, reassemble the initializer list.
2385 std::vector<Constant*> CSVals;
Owen Anderson1d0be152009-08-13 21:58:54 +00002386 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(Context), 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002387 CSVals.push_back(0);
2388
2389 // Create the new init list.
2390 std::vector<Constant*> CAList;
2391 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002392 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002393 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002394 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00002395 const Type *FTy = FunctionType::get(Type::getVoidTy(Context), false);
Owen Andersondebcb012009-07-29 22:17:13 +00002396 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002397 CSVals[1] = Constant::getNullValue(PFTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00002398 CSVals[0] = ConstantInt::get(Type::getInt32Ty(Context), 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002399 }
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002400 CAList.push_back(ConstantStruct::get(Context, CSVals, false));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002401 }
2402
2403 // Create the array initializer.
2404 const Type *StructTy =
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002405 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson1fd70962009-07-28 18:32:17 +00002406 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002407 CAList.size()), CAList);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002408
2409 // If we didn't change the number of elements, don't create a new GV.
2410 if (CA->getType() == GCL->getInitializer()->getType()) {
2411 GCL->setInitializer(CA);
2412 return GCL;
2413 }
2414
2415 // Create the new global and insert it next to the existing list.
Owen Andersone922c022009-07-22 00:24:57 +00002416 GlobalVariable *NGV = new GlobalVariable(Context, CA->getType(),
Owen Anderson3d29df32009-07-08 01:26:06 +00002417 GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002418 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002419 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002420 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002421 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002422
2423 // Nuke the old list, replacing any uses with the new one.
2424 if (!GCL->use_empty()) {
2425 Constant *V = NGV;
2426 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002427 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002428 GCL->replaceAllUsesWith(V);
2429 }
2430 GCL->eraseFromParent();
2431
2432 if (Ctors.size())
2433 return NGV;
2434 else
2435 return 0;
2436}
Chris Lattner79c11012005-09-26 04:44:35 +00002437
2438
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002439static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00002440 Value *V) {
2441 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2442 Constant *R = ComputedValues[V];
2443 assert(R && "Reference to an uncomputed value!");
2444 return R;
2445}
2446
2447/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2448/// enough for us to understand. In particular, if it is a cast of something,
2449/// we punt. We basically just support direct accesses to globals and GEP's of
2450/// globals. This should be kept up to date with CommitValueTo.
Owen Andersone922c022009-07-22 00:24:57 +00002451static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext &Context) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002452 // Conservatively, avoid aggregate types. This is because we don't
2453 // want to worry about them partially overlapping other stores.
2454 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2455 return false;
2456
Dan Gohmanfd54a892009-09-07 22:31:26 +00002457 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2458 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2459 // external globals.
2460 return GV->hasDefinitiveInitializer();
2461
Chris Lattner798b4d52005-09-26 06:52:44 +00002462 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2463 // Handle a constantexpr gep.
2464 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002465 isa<GlobalVariable>(CE->getOperand(0)) &&
2466 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002467 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohmanfd54a892009-09-07 22:31:26 +00002468 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2469 // external globals.
2470 if (!GV->hasDefinitiveInitializer())
2471 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002472
Dan Gohman80bdc962009-09-07 22:44:55 +00002473 // The first index must be zero.
Dan Gohmane6992f72009-09-10 23:37:55 +00002474 ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002475 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002476
2477 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002478 // notional bounds of the corresponding static array types.
2479 if (!CE->isGEPWithNoNotionalOverIndexing())
2480 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002481
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002482 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002483 }
Chris Lattner79c11012005-09-26 04:44:35 +00002484 return false;
2485}
2486
Chris Lattner798b4d52005-09-26 06:52:44 +00002487/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2488/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2489/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2490static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002491 ConstantExpr *Addr, unsigned OpNo,
Owen Andersone922c022009-07-22 00:24:57 +00002492 LLVMContext &Context) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002493 // Base case of the recursion.
2494 if (OpNo == Addr->getNumOperands()) {
2495 assert(Val->getType() == Init->getType() && "Type mismatch!");
2496 return Val;
2497 }
2498
2499 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2500 std::vector<Constant*> Elts;
2501
2502 // Break up the constant into its elements.
2503 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002504 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2505 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002506 } else if (isa<ConstantAggregateZero>(Init)) {
2507 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002508 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002509 } else if (isa<UndefValue>(Init)) {
2510 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002511 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002512 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002513 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002514 " ConstantFoldLoadThroughGEPConstantExpr");
2515 }
2516
2517 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002518 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2519 unsigned Idx = CU->getZExtValue();
2520 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002521 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002522
2523 // Return the modified struct.
Owen Andersond7f2a6c2009-08-05 23:16:16 +00002524 return ConstantStruct::get(Context, &Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002525 } else {
2526 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2527 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2528
2529 // Break up the array into elements.
2530 std::vector<Constant*> Elts;
2531 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002532 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2533 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002534 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002535 Constant *Elt = Constant::getNullValue(ATy->getElementType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002536 Elts.assign(ATy->getNumElements(), Elt);
2537 } else if (isa<UndefValue>(Init)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002538 Constant *Elt = UndefValue::get(ATy->getElementType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002539 Elts.assign(ATy->getNumElements(), Elt);
2540 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002541 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002542 " ConstantFoldLoadThroughGEPConstantExpr");
2543 }
2544
Reid Spencerb83eb642006-10-20 07:07:24 +00002545 assert(CI->getZExtValue() < ATy->getNumElements());
2546 Elts[CI->getZExtValue()] =
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002547 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
Owen Anderson1fd70962009-07-28 18:32:17 +00002548 return ConstantArray::get(ATy, Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002549 }
2550}
2551
Chris Lattner79c11012005-09-26 04:44:35 +00002552/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2553/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002554static void CommitValueTo(Constant *Val, Constant *Addr,
Owen Andersone922c022009-07-22 00:24:57 +00002555 LLVMContext &Context) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002556 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2557 assert(GV->hasInitializer());
2558 GV->setInitializer(Val);
2559 return;
2560 }
2561
2562 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2563 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2564
2565 Constant *Init = GV->getInitializer();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002566 Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002567 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00002568}
2569
Chris Lattner562a0552005-09-26 05:16:34 +00002570/// ComputeLoadResult - Return the value that would be computed by a load from
2571/// P after the stores reflected by 'memory' have been performed. If we can't
2572/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002573static Constant *ComputeLoadResult(Constant *P,
Owen Anderson50895512009-07-06 18:42:36 +00002574 const DenseMap<Constant*, Constant*> &Memory,
Owen Andersone922c022009-07-22 00:24:57 +00002575 LLVMContext &Context) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002576 // If this memory location has been recently stored, use the stored value: it
2577 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002578 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002579 if (I != Memory.end()) return I->second;
2580
2581 // Access it.
2582 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002583 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002584 return GV->getInitializer();
2585 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002586 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002587
2588 // Handle a constantexpr getelementptr.
2589 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2590 if (CE->getOpcode() == Instruction::GetElementPtr &&
2591 isa<GlobalVariable>(CE->getOperand(0))) {
2592 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002593 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002594 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002595 }
2596
2597 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002598}
2599
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002600/// EvaluateFunction - Evaluate a call to function F, returning true if
2601/// successful, false if we can't evaluate it. ActualArgs contains the formal
2602/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002603static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002604 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002605 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002606 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002607 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002608 // Check to see if this function is already executing (recursion). If so,
2609 // bail out. TODO: we might want to accept limited recursion.
2610 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2611 return false;
2612
Owen Andersone922c022009-07-22 00:24:57 +00002613 LLVMContext &Context = F->getContext();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002614
Chris Lattnercd271422005-09-27 04:45:34 +00002615 CallStack.push_back(F);
2616
Chris Lattner79c11012005-09-26 04:44:35 +00002617 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002618 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002619
2620 // Initialize arguments to the incoming values specified.
2621 unsigned ArgNo = 0;
2622 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2623 ++AI, ++ArgNo)
2624 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002625
Chris Lattnercdf98be2005-09-26 04:57:38 +00002626 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2627 /// we can only evaluate any one basic block at most once. This set keeps
2628 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002629 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002630
Chris Lattner79c11012005-09-26 04:44:35 +00002631 // CurInst - The current instruction we're evaluating.
2632 BasicBlock::iterator CurInst = F->begin()->begin();
2633
2634 // This is the main evaluation loop.
2635 while (1) {
2636 Constant *InstResult = 0;
2637
2638 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002639 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002640 Constant *Ptr = getVal(Values, SI->getOperand(1));
Owen Anderson50895512009-07-06 18:42:36 +00002641 if (!isSimpleEnoughPointerToCommit(Ptr, Context))
Chris Lattner79c11012005-09-26 04:44:35 +00002642 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002643 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002644 Constant *Val = getVal(Values, SI->getOperand(0));
2645 MutatedMemory[Ptr] = Val;
2646 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002647 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002648 getVal(Values, BO->getOperand(0)),
2649 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002650 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002651 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002652 getVal(Values, CI->getOperand(0)),
2653 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002654 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002655 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002656 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002657 CI->getType());
2658 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002659 InstResult =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002660 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002661 getVal(Values, SI->getOperand(1)),
2662 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002663 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2664 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002665 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002666 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2667 i != e; ++i)
2668 GEPOps.push_back(getVal(Values, *i));
Dan Gohman4a7e6b72009-09-07 22:34:43 +00002669 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2670 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2671 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002672 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002673 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002674 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Owen Anderson50895512009-07-06 18:42:36 +00002675 MutatedMemory, Context);
Chris Lattnercd271422005-09-27 04:45:34 +00002676 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002677 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002678 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002679 const Type *Ty = AI->getType()->getElementType();
Owen Andersone922c022009-07-22 00:24:57 +00002680 AllocaTmps.push_back(new GlobalVariable(Context, Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002681 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002682 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002683 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002684 InstResult = AllocaTmps.back();
2685 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002686
2687 // Debug info can safely be ignored here.
2688 if (isa<DbgInfoIntrinsic>(CI)) {
2689 ++CurInst;
2690 continue;
2691 }
2692
Chris Lattner7cd580f2006-07-07 21:37:01 +00002693 // Cannot handle inline asm.
2694 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2695
Chris Lattnercd271422005-09-27 04:45:34 +00002696 // Resolve function pointers.
2697 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2698 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002699
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002700 SmallVector<Constant*, 8> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002701 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2702 i != e; ++i)
2703 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002704
Reid Spencer5cbf9852007-01-30 20:08:39 +00002705 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002706 // If this is a function we can constant fold, do it.
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002707 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
Chris Lattner6c1f5652007-01-30 23:14:52 +00002708 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002709 InstResult = C;
2710 } else {
2711 return false;
2712 }
2713 } else {
2714 if (Callee->getFunctionType()->isVarArg())
2715 return false;
2716
2717 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002718 // Execute the call, if successful, use the return value.
2719 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2720 MutatedMemory, AllocaTmps))
2721 return false;
2722 InstResult = RetVal;
2723 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002724 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002725 BasicBlock *NewBB = 0;
2726 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2727 if (BI->isUnconditional()) {
2728 NewBB = BI->getSuccessor(0);
2729 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002730 ConstantInt *Cond =
2731 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002732 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002733
Reid Spencer579dca12007-01-12 04:24:46 +00002734 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002735 }
2736 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2737 ConstantInt *Val =
2738 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002739 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002740 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2741 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002742 if (RI->getNumOperands())
2743 RetVal = getVal(Values, RI->getOperand(0));
2744
2745 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002746 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002747 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002748 // invoke, unwind, unreachable.
2749 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002750 }
2751
2752 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002753 // executed the new block before. If so, we have a looping function,
2754 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002755 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002756 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002757
2758 // Okay, we have never been in this block before. Check to see if there
2759 // are any PHI nodes. If so, evaluate them with information about where
2760 // we came from.
2761 BasicBlock *OldBB = CurInst->getParent();
2762 CurInst = NewBB->begin();
2763 PHINode *PN;
2764 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2765 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2766
2767 // Do NOT increment CurInst. We know that the terminator had no value.
2768 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002769 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002770 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002771 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002772 }
2773
2774 if (!CurInst->use_empty())
2775 Values[CurInst] = InstResult;
2776
2777 // Advance program counter.
2778 ++CurInst;
2779 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002780}
2781
2782/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2783/// we can. Return true if we can, false otherwise.
2784static bool EvaluateStaticConstructor(Function *F) {
2785 /// MutatedMemory - For each store we execute, we update this map. Loads
2786 /// check this to get the most up-to-date value. If evaluation is successful,
2787 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002788 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002789
2790 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2791 /// to represent its body. This vector is needed so we can delete the
2792 /// temporary globals when we are done.
2793 std::vector<GlobalVariable*> AllocaTmps;
2794
2795 /// CallStack - This is used to detect recursion. In pathological situations
2796 /// we could hit exponential behavior, but at least there is nothing
2797 /// unbounded.
2798 std::vector<Function*> CallStack;
2799
2800 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002801 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002802 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2803 SmallVector<Constant*, 0>(), CallStack,
2804 MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002805 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002806 // We succeeded at evaluation: commit the result.
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002807 DEBUG(errs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2808 << F->getName() << "' to " << MutatedMemory.size()
2809 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002810 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002811 E = MutatedMemory.end(); I != E; ++I)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002812 CommitValueTo(I->second, I->first, F->getContext());
Chris Lattnera22fdb02005-09-26 17:07:09 +00002813 }
Chris Lattner79c11012005-09-26 04:44:35 +00002814
Chris Lattnera22fdb02005-09-26 17:07:09 +00002815 // At this point, we are done interpreting. If we created any 'alloca'
2816 // temporaries, release them now.
2817 while (!AllocaTmps.empty()) {
2818 GlobalVariable *Tmp = AllocaTmps.back();
2819 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002820
Chris Lattnera22fdb02005-09-26 17:07:09 +00002821 // If there are still users of the alloca, the program is doing something
2822 // silly, e.g. storing the address of the alloca somewhere and using it
2823 // later. Since this is undefined, we'll just make it be null.
2824 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002825 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002826 delete Tmp;
2827 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002828
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002829 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002830}
2831
Chris Lattnerdb973e62005-09-26 02:31:18 +00002832
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002833
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002834/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2835/// Return true if anything changed.
2836bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2837 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2838 bool MadeChange = false;
2839 if (Ctors.empty()) return false;
2840
2841 // Loop over global ctors, optimizing them when we can.
2842 for (unsigned i = 0; i != Ctors.size(); ++i) {
2843 Function *F = Ctors[i];
2844 // Found a null terminator in the middle of the list, prune off the rest of
2845 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002846 if (F == 0) {
2847 if (i != Ctors.size()-1) {
2848 Ctors.resize(i+1);
2849 MadeChange = true;
2850 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002851 break;
2852 }
2853
Chris Lattner79c11012005-09-26 04:44:35 +00002854 // We cannot simplify external ctor functions.
2855 if (F->empty()) continue;
2856
2857 // If we can evaluate the ctor at compile time, do.
2858 if (EvaluateStaticConstructor(F)) {
2859 Ctors.erase(Ctors.begin()+i);
2860 MadeChange = true;
2861 --i;
2862 ++NumCtorsEvaluated;
2863 continue;
2864 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002865 }
2866
2867 if (!MadeChange) return false;
2868
Owen Andersone922c022009-07-22 00:24:57 +00002869 GCL = InstallGlobalCtors(GCL, Ctors, GCL->getContext());
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002870 return true;
2871}
2872
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002873bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002874 bool Changed = false;
2875
Duncan Sands177d84e2009-01-07 20:01:06 +00002876 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002877 I != E;) {
2878 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002879 // Aliases without names cannot be referenced outside this module.
2880 if (!J->hasName() && !J->isDeclaration())
2881 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002882 // If the aliasee may change at link time, nothing can be done - bail out.
2883 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002884 continue;
2885
Duncan Sands4782b302009-02-15 09:56:08 +00002886 Constant *Aliasee = J->getAliasee();
2887 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002888 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002889 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2890
2891 // Make all users of the alias use the aliasee instead.
2892 if (!J->use_empty()) {
2893 J->replaceAllUsesWith(Aliasee);
2894 ++NumAliasesResolved;
2895 Changed = true;
2896 }
2897
2898 // If the aliasee has internal linkage, give it the name and linkage
2899 // of the alias, and delete the alias. This turns:
2900 // define internal ... @f(...)
2901 // @a = alias ... @f
2902 // into:
2903 // define ... @a(...)
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002904 if (!Target->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002905 continue;
2906
2907 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002908 if (J->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002909 continue;
2910
Duncan Sandsa37d1192009-02-15 11:54:49 +00002911 // Do not perform the transform if multiple aliases potentially target the
2912 // aliasee. This check also ensures that it is safe to replace the section
2913 // and other attributes of the aliasee with those of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002914 if (!hasOneUse)
2915 continue;
2916
Duncan Sandsa37d1192009-02-15 11:54:49 +00002917 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002918 Target->takeName(J);
2919 Target->setLinkage(J->getLinkage());
Duncan Sandsa37d1192009-02-15 11:54:49 +00002920 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sands4782b302009-02-15 09:56:08 +00002921
2922 // Delete the alias.
2923 M.getAliasList().erase(J);
2924 ++NumAliasesRemoved;
2925 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002926 }
2927
2928 return Changed;
2929}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002930
Chris Lattner7a90b682004-10-07 04:16:33 +00002931bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002932 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002933
2934 // Try to find the llvm.globalctors list.
2935 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002936
Chris Lattner7a90b682004-10-07 04:16:33 +00002937 bool LocalChange = true;
2938 while (LocalChange) {
2939 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002940
2941 // Delete functions that are trivially dead, ccc -> fastcc
2942 LocalChange |= OptimizeFunctions(M);
2943
2944 // Optimize global_ctors list.
2945 if (GlobalCtors)
2946 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2947
2948 // Optimize non-address-taken globals.
2949 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002950
2951 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002952 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002953 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002954 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002955
2956 // TODO: Move all global ctors functions to the end of the module for code
2957 // layout.
2958
Chris Lattner079236d2004-02-25 21:34:36 +00002959 return Changed;
2960}