blob: 9d048b5300168d1d0704feefa55f2dd13fbec686 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000023#include "llvm/LLVMContext.h"
Chris Lattner079236d2004-02-25 21:34:36 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000027#include "llvm/Target/TargetData.h"
Duncan Sands548448a2008-02-18 17:32:13 +000028#include "llvm/Support/CallSite.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000029#include "llvm/Support/Compiler.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000030#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000034#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000035#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000036#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000037#include "llvm/ADT/Statistic.h"
Chris Lattner670c8892004-10-08 17:32:09 +000038#include "llvm/ADT/StringExtras.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000039#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000040#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000041using namespace llvm;
42
Chris Lattner86453c52006-12-19 22:09:18 +000043STATISTIC(NumMarked , "Number of globals marked constant");
44STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
45STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
46STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
47STATISTIC(NumDeleted , "Number of globals deleted");
48STATISTIC(NumFnDeleted , "Number of functions deleted");
49STATISTIC(NumGlobUses , "Number of global uses devirtualized");
50STATISTIC(NumLocalized , "Number of globals localized");
51STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
52STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
53STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000054STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000055STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
56STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Chris Lattner079236d2004-02-25 21:34:36 +000057
Chris Lattner86453c52006-12-19 22:09:18 +000058namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000059 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000060 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 AU.addRequired<TargetData>();
62 }
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 Anderson07cf79e2009-07-06 23:00:19 +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 Anderson14ce9ef2009-07-06 01:34:54 +0000264 return Context->getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000265 } else if (const SequentialType *STy =
266 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000267 return Context->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 Anderson14ce9ef2009-07-06 01:34:54 +0000272 return Context->getUndef(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000273 } else if (const SequentialType *STy =
274 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000275 return Context->getUndef(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 Anderson07cf79e2009-07-06 23:00:19 +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)
Owen Anderson50895512009-07-06 18:42:36 +0000307 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
308 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)
Owen Anderson50895512009-07-06 18:42:36 +0000328 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
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.
430 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
431 ++GEPI) {
432 uint64_t NumElements;
433 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
434 NumElements = SubArrayTy->getNumElements();
435 else
436 NumElements = cast<VectorType>(*GEPI)->getNumElements();
437
438 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
439 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
440 return false;
441 }
442 }
443
444 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
445 if (!isSafeSROAElementUse(*I))
446 return false;
447 return true;
448}
449
450/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
451/// is safe for us to perform this transformation.
452///
453static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
454 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
455 UI != E; ++UI) {
456 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
457 return false;
458 }
459 return true;
460}
461
462
Chris Lattner670c8892004-10-08 17:32:09 +0000463/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
464/// variable. This opens the door for other optimizations by exposing the
465/// behavior of the program in a more fine-grained way. We have determined that
466/// this transformation is safe already. We return the first global variable we
467/// insert so that the caller can reprocess it.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000468static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000469 LLVMContext *Context) {
Chris Lattner727c2102008-01-14 01:31:05 +0000470 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000471 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000472 return 0;
473
Rafael Espindolabb46f522009-01-15 20:18:42 +0000474 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000475 Constant *Init = GV->getInitializer();
476 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000477
Chris Lattner670c8892004-10-08 17:32:09 +0000478 std::vector<GlobalVariable*> NewGlobals;
479 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
480
Chris Lattner998182b2008-04-26 07:40:11 +0000481 // Get the alignment of the global, either explicit or target-specific.
482 unsigned StartAlignment = GV->getAlignment();
483 if (StartAlignment == 0)
484 StartAlignment = TD.getABITypeAlignment(GV->getType());
485
Chris Lattner670c8892004-10-08 17:32:09 +0000486 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
487 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000488 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000489 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
490 Constant *In = getAggregateConstantElement(Init,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000491 Context->getConstantInt(Type::Int32Ty, i),
492 Context);
Chris Lattner670c8892004-10-08 17:32:09 +0000493 assert(In && "Couldn't get element of initializer?");
Owen Andersone9b11b42009-07-08 19:03:57 +0000494 GlobalVariable *NGV = new GlobalVariable(*Context,
495 STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000496 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000497 In, GV->getName()+"."+utostr(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000498 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000499 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000500 Globals.insert(GV, NGV);
501 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000502
503 // Calculate the known alignment of the field. If the original aggregate
504 // had 256 byte alignment for example, something might depend on that:
505 // propagate info to each field.
506 uint64_t FieldOffset = Layout.getElementOffset(i);
507 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
508 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
509 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000510 }
511 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
512 unsigned NumElements = 0;
513 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
514 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000515 else
Chris Lattner998182b2008-04-26 07:40:11 +0000516 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000517
Chris Lattner1f21ef12005-02-23 16:53:04 +0000518 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000519 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000520 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000521
Duncan Sands777d2302009-05-09 07:06:46 +0000522 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000523 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000524 for (unsigned i = 0, e = NumElements; i != e; ++i) {
525 Constant *In = getAggregateConstantElement(Init,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000526 Context->getConstantInt(Type::Int32Ty, i),
527 Context);
Chris Lattner670c8892004-10-08 17:32:09 +0000528 assert(In && "Couldn't get element of initializer?");
529
Owen Andersone9b11b42009-07-08 19:03:57 +0000530 GlobalVariable *NGV = new GlobalVariable(*Context,
531 STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000532 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000533 In, GV->getName()+"."+utostr(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000534 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000535 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000536 Globals.insert(GV, NGV);
537 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000538
539 // Calculate the known alignment of the field. If the original aggregate
540 // had 256 byte alignment for example, something might depend on that:
541 // propagate info to each field.
542 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
543 if (NewAlign > EltAlign)
544 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000545 }
546 }
547
548 if (NewGlobals.empty())
549 return 0;
550
Bill Wendling0a81aac2006-11-26 10:02:32 +0000551 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000552
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000553 Constant *NullInt = Context->getNullValue(Type::Int32Ty);
Chris Lattner670c8892004-10-08 17:32:09 +0000554
555 // Loop over all of the uses of the global, replacing the constantexpr geps,
556 // with smaller constantexpr geps or direct references.
557 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000558 User *GEP = GV->use_back();
559 assert(((isa<ConstantExpr>(GEP) &&
560 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
561 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000562
Chris Lattner670c8892004-10-08 17:32:09 +0000563 // Ignore the 1th operand, which has to be zero or else the program is quite
564 // broken (undefined). Get the 2nd operand, which is the structure or array
565 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000566 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000567 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
568
Chris Lattner30ba5692004-10-11 05:54:41 +0000569 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000570
571 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000572 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000573 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000574 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000575 Idxs.push_back(NullInt);
576 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
577 Idxs.push_back(CE->getOperand(i));
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000578 NewPtr = Context->getConstantExprGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000579 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000580 } else {
581 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000582 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000583 Idxs.push_back(NullInt);
584 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
585 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000586 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
587 GEPI->getName()+"."+utostr(Val), GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000588 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000589 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000590 GEP->replaceAllUsesWith(NewPtr);
591
592 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000593 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000594 else
595 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000596 }
597
Chris Lattnere40e2d12004-10-08 20:25:55 +0000598 // Delete the old global, now that it is dead.
599 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000600 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000601
602 // Loop over the new globals array deleting any globals that are obviously
603 // dead. This can arise due to scalarization of a structure or an array that
604 // has elements that are dead.
605 unsigned FirstGlobal = 0;
606 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
607 if (NewGlobals[i]->use_empty()) {
608 Globals.erase(NewGlobals[i]);
609 if (FirstGlobal == i) ++FirstGlobal;
610 }
611
612 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000613}
614
Chris Lattner9b34a612004-10-09 21:48:45 +0000615/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000616/// value will trap if the value is dynamically null. PHIs keeps track of any
617/// phi nodes we've seen to avoid reprocessing them.
618static bool AllUsesOfValueWillTrapIfNull(Value *V,
619 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000620 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
621 if (isa<LoadInst>(*UI)) {
622 // Will trap.
623 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
624 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000625 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000626 return false; // Storing the value.
627 }
628 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
629 if (CI->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; // Not calling the ptr
632 }
633 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
634 if (II->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 }
Chris Lattner81686182007-09-13 16:30:19 +0000638 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
639 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000640 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000641 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
642 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
643 // If we've already seen this phi node, ignore it, it has already been
644 // checked.
645 if (PHIs.insert(PN))
646 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000647 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000648 isa<ConstantPointerNull>(UI->getOperand(1))) {
649 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000650 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000651 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000652 return false;
653 }
654 return true;
655}
656
657/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000658/// from GV will trap if the loaded value is null. Note that this also permits
659/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000660static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
661 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
662 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000663 SmallPtrSet<PHINode*, 8> PHIs;
664 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000665 return false;
666 } else if (isa<StoreInst>(*UI)) {
667 // Ignore stores to the global.
668 } else {
669 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000670 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000671 return false;
672 }
673
674 return true;
675}
676
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000677static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000678 LLVMContext *Context) {
Chris Lattner708148e2004-10-10 23:14:11 +0000679 bool Changed = false;
680 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
681 Instruction *I = cast<Instruction>(*UI++);
682 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
683 LI->setOperand(0, NewV);
684 Changed = true;
685 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
686 if (SI->getOperand(1) == V) {
687 SI->setOperand(1, NewV);
688 Changed = true;
689 }
690 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
691 if (I->getOperand(0) == V) {
692 // Calling through the pointer! Turn into a direct call, but be careful
693 // that the pointer is not also being passed as an argument.
694 I->setOperand(0, NewV);
695 Changed = true;
696 bool PassedAsArg = false;
697 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
698 if (I->getOperand(i) == V) {
699 PassedAsArg = true;
700 I->setOperand(i, NewV);
701 }
702
703 if (PassedAsArg) {
704 // Being passed as an argument also. Be careful to not invalidate UI!
705 UI = V->use_begin();
706 }
707 }
708 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
709 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000710 Context->getConstantExprCast(CI->getOpcode(),
711 NewV, CI->getType()), Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000712 if (CI->use_empty()) {
713 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000714 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000715 }
716 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
717 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000718 SmallVector<Constant*, 8> Idxs;
719 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000720 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
721 i != e; ++i)
722 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000723 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000724 else
725 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000726 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000727 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000728 Context->getConstantExprGetElementPtr(NewV, &Idxs[0],
729 Idxs.size()), Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000730 if (GEPI->use_empty()) {
731 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000732 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000733 }
734 }
735 }
736
737 return Changed;
738}
739
740
741/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
742/// value stored into it. If there are uses of the loaded value that would trap
743/// if the loaded value is dynamically null, then we know that they cannot be
744/// reachable with a null optimize away the load.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000745static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000746 LLVMContext *Context) {
Chris Lattner708148e2004-10-10 23:14:11 +0000747 bool Changed = false;
748
Chris Lattner92c6bd22009-01-14 00:12:58 +0000749 // Keep track of whether we are able to remove all the uses of the global
750 // other than the store that defines it.
751 bool AllNonStoreUsesGone = true;
752
Chris Lattner708148e2004-10-10 23:14:11 +0000753 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000754 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
755 User *GlobalUser = *GUI++;
756 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000757 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000758 // If we were able to delete all uses of the loads
759 if (LI->use_empty()) {
760 LI->eraseFromParent();
761 Changed = true;
762 } else {
763 AllNonStoreUsesGone = false;
764 }
765 } else if (isa<StoreInst>(GlobalUser)) {
766 // Ignore the store that stores "LV" to the global.
767 assert(GlobalUser->getOperand(1) == GV &&
768 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000769 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000770 AllNonStoreUsesGone = false;
771
772 // If we get here we could have other crazy uses that are transitively
773 // loaded.
774 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
775 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000776 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000777 }
Chris Lattner708148e2004-10-10 23:14:11 +0000778
779 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000780 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000781 ++NumGlobUses;
782 }
783
Chris Lattner708148e2004-10-10 23:14:11 +0000784 // If we nuked all of the loads, then none of the stores are needed either,
785 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000786 if (AllNonStoreUsesGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000787 DOUT << " *** GLOBAL NOW DEAD!\n";
Owen Anderson50895512009-07-06 18:42:36 +0000788 CleanupConstantGlobalUsers(GV, 0, Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000789 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000790 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000791 ++NumDeleted;
792 }
793 Changed = true;
794 }
795 return Changed;
796}
797
Chris Lattner30ba5692004-10-11 05:54:41 +0000798/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
799/// instructions that are foldable.
Owen Anderson07cf79e2009-07-06 23:00:19 +0000800static void ConstantPropUsersOf(Value *V, LLVMContext *Context) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000801 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
802 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Owen Anderson50895512009-07-06 18:42:36 +0000803 if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000804 I->replaceAllUsesWith(NewC);
805
Chris Lattnerd514d822005-02-01 01:23:31 +0000806 // Advance UI to the next non-I use to avoid invalidating it!
807 // Instructions could multiply use V.
808 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000809 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000810 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000811 }
812}
813
814/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
815/// variable, and transforms the program as if it always contained the result of
816/// the specified malloc. Because it is always the result of the specified
817/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000818/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000819static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000820 MallocInst *MI,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000821 LLVMContext *Context) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000822 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000823 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
824
Reid Spencerb83eb642006-10-20 07:07:24 +0000825 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000826 // If we have an array allocation, transform it to a single element
827 // allocation to make the code below simpler.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000828 Type *NewTy = Context->getArrayType(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000829 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000830 MallocInst *NewMI =
Owen Anderson50dead02009-07-15 23:53:25 +0000831 new MallocInst(NewTy, Context->getNullValue(Type::Int32Ty),
Nate Begeman14b05292005-11-05 09:21:28 +0000832 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000833 Value* Indices[2];
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000834 Indices[0] = Indices[1] = Context->getNullValue(Type::Int32Ty);
Gabor Greif051a9502008-04-06 20:25:17 +0000835 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
836 NewMI->getName()+".el0", MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000837 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000838 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000839 MI = NewMI;
840 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000841
Chris Lattner7a7ed022004-10-16 18:09:00 +0000842 // Create the new global variable. The contents of the malloc'd memory is
843 // undefined, so initialize with an undef value.
Chris Lattner998182b2008-04-26 07:40:11 +0000844 // FIXME: This new global should have the alignment returned by malloc. Code
845 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
846 // this would only guarantee some lower alignment.
Owen Andersone9b11b42009-07-08 19:03:57 +0000847 Constant *Init = Context->getUndef(MI->getAllocatedType());
848 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
849 MI->getAllocatedType(), false,
850 GlobalValue::InternalLinkage, Init,
851 GV->getName()+".body",
852 GV,
853 GV->isThreadLocal());
854
Chris Lattner30ba5692004-10-11 05:54:41 +0000855 // Anything that used the malloc now uses the global directly.
856 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000857
858 Constant *RepValue = NewGV;
859 if (NewGV->getType() != GV->getType()->getElementType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000860 RepValue = Context->getConstantExprBitCast(RepValue,
Reid Spencerd977d862006-12-12 23:36:14 +0000861 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000862
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000863 // If there is a comparison against null, we will insert a global bool to
864 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000865 GlobalVariable *InitBool =
Owen Anderson3d29df32009-07-08 01:26:06 +0000866 new GlobalVariable(*Context, Type::Int1Ty, false,
867 GlobalValue::InternalLinkage,
Owen Andersonb3056fa2009-07-21 18:03:38 +0000868 Context->getFalse(), GV->getName()+".init",
Owen Andersone9b11b42009-07-08 19:03:57 +0000869 GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000870 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000871
Chris Lattner30ba5692004-10-11 05:54:41 +0000872 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000873 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000874 while (!GV->use_empty())
875 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000876 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000877 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000878 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000879 LoadUse = RepValue;
880 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000881 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
882 // Replace the cmp X, 0 with a use of the bool value.
883 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000884 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000885 switch (CI->getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000886 default: llvm_unreachable("Unknown ICmp Predicate!");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000887 case ICmpInst::ICMP_ULT:
888 case ICmpInst::ICMP_SLT:
Owen Andersonb3056fa2009-07-21 18:03:38 +0000889 LV = Context->getFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000890 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000891 case ICmpInst::ICMP_ULE:
892 case ICmpInst::ICMP_SLE:
893 case ICmpInst::ICMP_EQ:
Owen Anderson73c6b712009-07-13 20:58:05 +0000894 LV = BinaryOperator::CreateNot(*Context, LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000895 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000896 case ICmpInst::ICMP_NE:
897 case ICmpInst::ICMP_UGE:
898 case ICmpInst::ICMP_SGE:
899 case ICmpInst::ICMP_UGT:
900 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000901 break; // no change.
902 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000903 CI->replaceAllUsesWith(LV);
904 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000905 }
906 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000907 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000908 } else {
909 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000910 // The global is initialized when the store to it occurs.
Owen Andersonb3056fa2009-07-21 18:03:38 +0000911 new StoreInst(Context->getTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000912 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000913 }
914
Chris Lattnerbc965b92004-12-02 06:25:58 +0000915 // If the initialization boolean was used, insert it, otherwise delete it.
916 if (!InitBoolUsed) {
917 while (!InitBool->use_empty()) // Delete initializations
918 cast<Instruction>(InitBool->use_back())->eraseFromParent();
919 delete InitBool;
920 } else
921 GV->getParent()->getGlobalList().insert(GV, InitBool);
922
923
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000924 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000925 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000926 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000927
928 // To further other optimizations, loop over all users of NewGV and try to
929 // constant prop them. This will promote GEP instructions with constant
930 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Owen Anderson50895512009-07-06 18:42:36 +0000931 ConstantPropUsersOf(NewGV, Context);
Chris Lattner30ba5692004-10-11 05:54:41 +0000932 if (RepValue != NewGV)
Owen Anderson50895512009-07-06 18:42:36 +0000933 ConstantPropUsersOf(RepValue, Context);
Chris Lattner30ba5692004-10-11 05:54:41 +0000934
935 return NewGV;
936}
Chris Lattner708148e2004-10-10 23:14:11 +0000937
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000938/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
939/// to make sure that there are no complex uses of V. We permit simple things
940/// like dereferencing the pointer, but not storing through the address, unless
941/// it is to the specified global.
942static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000943 GlobalVariable *GV,
944 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000945 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foad0906b1b2009-06-06 17:49:35 +0000946 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000947
948 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
949 continue; // Fine, ignore.
950 }
951
952 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000953 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
954 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000955 continue; // Otherwise, storing through it, or storing into GV... fine.
956 }
957
958 if (isa<GetElementPtrInst>(Inst)) {
959 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000960 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000961 continue;
962 }
963
964 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000965 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
966 // cycles.
967 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000968 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
969 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000970 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000971 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000972
973 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
974 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
975 return false;
976 continue;
977 }
978
979 return false;
980 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000981 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000982}
983
Chris Lattner86395032006-09-30 23:32:09 +0000984/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
985/// somewhere. Transform all uses of the allocation into loads from the
986/// global and uses of the resultant pointer. Further, delete the store into
987/// GV. This assumes that these value pass the
988/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
989static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
990 GlobalVariable *GV) {
991 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000992 Instruction *U = cast<Instruction>(*Alloc->use_begin());
993 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +0000994 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
995 // If this is the store of the allocation into the global, remove it.
996 if (SI->getOperand(1) == GV) {
997 SI->eraseFromParent();
998 continue;
999 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001000 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1001 // Insert the load in the corresponding predecessor, not right before the
1002 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001003 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001004 } else if (isa<BitCastInst>(U)) {
1005 // Must be bitcast between the malloc and store to initialize the global.
1006 ReplaceUsesOfMallocWithGlobal(U, GV);
1007 U->eraseFromParent();
1008 continue;
1009 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1010 // If this is a "GEP bitcast" and the user is a store to the global, then
1011 // just process it as a bitcast.
1012 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1013 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1014 if (SI->getOperand(1) == GV) {
1015 // Must be bitcast GEP between the malloc and store to initialize
1016 // the global.
1017 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1018 GEPI->eraseFromParent();
1019 continue;
1020 }
Chris Lattner86395032006-09-30 23:32:09 +00001021 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001022
Chris Lattner86395032006-09-30 23:32:09 +00001023 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001024 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001025 U->replaceUsesOfWith(Alloc, NL);
1026 }
1027}
1028
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001029/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1030/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1031/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001032static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Cheng5d163962009-06-02 00:56:07 +00001033 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1034 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001035 // We permit two users of the load: setcc comparing against the null
1036 // pointer, and a getelementptr of a specific form.
1037 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1038 Instruction *User = cast<Instruction>(*UI);
1039
1040 // Comparison against null is ok.
1041 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1042 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1043 return false;
1044 continue;
1045 }
1046
1047 // getelementptr is also ok, but only a simple form.
1048 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1049 // Must index into the array and into the struct.
1050 if (GEPI->getNumOperands() < 3)
1051 return false;
1052
1053 // Otherwise the GEP is ok.
1054 continue;
1055 }
1056
1057 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001058 if (!LoadUsingPHIsPerLoad.insert(PN))
1059 // This means some phi nodes are dependent on each other.
1060 // Avoid infinite looping!
1061 return false;
1062 if (!LoadUsingPHIs.insert(PN))
1063 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001064 continue;
1065
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001066 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001067 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1068 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001069 return false;
1070
1071 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001072 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001073
1074 // Otherwise we don't know what this is, not ok.
1075 return false;
1076 }
1077
1078 return true;
1079}
1080
1081
1082/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1083/// GV are simple enough to perform HeapSRA, return true.
1084static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1085 MallocInst *MI) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001086 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Cheng5d163962009-06-02 00:56:07 +00001087 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001088 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1089 ++UI)
Evan Cheng5d163962009-06-02 00:56:07 +00001090 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1091 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1092 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001093 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001094 LoadUsingPHIsPerLoad.clear();
1095 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001096
1097 // If we reach here, we know that all uses of the loads and transitive uses
1098 // (through PHI nodes) are simple enough to transform. However, we don't know
1099 // that all inputs the to the PHI nodes are in the same equivalence sets.
1100 // Check to verify that all operands of the PHIs are either PHIS that can be
1101 // transformed, loads from GV, or MI itself.
1102 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1103 E = LoadUsingPHIs.end(); I != E; ++I) {
1104 PHINode *PN = *I;
1105 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1106 Value *InVal = PN->getIncomingValue(op);
1107
1108 // PHI of the stored value itself is ok.
1109 if (InVal == MI) continue;
1110
1111 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1112 // One of the PHIs in our set is (optimistically) ok.
1113 if (LoadUsingPHIs.count(InPN))
1114 continue;
1115 return false;
1116 }
1117
1118 // Load from GV is ok.
1119 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1120 if (LI->getOperand(0) == GV)
1121 continue;
1122
1123 // UNDEF? NULL?
1124
1125 // Anything else is rejected.
1126 return false;
1127 }
1128 }
1129
Chris Lattner86395032006-09-30 23:32:09 +00001130 return true;
1131}
1132
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001133static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1134 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001135 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001136 LLVMContext *Context) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001137 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1138
1139 if (FieldNo >= FieldVals.size())
1140 FieldVals.resize(FieldNo+1);
1141
1142 // If we already have this value, just reuse the previously scalarized
1143 // version.
1144 if (Value *FieldVal = FieldVals[FieldNo])
1145 return FieldVal;
1146
1147 // Depending on what instruction this is, we have several cases.
1148 Value *Result;
1149 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1150 // This is a scalarized version of the load from the global. Just create
1151 // a new Load of the scalarized global.
1152 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1153 InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001154 PHIsToRewrite, Context),
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001155 LI->getName()+".f" + utostr(FieldNo), LI);
1156 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1157 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1158 // field.
1159 const StructType *ST =
1160 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1161
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001162 Result =
1163 PHINode::Create(Context->getPointerTypeUnqual(ST->getElementType(FieldNo)),
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001164 PN->getName()+".f"+utostr(FieldNo), PN);
1165 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1166 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001167 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001168 Result = 0;
1169 }
1170
1171 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001172}
1173
Chris Lattner330245e2007-09-13 17:29:05 +00001174/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1175/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001176static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1177 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001178 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001179 LLVMContext *Context) {
Chris Lattner330245e2007-09-13 17:29:05 +00001180 // If this is a comparison against null, handle it.
1181 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1182 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1183 // If we have a setcc of the loaded pointer, we can use a setcc of any
1184 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001185 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001186 InsertedScalarizedValues, PHIsToRewrite,
1187 Context);
Chris Lattner330245e2007-09-13 17:29:05 +00001188
Owen Anderson333c4002009-07-09 23:48:35 +00001189 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1190 Context->getNullValue(NPtr->getType()),
1191 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001192 SCI->replaceAllUsesWith(New);
1193 SCI->eraseFromParent();
1194 return;
1195 }
1196
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001197 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001198 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1199 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1200 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001201
Chris Lattnera637a8b2007-09-13 18:00:31 +00001202 // Load the pointer for this field.
1203 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001204 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001205 InsertedScalarizedValues, PHIsToRewrite,
1206 Context);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001207
1208 // Create the new GEP idx vector.
1209 SmallVector<Value*, 8> GEPIdx;
1210 GEPIdx.push_back(GEPI->getOperand(1));
1211 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1212
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001213 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1214 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001215 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001216 GEPI->replaceAllUsesWith(NGEPI);
1217 GEPI->eraseFromParent();
1218 return;
1219 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001220
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001221 // Recursively transform the users of PHI nodes. This will lazily create the
1222 // PHIs that are needed for individual elements. Keep track of what PHIs we
1223 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1224 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1225 // already been seen first by another load, so its uses have already been
1226 // processed.
1227 PHINode *PN = cast<PHINode>(LoadUser);
1228 bool Inserted;
1229 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1230 tie(InsertPos, Inserted) =
1231 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1232 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001233
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001234 // If this is the first time we've seen this PHI, recursively process all
1235 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001236 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1237 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001238 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1239 Context);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001240 }
Chris Lattner330245e2007-09-13 17:29:05 +00001241}
1242
Chris Lattner86395032006-09-30 23:32:09 +00001243/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1244/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1245/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001246/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001247static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001248 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001249 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001250 LLVMContext *Context) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001251 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001252 UI != E; ) {
1253 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001254 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1255 Context);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001256 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001257
1258 if (Load->use_empty()) {
1259 Load->eraseFromParent();
1260 InsertedScalarizedValues.erase(Load);
1261 }
Chris Lattner86395032006-09-30 23:32:09 +00001262}
1263
1264/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1265/// it up into multiple allocations of arrays of the fields.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001266static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001267 LLVMContext *Context){
Bill Wendling0a81aac2006-11-26 10:02:32 +00001268 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +00001269 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1270
1271 // There is guaranteed to be at least one use of the malloc (storing
1272 // it into GV). If there are other uses, change them to be uses of
1273 // the global to simplify later code. This also deletes the store
1274 // into GV.
1275 ReplaceUsesOfMallocWithGlobal(MI, GV);
1276
1277 // Okay, at this point, there are no users of the malloc. Insert N
1278 // new mallocs at the same place as MI, and N globals.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001279 std::vector<Value*> FieldGlobals;
Chris Lattner86395032006-09-30 23:32:09 +00001280 std::vector<MallocInst*> FieldMallocs;
1281
1282 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1283 const Type *FieldTy = STy->getElementType(FieldNo);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001284 const Type *PFieldTy = Context->getPointerTypeUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001285
1286 GlobalVariable *NGV =
Owen Andersone9b11b42009-07-08 19:03:57 +00001287 new GlobalVariable(*GV->getParent(),
1288 PFieldTy, false, GlobalValue::InternalLinkage,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001289 Context->getNullValue(PFieldTy),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001290 GV->getName() + ".f" + utostr(FieldNo), GV,
1291 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001292 FieldGlobals.push_back(NGV);
1293
Owen Anderson50dead02009-07-15 23:53:25 +00001294 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
Chris Lattner86395032006-09-30 23:32:09 +00001295 MI->getName() + ".f" + utostr(FieldNo),MI);
1296 FieldMallocs.push_back(NMI);
1297 new StoreInst(NMI, NGV, MI);
1298 }
1299
1300 // The tricky aspect of this transformation is handling the case when malloc
1301 // fails. In the original code, malloc failing would set the result pointer
1302 // of malloc to null. In this case, some mallocs could succeed and others
1303 // could fail. As such, we emit code that looks like this:
1304 // F0 = malloc(field0)
1305 // F1 = malloc(field1)
1306 // F2 = malloc(field2)
1307 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1308 // if (F0) { free(F0); F0 = 0; }
1309 // if (F1) { free(F1); F1 = 0; }
1310 // if (F2) { free(F2); F2 = 0; }
1311 // }
1312 Value *RunningOr = 0;
1313 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Owen Anderson333c4002009-07-09 23:48:35 +00001314 Value *Cond = new ICmpInst(MI, ICmpInst::ICMP_EQ, FieldMallocs[i],
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001315 Context->getNullValue(FieldMallocs[i]->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001316 "isnull");
Chris Lattner86395032006-09-30 23:32:09 +00001317 if (!RunningOr)
1318 RunningOr = Cond; // First seteq
1319 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001320 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Chris Lattner86395032006-09-30 23:32:09 +00001321 }
1322
1323 // Split the basic block at the old malloc.
1324 BasicBlock *OrigBB = MI->getParent();
1325 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1326
1327 // Create the block to check the first condition. Put all these blocks at the
1328 // end of the function as they are unlikely to be executed.
Gabor Greif051a9502008-04-06 20:25:17 +00001329 BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
1330 OrigBB->getParent());
Chris Lattner86395032006-09-30 23:32:09 +00001331
1332 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1333 // branch on RunningOr.
1334 OrigBB->getTerminator()->eraseFromParent();
Gabor Greif051a9502008-04-06 20:25:17 +00001335 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Chris Lattner86395032006-09-30 23:32:09 +00001336
1337 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1338 // pointer, because some may be null while others are not.
1339 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1340 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Owen Anderson333c4002009-07-09 23:48:35 +00001341 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001342 Context->getNullValue(GVVal->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001343 "tmp");
Gabor Greif051a9502008-04-06 20:25:17 +00001344 BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
1345 BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
1346 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001347
1348 // Fill in FreeBlock.
1349 new FreeInst(GVVal, FreeBlock);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001350 new StoreInst(Context->getNullValue(GVVal->getType()), FieldGlobals[i],
Chris Lattner86395032006-09-30 23:32:09 +00001351 FreeBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001352 BranchInst::Create(NextBlock, FreeBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001353
1354 NullPtrBlock = NextBlock;
1355 }
1356
Gabor Greif051a9502008-04-06 20:25:17 +00001357 BranchInst::Create(ContBB, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001358
1359 // MI is no longer needed, remove it.
1360 MI->eraseFromParent();
1361
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001362 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1363 /// update all uses of the load, keep track of what scalarized loads are
1364 /// inserted for a given load.
1365 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1366 InsertedScalarizedValues[GV] = FieldGlobals;
1367
1368 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Chris Lattner86395032006-09-30 23:32:09 +00001369
1370 // Okay, the malloc site is completely handled. All of the uses of GV are now
1371 // loads, and all uses of those loads are simple. Rewrite them to use loads
1372 // of the per-field globals instead.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001373 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1374 Instruction *User = cast<Instruction>(*UI++);
1375
1376 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001377 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1378 Context);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001379 continue;
Chris Lattner39ff1e22007-01-09 23:29:37 +00001380 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001381
1382 // Must be a store of null.
1383 StoreInst *SI = cast<StoreInst>(User);
1384 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1385 "Unexpected heap-sra user!");
1386
1387 // Insert a store of null into each global.
1388 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1389 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001390 Constant *Null = Context->getNullValue(PT->getElementType());
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001391 new StoreInst(Null, FieldGlobals[i], SI);
1392 }
1393 // Erase the original store.
1394 SI->eraseFromParent();
Chris Lattner86395032006-09-30 23:32:09 +00001395 }
1396
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001397 // While we have PHIs that are interesting to rewrite, do it.
1398 while (!PHIsToRewrite.empty()) {
1399 PHINode *PN = PHIsToRewrite.back().first;
1400 unsigned FieldNo = PHIsToRewrite.back().second;
1401 PHIsToRewrite.pop_back();
1402 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1403 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1404
1405 // Add all the incoming values. This can materialize more phis.
1406 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1407 Value *InVal = PN->getIncomingValue(i);
1408 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001409 PHIsToRewrite, Context);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001410 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1411 }
1412 }
1413
1414 // Drop all inter-phi links and any loads that made it this far.
1415 for (DenseMap<Value*, std::vector<Value*> >::iterator
1416 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1417 I != E; ++I) {
1418 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1419 PN->dropAllReferences();
1420 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1421 LI->dropAllReferences();
1422 }
1423
1424 // Delete all the phis and loads now that inter-references are dead.
1425 for (DenseMap<Value*, std::vector<Value*> >::iterator
1426 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1427 I != E; ++I) {
1428 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1429 PN->eraseFromParent();
1430 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1431 LI->eraseFromParent();
1432 }
1433
Chris Lattner86395032006-09-30 23:32:09 +00001434 // The old global is now dead, remove it.
1435 GV->eraseFromParent();
1436
1437 ++NumHeapSRA;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001438 return cast<GlobalVariable>(FieldGlobals[0]);
Chris Lattner86395032006-09-30 23:32:09 +00001439}
1440
Chris Lattnere61d0a62008-12-15 21:02:25 +00001441/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1442/// pointer global variable with a single value stored it that is a malloc or
1443/// cast of malloc.
1444static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1445 MallocInst *MI,
1446 Module::global_iterator &GVI,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001447 TargetData &TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001448 LLVMContext *Context) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001449 // If this is a malloc of an abstract type, don't touch it.
1450 if (!MI->getAllocatedType()->isSized())
1451 return false;
1452
1453 // We can't optimize this global unless all uses of it are *known* to be
1454 // of the malloc value, not of the null initializer value (consider a use
1455 // that compares the global's value against zero to see if the malloc has
1456 // been reached). To do this, we check to see if all uses of the global
1457 // would trap if the global were null: this proves that they must all
1458 // happen after the malloc.
1459 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1460 return false;
1461
1462 // We can't optimize this if the malloc itself is used in a complex way,
1463 // for example, being stored into multiple globals. This allows the
1464 // malloc to be stored into the specified global, loaded setcc'd, and
1465 // GEP'd. These are all things we could transform to using the global
1466 // for.
1467 {
1468 SmallPtrSet<PHINode*, 8> PHIs;
1469 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1470 return false;
1471 }
1472
1473
1474 // If we have a global that is only initialized with a fixed size malloc,
1475 // transform the program to use global memory instead of malloc'd memory.
1476 // This eliminates dynamic allocation, avoids an indirection accessing the
1477 // data, and exposes the resultant global to further GlobalOpt.
1478 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1479 // Restrict this transformation to only working on small allocations
1480 // (2048 bytes currently), as we don't want to introduce a 16M global or
1481 // something.
1482 if (NElements->getZExtValue()*
Duncan Sands777d2302009-05-09 07:06:46 +00001483 TD.getTypeAllocSize(MI->getAllocatedType()) < 2048) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001484 GVI = OptimizeGlobalAddressOfMalloc(GV, MI, Context);
Chris Lattnere61d0a62008-12-15 21:02:25 +00001485 return true;
1486 }
1487 }
1488
1489 // If the allocation is an array of structures, consider transforming this
1490 // into multiple malloc'd arrays, one for each field. This is basically
1491 // SRoA for malloc'd memory.
Chris Lattner101f44e2008-12-15 21:44:34 +00001492 const Type *AllocTy = MI->getAllocatedType();
1493
1494 // If this is an allocation of a fixed size array of structs, analyze as a
1495 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1496 if (!MI->isArrayAllocation())
1497 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1498 AllocTy = AT->getElementType();
1499
1500 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001501 // This the structure has an unreasonable number of fields, leave it
1502 // alone.
Chris Lattner101f44e2008-12-15 21:44:34 +00001503 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001504 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner101f44e2008-12-15 21:44:34 +00001505
1506 // If this is a fixed size array, transform the Malloc to be an alloc of
1507 // structs. malloc [100 x struct],1 -> malloc struct, 100
1508 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1509 MallocInst *NewMI =
Owen Anderson50dead02009-07-15 23:53:25 +00001510 new MallocInst(AllocSTy,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001511 Context->getConstantInt(Type::Int32Ty, AT->getNumElements()),
Chris Lattner101f44e2008-12-15 21:44:34 +00001512 "", MI);
1513 NewMI->takeName(MI);
1514 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1515 MI->replaceAllUsesWith(Cast);
1516 MI->eraseFromParent();
1517 MI = NewMI;
1518 }
1519
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001520 GVI = PerformHeapAllocSRoA(GV, MI, Context);
Chris Lattnere61d0a62008-12-15 21:02:25 +00001521 return true;
1522 }
1523 }
1524
1525 return false;
1526}
Chris Lattner86395032006-09-30 23:32:09 +00001527
Chris Lattner9b34a612004-10-09 21:48:45 +00001528// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1529// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001530static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001531 Module::global_iterator &GVI,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001532 TargetData &TD, LLVMContext *Context) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001533 // Ignore no-op GEPs and bitcasts.
1534 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001535
Chris Lattner708148e2004-10-10 23:14:11 +00001536 // If we are dealing with a pointer global that is initialized to null and
1537 // only has one (non-null) value stored into it, then we can optimize any
1538 // users of the loaded value (often calls and loads) that would trap if the
1539 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001540 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1541 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001542 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1543 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001544 SOVC =
1545 Context->getConstantExprBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001546
Chris Lattner708148e2004-10-10 23:14:11 +00001547 // Optimize away any trapping uses of the loaded value.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001548 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
Chris Lattner8be80122004-10-10 17:07:12 +00001549 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001550 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001551 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD, Context))
Chris Lattnere61d0a62008-12-15 21:02:25 +00001552 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001553 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001554 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001555
Chris Lattner9b34a612004-10-09 21:48:45 +00001556 return false;
1557}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001558
Chris Lattner58e44f42008-01-14 01:17:44 +00001559/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1560/// two values ever stored into GV are its initializer and OtherVal. See if we
1561/// can shrink the global into a boolean and select between the two values
1562/// whenever it is used. This exposes the values to other scalar optimizations.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001563static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001564 LLVMContext *Context) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001565 const Type *GVElType = GV->getType()->getElementType();
1566
1567 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001568 // an FP value, pointer or vector, don't do this optimization because a select
1569 // between them is very expensive and unlikely to lead to later
1570 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1571 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner58e44f42008-01-14 01:17:44 +00001572 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
Chris Lattner6f6923f2009-03-07 23:32:02 +00001573 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
Chris Lattner58e44f42008-01-14 01:17:44 +00001574 return false;
1575
1576 // Walk the use list of the global seeing if all the uses are load or store.
1577 // If there is anything else, bail out.
1578 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel771281f2009-03-06 01:39:36 +00001579 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattner58e44f42008-01-14 01:17:44 +00001580 return false;
1581
1582 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1583
Chris Lattner96a86b22004-12-12 05:53:50 +00001584 // Create the new global, initializing it to false.
Owen Anderson3d29df32009-07-08 01:26:06 +00001585 GlobalVariable *NewGV = new GlobalVariable(*Context, Type::Int1Ty, false,
Owen Andersonb3056fa2009-07-21 18:03:38 +00001586 GlobalValue::InternalLinkage, Context->getFalse(),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001587 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001588 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001589 GV->getParent()->getGlobalList().insert(GV, NewGV);
1590
1591 Constant *InitVal = GV->getInitializer();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001592 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001593
1594 // If initialized to zero and storing one into the global, we can use a cast
1595 // instead of a select to synthesize the desired value.
1596 bool IsOneZero = false;
1597 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001598 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001599
1600 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001601 Instruction *UI = cast<Instruction>(GV->use_back());
1602 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001603 // Change the store into a boolean store.
1604 bool StoringOther = SI->getOperand(0) == OtherVal;
1605 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001606 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001607 if (StoringOther || SI->getOperand(0) == InitVal)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001608 StoreVal = Context->getConstantInt(Type::Int1Ty, StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001609 else {
1610 // Otherwise, we are storing a previously loaded copy. To do this,
1611 // change the copy from copying the original value to just copying the
1612 // bool.
1613 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1614
1615 // If we're already replaced the input, StoredVal will be a cast or
1616 // select instruction. If not, it will be a load of the original
1617 // global.
1618 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1619 assert(LI->getOperand(0) == GV && "Not a copy!");
1620 // Insert a new load, to preserve the saved value.
1621 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1622 } else {
1623 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1624 "This is not a form that we understand!");
1625 StoreVal = StoredVal->getOperand(0);
1626 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1627 }
1628 }
1629 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001630 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001631 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001632 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001633 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001634 Value *NSI;
1635 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001636 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001637 else
Gabor Greif051a9502008-04-06 20:25:17 +00001638 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001639 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001640 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001641 }
1642 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001643 }
1644
1645 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001646 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001647}
1648
1649
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001650/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1651/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001652bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001653 Module::global_iterator &GVI) {
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001654 SmallPtrSet<PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001655 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001656 GV->removeDeadConstantUsers();
1657
1658 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001659 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001660 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001661 ++NumDeleted;
1662 return true;
1663 }
1664
1665 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001666#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001667 cerr << "Global: " << *GV;
1668 cerr << " isLoaded = " << GS.isLoaded << "\n";
1669 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001670 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001671 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1672 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1673 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1674 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001675 }
1676 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001677 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001678 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001679 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001680 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001681 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001682 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001683 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001684 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001685#endif
1686
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001687 // If this is a first class global and has only one accessing function
1688 // and this function is main (which we know is not recursive we can make
1689 // this global a local variable) we replace the global with a local alloca
1690 // in this function.
1691 //
Dan Gohman399101a2008-05-23 00:17:26 +00001692 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001693 // are just replacing static memory to stack memory.
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001694 //
1695 // If the global is in different address space, don't bring it to stack.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001696 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001697 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001698 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001699 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001700 GS.AccessingFunction->hasExternalLinkage() &&
1701 GV->getType()->getAddressSpace() == 0) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001702 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001703 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1704 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001705 // FIXME: Pass Global's alignment when globals have alignment
Owen Anderson50dead02009-07-15 23:53:25 +00001706 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001707 if (!isa<UndefValue>(GV->getInitializer()))
1708 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001709
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001710 GV->replaceAllUsesWith(Alloca);
1711 GV->eraseFromParent();
1712 ++NumLocalized;
1713 return true;
1714 }
Chris Lattnercff16732006-09-30 19:40:30 +00001715
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001716 // If the global is never loaded (but may be stored to), it is dead.
1717 // Delete it now.
1718 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001719 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001720
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001721 // Delete any stores we can find to the global. We may not be able to
1722 // make it completely dead though.
Owen Anderson50895512009-07-06 18:42:36 +00001723 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1724 Context);
Chris Lattner930f4752004-10-09 03:32:52 +00001725
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001726 // If the global is dead now, delete it.
1727 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001728 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001729 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001730 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001731 }
Chris Lattner930f4752004-10-09 03:32:52 +00001732 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001733
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001734 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001735 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001736 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001737
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001738 // Clean up any obviously simplifiable users now.
Owen Anderson50895512009-07-06 18:42:36 +00001739 CleanupConstantGlobalUsers(GV, GV->getInitializer(), Context);
Misha Brukmanfd939082005-04-21 23:48:37 +00001740
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001741 // If the global is dead now, just nuke it.
1742 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001743 DOUT << " *** Marking constant allowed us to simplify "
1744 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001745 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001746 ++NumDeleted;
1747 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001748
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001749 ++NumMarked;
1750 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001751 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Chris Lattner998182b2008-04-26 07:40:11 +00001752 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001753 getAnalysis<TargetData>(),
1754 Context)) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001755 GVI = FirstNewGV; // Don't skip the newly produced globals!
1756 return true;
1757 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001758 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001759 // If the initial value for the global was an undef value, and if only
1760 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001761 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001762 // global. This allows us to mark it constant.
1763 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1764 if (isa<UndefValue>(GV->getInitializer())) {
1765 // Change the initial value here.
1766 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001767
Chris Lattner96a86b22004-12-12 05:53:50 +00001768 // Clean up any obviously simplifiable users now.
Owen Anderson50895512009-07-06 18:42:36 +00001769 CleanupConstantGlobalUsers(GV, GV->getInitializer(), Context);
Misha Brukmanfd939082005-04-21 23:48:37 +00001770
Chris Lattner96a86b22004-12-12 05:53:50 +00001771 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001772 DOUT << " *** Substituting initializer allowed us to "
1773 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001774 GV->eraseFromParent();
1775 ++NumDeleted;
1776 } else {
1777 GVI = GV;
1778 }
1779 ++NumSubstitute;
1780 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001781 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001782
Chris Lattner9b34a612004-10-09 21:48:45 +00001783 // Try to optimize globals based on the knowledge that only one value
1784 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001785 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001786 getAnalysis<TargetData>(), Context))
Chris Lattner9b34a612004-10-09 21:48:45 +00001787 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001788
1789 // Otherwise, if the global was not a boolean, we can shrink it to be a
1790 // boolean.
1791 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001792 if (TryToShrinkGlobalToBoolean(GV, SOVConstant, Context)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001793 ++NumShrunkToBool;
1794 return true;
1795 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001796 }
1797 }
1798 return false;
1799}
1800
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001801/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1802/// function, changing them to FastCC.
1803static void ChangeCalleesToFastCall(Function *F) {
1804 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001805 CallSite User(cast<Instruction>(*UI));
1806 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001807 }
1808}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001809
Devang Patel05988662008-09-25 21:00:45 +00001810static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001811 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001812 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001813 continue;
1814
Duncan Sands548448a2008-02-18 17:32:13 +00001815 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001816 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001817 }
1818
1819 return Attrs;
1820}
1821
1822static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001823 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001824 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001825 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001826 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001827 }
1828}
1829
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001830bool GlobalOpt::OptimizeFunctions(Module &M) {
1831 bool Changed = false;
1832 // Optimize functions.
1833 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1834 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001835 // Functions without names cannot be referenced outside this module.
1836 if (!F->hasName() && !F->isDeclaration())
1837 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001838 F->removeDeadConstantUsers();
Rafael Espindolabb46f522009-01-15 20:18:42 +00001839 if (F->use_empty() && (F->hasLocalLinkage() ||
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001840 F->hasLinkOnceLinkage())) {
1841 M.getFunctionList().erase(F);
1842 Changed = true;
1843 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001844 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001845 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001846 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001847 // If this function has C calling conventions, is not a varargs
1848 // function, and is only called directly, promote it to use the Fast
1849 // calling convention.
1850 F->setCallingConv(CallingConv::Fast);
1851 ChangeCalleesToFastCall(F);
1852 ++NumFastCallFns;
1853 Changed = true;
1854 }
1855
Devang Patel05988662008-09-25 21:00:45 +00001856 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001857 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001858 // The function is not used by a trampoline intrinsic, so it is safe
1859 // to remove the 'nest' attribute.
1860 RemoveNestAttribute(F);
1861 ++NumNestRemoved;
1862 Changed = true;
1863 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001864 }
1865 }
1866 return Changed;
1867}
1868
1869bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1870 bool Changed = false;
1871 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1872 GVI != E; ) {
1873 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001874 // Global variables without names cannot be referenced outside this module.
1875 if (!GV->hasName() && !GV->isDeclaration())
1876 GV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolabb46f522009-01-15 20:18:42 +00001877 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001878 GV->hasInitializer())
1879 Changed |= ProcessInternalGlobal(GV, GVI);
1880 }
1881 return Changed;
1882}
1883
1884/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1885/// initializers have an init priority of 65535.
1886GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001887 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1888 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001889 if (I->getName() == "llvm.global_ctors") {
1890 // Found it, verify it's an array of { int, void()* }.
1891 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1892 if (!ATy) return 0;
1893 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1894 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc5b206b2006-12-31 05:48:39 +00001895 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001896 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1897 if (!PFTy) return 0;
1898 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1899 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1900 FTy->getNumParams() != 0)
1901 return 0;
1902
1903 // Verify that the initializer is simple enough for us to handle.
1904 if (!I->hasInitializer()) return 0;
1905 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1906 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001907 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1908 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001909 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1910 continue;
1911
1912 // Must have a function or null ptr.
1913 if (!isa<Function>(CS->getOperand(1)))
1914 return 0;
1915
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001916 // Init priority must be standard.
1917 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001918 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001919 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001920 } else {
1921 return 0;
1922 }
1923
1924 return I;
1925 }
1926 return 0;
1927}
1928
Chris Lattnerdb973e62005-09-26 02:31:18 +00001929/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1930/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001931static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1932 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1933 std::vector<Function*> Result;
1934 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001935 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1936 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001937 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1938 }
1939 return Result;
1940}
1941
Chris Lattnerdb973e62005-09-26 02:31:18 +00001942/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1943/// specified array, returning the new global to use.
1944static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001945 const std::vector<Function*> &Ctors,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001946 LLVMContext *Context) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001947 // If we made a change, reassemble the initializer list.
1948 std::vector<Constant*> CSVals;
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001949 CSVals.push_back(Context->getConstantInt(Type::Int32Ty, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001950 CSVals.push_back(0);
1951
1952 // Create the new init list.
1953 std::vector<Constant*> CAList;
1954 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001955 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001956 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001957 } else {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001958 const Type *FTy = Context->getFunctionType(Type::VoidTy, false);
1959 const PointerType *PFTy = Context->getPointerTypeUnqual(FTy);
1960 CSVals[1] = Context->getNullValue(PFTy);
1961 CSVals[0] = Context->getConstantInt(Type::Int32Ty, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001962 }
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001963 CAList.push_back(Context->getConstantStruct(CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001964 }
1965
1966 // Create the array initializer.
1967 const Type *StructTy =
1968 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001969 Constant *CA = Context->getConstantArray(ArrayType::get(StructTy,
1970 CAList.size()), CAList);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001971
1972 // If we didn't change the number of elements, don't create a new GV.
1973 if (CA->getType() == GCL->getInitializer()->getType()) {
1974 GCL->setInitializer(CA);
1975 return GCL;
1976 }
1977
1978 // Create the new global and insert it next to the existing list.
Owen Anderson3d29df32009-07-08 01:26:06 +00001979 GlobalVariable *NGV = new GlobalVariable(*Context, CA->getType(),
1980 GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001981 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001982 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001983 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001984 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001985
1986 // Nuke the old list, replacing any uses with the new one.
1987 if (!GCL->use_empty()) {
1988 Constant *V = NGV;
1989 if (V->getType() != GCL->getType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001990 V = Context->getConstantExprBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001991 GCL->replaceAllUsesWith(V);
1992 }
1993 GCL->eraseFromParent();
1994
1995 if (Ctors.size())
1996 return NGV;
1997 else
1998 return 0;
1999}
Chris Lattner79c11012005-09-26 04:44:35 +00002000
2001
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002002static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00002003 Value *V) {
2004 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2005 Constant *R = ComputedValues[V];
2006 assert(R && "Reference to an uncomputed value!");
2007 return R;
2008}
2009
2010/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2011/// enough for us to understand. In particular, if it is a cast of something,
2012/// we punt. We basically just support direct accesses to globals and GEP's of
2013/// globals. This should be kept up to date with CommitValueTo.
Owen Anderson07cf79e2009-07-06 23:00:19 +00002014static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext *Context) {
Chris Lattner231308c2005-09-27 04:50:03 +00002015 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolabb46f522009-01-15 20:18:42 +00002016 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002017 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00002018 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00002019 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002020 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2021 // Handle a constantexpr gep.
2022 if (CE->getOpcode() == Instruction::GetElementPtr &&
2023 isa<GlobalVariable>(CE->getOperand(0))) {
2024 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolabb46f522009-01-15 20:18:42 +00002025 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002026 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00002027 return GV->hasInitializer() &&
Owen Anderson50895512009-07-06 18:42:36 +00002028 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2029 Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002030 }
Chris Lattner79c11012005-09-26 04:44:35 +00002031 return false;
2032}
2033
Chris Lattner798b4d52005-09-26 06:52:44 +00002034/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2035/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2036/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2037static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002038 ConstantExpr *Addr, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +00002039 LLVMContext *Context) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002040 // Base case of the recursion.
2041 if (OpNo == Addr->getNumOperands()) {
2042 assert(Val->getType() == Init->getType() && "Type mismatch!");
2043 return Val;
2044 }
2045
2046 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2047 std::vector<Constant*> Elts;
2048
2049 // Break up the constant into its elements.
2050 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002051 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2052 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002053 } else if (isa<ConstantAggregateZero>(Init)) {
2054 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002055 Elts.push_back(Context->getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002056 } else if (isa<UndefValue>(Init)) {
2057 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002058 Elts.push_back(Context->getUndef(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002059 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002060 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002061 " ConstantFoldLoadThroughGEPConstantExpr");
2062 }
2063
2064 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002065 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2066 unsigned Idx = CU->getZExtValue();
2067 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002068 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002069
2070 // Return the modified struct.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002071 return Context->getConstantStruct(&Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002072 } else {
2073 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2074 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2075
2076 // Break up the array into elements.
2077 std::vector<Constant*> Elts;
2078 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002079 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2080 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002081 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002082 Constant *Elt = Context->getNullValue(ATy->getElementType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002083 Elts.assign(ATy->getNumElements(), Elt);
2084 } else if (isa<UndefValue>(Init)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002085 Constant *Elt = Context->getUndef(ATy->getElementType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002086 Elts.assign(ATy->getNumElements(), Elt);
2087 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002088 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002089 " ConstantFoldLoadThroughGEPConstantExpr");
2090 }
2091
Reid Spencerb83eb642006-10-20 07:07:24 +00002092 assert(CI->getZExtValue() < ATy->getNumElements());
2093 Elts[CI->getZExtValue()] =
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002094 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
2095 return Context->getConstantArray(ATy, Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002096 }
2097}
2098
Chris Lattner79c11012005-09-26 04:44:35 +00002099/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2100/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002101static void CommitValueTo(Constant *Val, Constant *Addr,
Owen Anderson07cf79e2009-07-06 23:00:19 +00002102 LLVMContext *Context) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002103 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2104 assert(GV->hasInitializer());
2105 GV->setInitializer(Val);
2106 return;
2107 }
2108
2109 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2110 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2111
2112 Constant *Init = GV->getInitializer();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002113 Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002114 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00002115}
2116
Chris Lattner562a0552005-09-26 05:16:34 +00002117/// ComputeLoadResult - Return the value that would be computed by a load from
2118/// P after the stores reflected by 'memory' have been performed. If we can't
2119/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002120static Constant *ComputeLoadResult(Constant *P,
Owen Anderson50895512009-07-06 18:42:36 +00002121 const DenseMap<Constant*, Constant*> &Memory,
Owen Anderson07cf79e2009-07-06 23:00:19 +00002122 LLVMContext *Context) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002123 // If this memory location has been recently stored, use the stored value: it
2124 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002125 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002126 if (I != Memory.end()) return I->second;
2127
2128 // Access it.
2129 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2130 if (GV->hasInitializer())
2131 return GV->getInitializer();
2132 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002133 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002134
2135 // Handle a constantexpr getelementptr.
2136 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2137 if (CE->getOpcode() == Instruction::GetElementPtr &&
2138 isa<GlobalVariable>(CE->getOperand(0))) {
2139 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2140 if (GV->hasInitializer())
Owen Anderson50895512009-07-06 18:42:36 +00002141 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2142 Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002143 }
2144
2145 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002146}
2147
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002148/// EvaluateFunction - Evaluate a call to function F, returning true if
2149/// successful, false if we can't evaluate it. ActualArgs contains the formal
2150/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002151static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002152 const std::vector<Constant*> &ActualArgs,
2153 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002154 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002155 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002156 // Check to see if this function is already executing (recursion). If so,
2157 // bail out. TODO: we might want to accept limited recursion.
2158 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2159 return false;
2160
Owen Anderson07cf79e2009-07-06 23:00:19 +00002161 LLVMContext *Context = F->getContext();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002162
Chris Lattnercd271422005-09-27 04:45:34 +00002163 CallStack.push_back(F);
2164
Chris Lattner79c11012005-09-26 04:44:35 +00002165 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002166 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002167
2168 // Initialize arguments to the incoming values specified.
2169 unsigned ArgNo = 0;
2170 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2171 ++AI, ++ArgNo)
2172 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002173
Chris Lattnercdf98be2005-09-26 04:57:38 +00002174 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2175 /// we can only evaluate any one basic block at most once. This set keeps
2176 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002177 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002178
Chris Lattner79c11012005-09-26 04:44:35 +00002179 // CurInst - The current instruction we're evaluating.
2180 BasicBlock::iterator CurInst = F->begin()->begin();
2181
2182 // This is the main evaluation loop.
2183 while (1) {
2184 Constant *InstResult = 0;
2185
2186 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002187 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002188 Constant *Ptr = getVal(Values, SI->getOperand(1));
Owen Anderson50895512009-07-06 18:42:36 +00002189 if (!isSimpleEnoughPointerToCommit(Ptr, Context))
Chris Lattner79c11012005-09-26 04:44:35 +00002190 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002191 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002192 Constant *Val = getVal(Values, SI->getOperand(0));
2193 MutatedMemory[Ptr] = Val;
2194 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002195 InstResult = Context->getConstantExpr(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002196 getVal(Values, BO->getOperand(0)),
2197 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002198 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002199 InstResult = Context->getConstantExprCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002200 getVal(Values, CI->getOperand(0)),
2201 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002202 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002203 InstResult = Context->getConstantExprCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002204 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002205 CI->getType());
2206 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002207 InstResult =
2208 Context->getConstantExprSelect(getVal(Values, SI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002209 getVal(Values, SI->getOperand(1)),
2210 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002211 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2212 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002213 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002214 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2215 i != e; ++i)
2216 GEPOps.push_back(getVal(Values, *i));
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002217 InstResult =
2218 Context->getConstantExprGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002219 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002220 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002221 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Owen Anderson50895512009-07-06 18:42:36 +00002222 MutatedMemory, Context);
Chris Lattnercd271422005-09-27 04:45:34 +00002223 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002224 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002225 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002226 const Type *Ty = AI->getType()->getElementType();
Owen Anderson3d29df32009-07-08 01:26:06 +00002227 AllocaTmps.push_back(new GlobalVariable(*Context, Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002228 GlobalValue::InternalLinkage,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002229 Context->getUndef(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002230 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002231 InstResult = AllocaTmps.back();
2232 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002233
2234 // Debug info can safely be ignored here.
2235 if (isa<DbgInfoIntrinsic>(CI)) {
2236 ++CurInst;
2237 continue;
2238 }
2239
Chris Lattner7cd580f2006-07-07 21:37:01 +00002240 // Cannot handle inline asm.
2241 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2242
Chris Lattnercd271422005-09-27 04:45:34 +00002243 // Resolve function pointers.
2244 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2245 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002246
Chris Lattnercd271422005-09-27 04:45:34 +00002247 std::vector<Constant*> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002248 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2249 i != e; ++i)
2250 Formals.push_back(getVal(Values, *i));
Chris Lattnercd271422005-09-27 04:45:34 +00002251
Reid Spencer5cbf9852007-01-30 20:08:39 +00002252 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002253 // If this is a function we can constant fold, do it.
Chris Lattner6c1f5652007-01-30 23:14:52 +00002254 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2255 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002256 InstResult = C;
2257 } else {
2258 return false;
2259 }
2260 } else {
2261 if (Callee->getFunctionType()->isVarArg())
2262 return false;
2263
2264 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002265 // Execute the call, if successful, use the return value.
2266 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2267 MutatedMemory, AllocaTmps))
2268 return false;
2269 InstResult = RetVal;
2270 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002271 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002272 BasicBlock *NewBB = 0;
2273 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2274 if (BI->isUnconditional()) {
2275 NewBB = BI->getSuccessor(0);
2276 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002277 ConstantInt *Cond =
2278 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002279 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002280
Reid Spencer579dca12007-01-12 04:24:46 +00002281 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002282 }
2283 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2284 ConstantInt *Val =
2285 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002286 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002287 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2288 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002289 if (RI->getNumOperands())
2290 RetVal = getVal(Values, RI->getOperand(0));
2291
2292 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002293 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002294 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002295 // invoke, unwind, unreachable.
2296 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002297 }
2298
2299 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002300 // executed the new block before. If so, we have a looping function,
2301 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002302 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002303 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002304
2305 // Okay, we have never been in this block before. Check to see if there
2306 // are any PHI nodes. If so, evaluate them with information about where
2307 // we came from.
2308 BasicBlock *OldBB = CurInst->getParent();
2309 CurInst = NewBB->begin();
2310 PHINode *PN;
2311 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2312 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2313
2314 // Do NOT increment CurInst. We know that the terminator had no value.
2315 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002316 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002317 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002318 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002319 }
2320
2321 if (!CurInst->use_empty())
2322 Values[CurInst] = InstResult;
2323
2324 // Advance program counter.
2325 ++CurInst;
2326 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002327}
2328
2329/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2330/// we can. Return true if we can, false otherwise.
2331static bool EvaluateStaticConstructor(Function *F) {
2332 /// MutatedMemory - For each store we execute, we update this map. Loads
2333 /// check this to get the most up-to-date value. If evaluation is successful,
2334 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002335 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002336
2337 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2338 /// to represent its body. This vector is needed so we can delete the
2339 /// temporary globals when we are done.
2340 std::vector<GlobalVariable*> AllocaTmps;
2341
2342 /// CallStack - This is used to detect recursion. In pathological situations
2343 /// we could hit exponential behavior, but at least there is nothing
2344 /// unbounded.
2345 std::vector<Function*> CallStack;
2346
2347 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002348 Constant *RetValDummy;
2349 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2350 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002351 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002352 // We succeeded at evaluation: commit the result.
Bill Wendling0a81aac2006-11-26 10:02:32 +00002353 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2354 << F->getName() << "' to " << MutatedMemory.size()
2355 << " stores.\n";
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002356 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002357 E = MutatedMemory.end(); I != E; ++I)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002358 CommitValueTo(I->second, I->first, F->getContext());
Chris Lattnera22fdb02005-09-26 17:07:09 +00002359 }
Chris Lattner79c11012005-09-26 04:44:35 +00002360
Chris Lattnera22fdb02005-09-26 17:07:09 +00002361 // At this point, we are done interpreting. If we created any 'alloca'
2362 // temporaries, release them now.
2363 while (!AllocaTmps.empty()) {
2364 GlobalVariable *Tmp = AllocaTmps.back();
2365 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002366
Chris Lattnera22fdb02005-09-26 17:07:09 +00002367 // If there are still users of the alloca, the program is doing something
2368 // silly, e.g. storing the address of the alloca somewhere and using it
2369 // later. Since this is undefined, we'll just make it be null.
2370 if (!Tmp->use_empty())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002371 Tmp->replaceAllUsesWith(F->getContext()->getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002372 delete Tmp;
2373 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002374
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002375 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002376}
2377
Chris Lattnerdb973e62005-09-26 02:31:18 +00002378
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002379
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002380/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2381/// Return true if anything changed.
2382bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2383 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2384 bool MadeChange = false;
2385 if (Ctors.empty()) return false;
2386
2387 // Loop over global ctors, optimizing them when we can.
2388 for (unsigned i = 0; i != Ctors.size(); ++i) {
2389 Function *F = Ctors[i];
2390 // Found a null terminator in the middle of the list, prune off the rest of
2391 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002392 if (F == 0) {
2393 if (i != Ctors.size()-1) {
2394 Ctors.resize(i+1);
2395 MadeChange = true;
2396 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002397 break;
2398 }
2399
Chris Lattner79c11012005-09-26 04:44:35 +00002400 // We cannot simplify external ctor functions.
2401 if (F->empty()) continue;
2402
2403 // If we can evaluate the ctor at compile time, do.
2404 if (EvaluateStaticConstructor(F)) {
2405 Ctors.erase(Ctors.begin()+i);
2406 MadeChange = true;
2407 --i;
2408 ++NumCtorsEvaluated;
2409 continue;
2410 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002411 }
2412
2413 if (!MadeChange) return false;
2414
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002415 GCL = InstallGlobalCtors(GCL, Ctors, Context);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002416 return true;
2417}
2418
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002419bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002420 bool Changed = false;
2421
Duncan Sands177d84e2009-01-07 20:01:06 +00002422 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002423 I != E;) {
2424 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002425 // Aliases without names cannot be referenced outside this module.
2426 if (!J->hasName() && !J->isDeclaration())
2427 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002428 // If the aliasee may change at link time, nothing can be done - bail out.
2429 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002430 continue;
2431
Duncan Sands4782b302009-02-15 09:56:08 +00002432 Constant *Aliasee = J->getAliasee();
2433 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002434 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002435 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2436
2437 // Make all users of the alias use the aliasee instead.
2438 if (!J->use_empty()) {
2439 J->replaceAllUsesWith(Aliasee);
2440 ++NumAliasesResolved;
2441 Changed = true;
2442 }
2443
2444 // If the aliasee has internal linkage, give it the name and linkage
2445 // of the alias, and delete the alias. This turns:
2446 // define internal ... @f(...)
2447 // @a = alias ... @f
2448 // into:
2449 // define ... @a(...)
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002450 if (!Target->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002451 continue;
2452
2453 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002454 if (J->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002455 continue;
2456
Duncan Sandsa37d1192009-02-15 11:54:49 +00002457 // Do not perform the transform if multiple aliases potentially target the
2458 // aliasee. This check also ensures that it is safe to replace the section
2459 // and other attributes of the aliasee with those of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002460 if (!hasOneUse)
2461 continue;
2462
Duncan Sandsa37d1192009-02-15 11:54:49 +00002463 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002464 Target->takeName(J);
2465 Target->setLinkage(J->getLinkage());
Duncan Sandsa37d1192009-02-15 11:54:49 +00002466 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sands4782b302009-02-15 09:56:08 +00002467
2468 // Delete the alias.
2469 M.getAliasList().erase(J);
2470 ++NumAliasesRemoved;
2471 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002472 }
2473
2474 return Changed;
2475}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002476
Chris Lattner7a90b682004-10-07 04:16:33 +00002477bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002478 bool Changed = false;
Owen Anderson001dbfe2009-07-16 18:04:31 +00002479 Context = &M.getContext();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002480
2481 // Try to find the llvm.globalctors list.
2482 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002483
Chris Lattner7a90b682004-10-07 04:16:33 +00002484 bool LocalChange = true;
2485 while (LocalChange) {
2486 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002487
2488 // Delete functions that are trivially dead, ccc -> fastcc
2489 LocalChange |= OptimizeFunctions(M);
2490
2491 // Optimize global_ctors list.
2492 if (GlobalCtors)
2493 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2494
2495 // Optimize non-address-taken globals.
2496 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002497
2498 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002499 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002500 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002501 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002502
2503 // TODO: Move all global ctors functions to the end of the module for code
2504 // layout.
2505
Chris Lattner079236d2004-02-25 21:34:36 +00002506 return Changed;
2507}