blob: 919da78651709ea7a732a9798e19dbc8fe02bb0b [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"
Chris Lattner941db492008-01-14 02:09:12 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000032#include "llvm/Support/MathExtras.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000033#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000034#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000035#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/ADT/Statistic.h"
Chris Lattner670c8892004-10-08 17:32:09 +000037#include "llvm/ADT/StringExtras.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000038#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000039#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000040using namespace llvm;
41
Chris Lattner86453c52006-12-19 22:09:18 +000042STATISTIC(NumMarked , "Number of globals marked constant");
43STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
44STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
45STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
46STATISTIC(NumDeleted , "Number of globals deleted");
47STATISTIC(NumFnDeleted , "Number of functions deleted");
48STATISTIC(NumGlobUses , "Number of global uses devirtualized");
49STATISTIC(NumLocalized , "Number of globals localized");
50STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
51STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
52STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000053STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000054STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
55STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Chris Lattner079236d2004-02-25 21:34:36 +000056
Chris Lattner86453c52006-12-19 22:09:18 +000057namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000058 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000059 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60 AU.addRequired<TargetData>();
61 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000062 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000063 GlobalOpt() : ModulePass(&ID) {}
Misha Brukmanfd939082005-04-21 23:48:37 +000064
Chris Lattnerb12914b2004-09-20 04:48:05 +000065 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000066
67 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000068 GlobalVariable *FindGlobalCtors(Module &M);
69 bool OptimizeFunctions(Module &M);
70 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000071 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000072 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000073 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000074 };
Chris Lattner079236d2004-02-25 21:34:36 +000075}
76
Dan Gohman844731a2008-05-13 00:00:25 +000077char GlobalOpt::ID = 0;
78static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
79
Chris Lattner7a90b682004-10-07 04:16:33 +000080ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000081
Dan Gohman844731a2008-05-13 00:00:25 +000082namespace {
83
Chris Lattner7a90b682004-10-07 04:16:33 +000084/// GlobalStatus - As we analyze each global, keep track of some information
85/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000086/// this info will be accurate.
Reid Spencer9133fe22007-02-05 23:32:05 +000087struct VISIBILITY_HIDDEN GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000088 /// isLoaded - True if the global is ever loaded. If the global isn't ever
89 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000090 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000091
92 /// StoredType - Keep track of what stores to the global look like.
93 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000094 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000095 /// NotStored - There is no store to this global. It can thus be marked
96 /// constant.
97 NotStored,
98
99 /// isInitializerStored - This global is stored to, but the only thing
100 /// stored is the constant it was initialized with. This is only tracked
101 /// for scalar globals.
102 isInitializerStored,
103
104 /// isStoredOnce - This global is stored to, but only its initializer and
105 /// one other value is ever stored to it. If this global isStoredOnce, we
106 /// track the value stored to it in StoredOnceValue below. This is only
107 /// tracked for scalar globals.
108 isStoredOnce,
109
110 /// isStored - This global is stored to by multiple values or something else
111 /// that we cannot track.
112 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000113 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000114
115 /// StoredOnceValue - If only one value (besides the initializer constant) is
116 /// ever stored to this global, keep track of what value it is.
117 Value *StoredOnceValue;
118
Chris Lattner25de4e52006-11-01 18:03:33 +0000119 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
120 /// null/false. When the first accessing function is noticed, it is recorded.
121 /// When a second different accessing function is noticed,
122 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000123 Function *AccessingFunction;
124 bool HasMultipleAccessingFunctions;
125
Chris Lattner25de4e52006-11-01 18:03:33 +0000126 /// HasNonInstructionUser - Set to true if this global has a user that is not
127 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000128 bool HasNonInstructionUser;
129
Chris Lattner25de4e52006-11-01 18:03:33 +0000130 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
131 bool HasPHIUser;
132
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000133 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000134 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner6a93fc02008-01-14 01:32:52 +0000135 HasNonInstructionUser(false), HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000136};
Chris Lattnere47ba742004-10-06 20:57:02 +0000137
Dan Gohman844731a2008-05-13 00:00:25 +0000138}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000139
Jay Foade3acf152009-06-09 21:37:11 +0000140// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
141// by constants itself. Note that constants cannot be cyclic, so this test is
142// pretty easy to implement recursively.
143//
144static bool SafeToDestroyConstant(Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000145 if (isa<GlobalValue>(C)) return false;
146
Devang Patel743cdf82009-03-06 01:37:41 +0000147 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
148 if (Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000149 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000150 } else
151 return false;
152 return true;
153}
154
155
Chris Lattner7a90b682004-10-07 04:16:33 +0000156/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
157/// structure. If the global has its address taken, return true to indicate we
158/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000159///
Chris Lattner7a90b682004-10-07 04:16:33 +0000160static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000161 SmallPtrSet<PHINode*, 16> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000162 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000163 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000164 GS.HasNonInstructionUser = true;
165
Chris Lattner7a90b682004-10-07 04:16:33 +0000166 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Chris Lattner670c8892004-10-08 17:32:09 +0000167
Chris Lattner079236d2004-02-25 21:34:36 +0000168 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000169 if (!GS.HasMultipleAccessingFunctions) {
170 Function *F = I->getParent()->getParent();
171 if (GS.AccessingFunction == 0)
172 GS.AccessingFunction = F;
173 else if (GS.AccessingFunction != F)
174 GS.HasMultipleAccessingFunctions = true;
175 }
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000176 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000177 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000178 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Chris Lattner7a90b682004-10-07 04:16:33 +0000179 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000180 // Don't allow a store OF the address, only stores TO the address.
181 if (SI->getOperand(0) == V) return true;
182
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000183 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
184
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000185 // If this is a direct store to the global (i.e., the global is a scalar
186 // value, not an aggregate), keep more specific information about
187 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000188 if (GS.StoredType != GlobalStatus::isStored) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000189 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000190 Value *StoredVal = SI->getOperand(0);
191 if (StoredVal == GV->getInitializer()) {
192 if (GS.StoredType < GlobalStatus::isInitializerStored)
193 GS.StoredType = GlobalStatus::isInitializerStored;
194 } else if (isa<LoadInst>(StoredVal) &&
195 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
196 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000197 if (GS.StoredType < GlobalStatus::isInitializerStored)
198 GS.StoredType = GlobalStatus::isInitializerStored;
199 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
200 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000201 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000202 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000203 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000204 // noop.
205 } else {
206 GS.StoredType = GlobalStatus::isStored;
207 }
208 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000209 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000210 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000211 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000212 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000214 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000215 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000216 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
217 // PHI nodes we can check just like select or GEP instructions, but we
218 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000219 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000220 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000221 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000222 } else if (isa<CmpInst>(I)) {
Chris Lattner8e108442009-03-08 03:37:35 +0000223 } else if (isa<MemTransferInst>(I)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000224 if (I->getOperand(1) == V)
225 GS.StoredType = GlobalStatus::isStored;
226 if (I->getOperand(2) == V)
227 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000228 } else if (isa<MemSetInst>(I)) {
229 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
230 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000231 } else {
232 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000233 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000234 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000235 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000236 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000237 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000238 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000239 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000240 GS.HasNonInstructionUser = true;
241 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000242 return true;
243 }
244
245 return false;
246}
247
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000248static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx,
249 LLVMContext* Context) {
Chris Lattner670c8892004-10-08 17:32:09 +0000250 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
251 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000252 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000253
Chris Lattner670c8892004-10-08 17:32:09 +0000254 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
255 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
256 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
257 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000258 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000259 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000260 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000261 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
262 if (IdxV < STy->getNumElements())
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000263 return Context->getNullValue(STy->getElementType(IdxV));
Chris Lattner670c8892004-10-08 17:32:09 +0000264 } else if (const SequentialType *STy =
265 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000266 return Context->getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000267 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000268 } else if (isa<UndefValue>(Agg)) {
269 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
270 if (IdxV < STy->getNumElements())
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000271 return Context->getUndef(STy->getElementType(IdxV));
Chris Lattner7a7ed022004-10-16 18:09:00 +0000272 } else if (const SequentialType *STy =
273 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000274 return Context->getUndef(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000275 }
Chris Lattner670c8892004-10-08 17:32:09 +0000276 }
277 return 0;
278}
Chris Lattner7a90b682004-10-07 04:16:33 +0000279
Chris Lattner7a90b682004-10-07 04:16:33 +0000280
Chris Lattnere47ba742004-10-06 20:57:02 +0000281/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
282/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000283/// quick scan over the use list to clean up the easy and obvious cruft. This
284/// returns true if it made a change.
285static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
286 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000287 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
288 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000289
Chris Lattner7a90b682004-10-07 04:16:33 +0000290 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000291 if (Init) {
292 // Replace the load with the initializer.
293 LI->replaceAllUsesWith(Init);
294 LI->eraseFromParent();
295 Changed = true;
296 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000297 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000298 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000299 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000300 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000301 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
302 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000303 Constant *SubInit = 0;
304 if (Init)
305 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000306 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000307 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000308 isa<PointerType>(CE->getType())) {
309 // Pointer cast, delete any stores and memsets to the global.
310 Changed |= CleanupConstantGlobalUsers(CE, 0);
311 }
312
313 if (CE->use_empty()) {
314 CE->destroyConstant();
315 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000316 }
317 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000318 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
319 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
320 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000321 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000322 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
323 ConstantExpr *CE =
324 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
325 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner19450242007-11-13 21:46:23 +0000326 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000327 }
Chris Lattner19450242007-11-13 21:46:23 +0000328 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000329
Chris Lattner031955d2004-10-10 16:43:46 +0000330 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000331 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000332 Changed = true;
333 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000334 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
335 if (MI->getRawDest() == V) {
336 MI->eraseFromParent();
337 Changed = true;
338 }
339
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000340 } else if (Constant *C = dyn_cast<Constant>(U)) {
341 // If we have a chain of dead constantexprs or other things dangling from
342 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000343 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000344 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000345 // This could have invalidated UI, start over from scratch.
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000346 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000347 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000348 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000349 }
350 }
Chris Lattner031955d2004-10-10 16:43:46 +0000351 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000352}
353
Chris Lattner941db492008-01-14 02:09:12 +0000354/// isSafeSROAElementUse - Return true if the specified instruction is a safe
355/// user of a derived expression from a global that we want to SROA.
356static bool isSafeSROAElementUse(Value *V) {
357 // We might have a dead and dangling constant hanging off of here.
358 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000359 return SafeToDestroyConstant(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000360
Chris Lattner941db492008-01-14 02:09:12 +0000361 Instruction *I = dyn_cast<Instruction>(V);
362 if (!I) return false;
363
364 // Loads are ok.
365 if (isa<LoadInst>(I)) return true;
366
367 // Stores *to* the pointer are ok.
368 if (StoreInst *SI = dyn_cast<StoreInst>(I))
369 return SI->getOperand(0) != V;
370
371 // Otherwise, it must be a GEP.
372 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
373 if (GEPI == 0) return false;
374
375 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
376 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
377 return false;
378
379 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
380 I != E; ++I)
381 if (!isSafeSROAElementUse(*I))
382 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000383 return true;
384}
385
Chris Lattner941db492008-01-14 02:09:12 +0000386
387/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
388/// Look at it and its uses and decide whether it is safe to SROA this global.
389///
390static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
391 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
392 if (!isa<GetElementPtrInst>(U) &&
393 (!isa<ConstantExpr>(U) ||
394 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
395 return false;
396
397 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
398 // don't like < 3 operand CE's, and we don't like non-constant integer
399 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
400 // value of C.
401 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
402 !cast<Constant>(U->getOperand(1))->isNullValue() ||
403 !isa<ConstantInt>(U->getOperand(2)))
404 return false;
405
406 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
407 ++GEPI; // Skip over the pointer index.
408
409 // If this is a use of an array allocation, do a bit more checking for sanity.
410 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
411 uint64_t NumElements = AT->getNumElements();
412 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
413
414 // Check to make sure that index falls within the array. If not,
415 // something funny is going on, so we won't do the optimization.
416 //
417 if (Idx->getZExtValue() >= NumElements)
418 return false;
419
420 // We cannot scalar repl this level of the array unless any array
421 // sub-indices are in-range constants. In particular, consider:
422 // A[0][i]. We cannot know that the user isn't doing invalid things like
423 // allowing i to index an out-of-range subscript that accesses A[1].
424 //
425 // Scalar replacing *just* the outer index of the array is probably not
426 // going to be a win anyway, so just give up.
427 for (++GEPI; // Skip array index.
428 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
429 ++GEPI) {
430 uint64_t NumElements;
431 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
432 NumElements = SubArrayTy->getNumElements();
433 else
434 NumElements = cast<VectorType>(*GEPI)->getNumElements();
435
436 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
437 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
438 return false;
439 }
440 }
441
442 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
443 if (!isSafeSROAElementUse(*I))
444 return false;
445 return true;
446}
447
448/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
449/// is safe for us to perform this transformation.
450///
451static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
452 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
453 UI != E; ++UI) {
454 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
455 return false;
456 }
457 return true;
458}
459
460
Chris Lattner670c8892004-10-08 17:32:09 +0000461/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
462/// variable. This opens the door for other optimizations by exposing the
463/// behavior of the program in a more fine-grained way. We have determined that
464/// this transformation is safe already. We return the first global variable we
465/// insert so that the caller can reprocess it.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000466static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
467 LLVMContext* Context) {
Chris Lattner727c2102008-01-14 01:31:05 +0000468 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000469 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000470 return 0;
471
Rafael Espindolabb46f522009-01-15 20:18:42 +0000472 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000473 Constant *Init = GV->getInitializer();
474 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000475
Chris Lattner670c8892004-10-08 17:32:09 +0000476 std::vector<GlobalVariable*> NewGlobals;
477 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
478
Chris Lattner998182b2008-04-26 07:40:11 +0000479 // Get the alignment of the global, either explicit or target-specific.
480 unsigned StartAlignment = GV->getAlignment();
481 if (StartAlignment == 0)
482 StartAlignment = TD.getABITypeAlignment(GV->getType());
483
Chris Lattner670c8892004-10-08 17:32:09 +0000484 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
485 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000486 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000487 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
488 Constant *In = getAggregateConstantElement(Init,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000489 Context->getConstantInt(Type::Int32Ty, i),
490 Context);
Chris Lattner670c8892004-10-08 17:32:09 +0000491 assert(In && "Couldn't get element of initializer?");
492 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
493 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000494 In, GV->getName()+"."+utostr(i),
495 (Module *)NULL,
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000496 GV->isThreadLocal(),
497 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000498 Globals.insert(GV, NGV);
499 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000500
501 // Calculate the known alignment of the field. If the original aggregate
502 // had 256 byte alignment for example, something might depend on that:
503 // propagate info to each field.
504 uint64_t FieldOffset = Layout.getElementOffset(i);
505 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
506 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
507 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000508 }
509 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
510 unsigned NumElements = 0;
511 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
512 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000513 else
Chris Lattner998182b2008-04-26 07:40:11 +0000514 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000515
Chris Lattner1f21ef12005-02-23 16:53:04 +0000516 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000517 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000518 NewGlobals.reserve(NumElements);
Chris Lattner998182b2008-04-26 07:40:11 +0000519
Duncan Sands777d2302009-05-09 07:06:46 +0000520 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000521 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000522 for (unsigned i = 0, e = NumElements; i != e; ++i) {
523 Constant *In = getAggregateConstantElement(Init,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000524 Context->getConstantInt(Type::Int32Ty, i),
525 Context);
Chris Lattner670c8892004-10-08 17:32:09 +0000526 assert(In && "Couldn't get element of initializer?");
527
528 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
529 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000530 In, GV->getName()+"."+utostr(i),
531 (Module *)NULL,
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000532 GV->isThreadLocal(),
533 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000534 Globals.insert(GV, NGV);
535 NewGlobals.push_back(NGV);
Chris Lattner998182b2008-04-26 07:40:11 +0000536
537 // Calculate the known alignment of the field. If the original aggregate
538 // had 256 byte alignment for example, something might depend on that:
539 // propagate info to each field.
540 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
541 if (NewAlign > EltAlign)
542 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000543 }
544 }
545
546 if (NewGlobals.empty())
547 return 0;
548
Bill Wendling0a81aac2006-11-26 10:02:32 +0000549 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000550
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000551 Constant *NullInt = Context->getNullValue(Type::Int32Ty);
Chris Lattner670c8892004-10-08 17:32:09 +0000552
553 // Loop over all of the uses of the global, replacing the constantexpr geps,
554 // with smaller constantexpr geps or direct references.
555 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000556 User *GEP = GV->use_back();
557 assert(((isa<ConstantExpr>(GEP) &&
558 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
559 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000560
Chris Lattner670c8892004-10-08 17:32:09 +0000561 // Ignore the 1th operand, which has to be zero or else the program is quite
562 // broken (undefined). Get the 2nd operand, which is the structure or array
563 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000564 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000565 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
566
Chris Lattner30ba5692004-10-11 05:54:41 +0000567 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000568
569 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000570 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000571 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000572 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000573 Idxs.push_back(NullInt);
574 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
575 Idxs.push_back(CE->getOperand(i));
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000576 NewPtr = Context->getConstantExprGetElementPtr(cast<Constant>(NewPtr),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000577 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000578 } else {
579 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000580 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000581 Idxs.push_back(NullInt);
582 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
583 Idxs.push_back(GEPI->getOperand(i));
Gabor Greif051a9502008-04-06 20:25:17 +0000584 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
585 GEPI->getName()+"."+utostr(Val), GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000586 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000587 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000588 GEP->replaceAllUsesWith(NewPtr);
589
590 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000591 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000592 else
593 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000594 }
595
Chris Lattnere40e2d12004-10-08 20:25:55 +0000596 // Delete the old global, now that it is dead.
597 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000598 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000599
600 // Loop over the new globals array deleting any globals that are obviously
601 // dead. This can arise due to scalarization of a structure or an array that
602 // has elements that are dead.
603 unsigned FirstGlobal = 0;
604 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
605 if (NewGlobals[i]->use_empty()) {
606 Globals.erase(NewGlobals[i]);
607 if (FirstGlobal == i) ++FirstGlobal;
608 }
609
610 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000611}
612
Chris Lattner9b34a612004-10-09 21:48:45 +0000613/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000614/// value will trap if the value is dynamically null. PHIs keeps track of any
615/// phi nodes we've seen to avoid reprocessing them.
616static bool AllUsesOfValueWillTrapIfNull(Value *V,
617 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000618 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
619 if (isa<LoadInst>(*UI)) {
620 // Will trap.
621 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
622 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000623 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000624 return false; // Storing the value.
625 }
626 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
627 if (CI->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000628 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000629 return false; // Not calling the ptr
630 }
631 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
632 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000633 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000634 return false; // Not calling the ptr
635 }
Chris Lattner81686182007-09-13 16:30:19 +0000636 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
637 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000638 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000639 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
640 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
641 // If we've already seen this phi node, ignore it, it has already been
642 // checked.
643 if (PHIs.insert(PN))
644 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000645 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000646 isa<ConstantPointerNull>(UI->getOperand(1))) {
647 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000648 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000649 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000650 return false;
651 }
652 return true;
653}
654
655/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000656/// from GV will trap if the loaded value is null. Note that this also permits
657/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000658static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
659 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
660 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000661 SmallPtrSet<PHINode*, 8> PHIs;
662 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000663 return false;
664 } else if (isa<StoreInst>(*UI)) {
665 // Ignore stores to the global.
666 } else {
667 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000668 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000669 return false;
670 }
671
672 return true;
673}
674
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000675static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
676 LLVMContext* Context) {
Chris Lattner708148e2004-10-10 23:14:11 +0000677 bool Changed = false;
678 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
679 Instruction *I = cast<Instruction>(*UI++);
680 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
681 LI->setOperand(0, NewV);
682 Changed = true;
683 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
684 if (SI->getOperand(1) == V) {
685 SI->setOperand(1, NewV);
686 Changed = true;
687 }
688 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
689 if (I->getOperand(0) == V) {
690 // Calling through the pointer! Turn into a direct call, but be careful
691 // that the pointer is not also being passed as an argument.
692 I->setOperand(0, NewV);
693 Changed = true;
694 bool PassedAsArg = false;
695 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
696 if (I->getOperand(i) == V) {
697 PassedAsArg = true;
698 I->setOperand(i, NewV);
699 }
700
701 if (PassedAsArg) {
702 // Being passed as an argument also. Be careful to not invalidate UI!
703 UI = V->use_begin();
704 }
705 }
706 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
707 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000708 Context->getConstantExprCast(CI->getOpcode(),
709 NewV, CI->getType()), Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000710 if (CI->use_empty()) {
711 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000712 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000713 }
714 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
715 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000716 SmallVector<Constant*, 8> Idxs;
717 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000718 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
719 i != e; ++i)
720 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000721 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000722 else
723 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000724 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000725 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000726 Context->getConstantExprGetElementPtr(NewV, &Idxs[0],
727 Idxs.size()), Context);
Chris Lattner708148e2004-10-10 23:14:11 +0000728 if (GEPI->use_empty()) {
729 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000730 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000731 }
732 }
733 }
734
735 return Changed;
736}
737
738
739/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
740/// value stored into it. If there are uses of the loaded value that would trap
741/// if the loaded value is dynamically null, then we know that they cannot be
742/// reachable with a null optimize away the load.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000743static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
744 LLVMContext* Context) {
Chris Lattner708148e2004-10-10 23:14:11 +0000745 bool Changed = false;
746
Chris Lattner92c6bd22009-01-14 00:12:58 +0000747 // Keep track of whether we are able to remove all the uses of the global
748 // other than the store that defines it.
749 bool AllNonStoreUsesGone = true;
750
Chris Lattner708148e2004-10-10 23:14:11 +0000751 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000752 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
753 User *GlobalUser = *GUI++;
754 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000755 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000756 // If we were able to delete all uses of the loads
757 if (LI->use_empty()) {
758 LI->eraseFromParent();
759 Changed = true;
760 } else {
761 AllNonStoreUsesGone = false;
762 }
763 } else if (isa<StoreInst>(GlobalUser)) {
764 // Ignore the store that stores "LV" to the global.
765 assert(GlobalUser->getOperand(1) == GV &&
766 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000767 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000768 AllNonStoreUsesGone = false;
769
770 // If we get here we could have other crazy uses that are transitively
771 // loaded.
772 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
773 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000774 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000775 }
Chris Lattner708148e2004-10-10 23:14:11 +0000776
777 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000778 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000779 ++NumGlobUses;
780 }
781
Chris Lattner708148e2004-10-10 23:14:11 +0000782 // If we nuked all of the loads, then none of the stores are needed either,
783 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000784 if (AllNonStoreUsesGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000785 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattner708148e2004-10-10 23:14:11 +0000786 CleanupConstantGlobalUsers(GV, 0);
787 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000788 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000789 ++NumDeleted;
790 }
791 Changed = true;
792 }
793 return Changed;
794}
795
Chris Lattner30ba5692004-10-11 05:54:41 +0000796/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
797/// instructions that are foldable.
798static void ConstantPropUsersOf(Value *V) {
799 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
800 if (Instruction *I = dyn_cast<Instruction>(*UI++))
801 if (Constant *NewC = ConstantFoldInstruction(I)) {
802 I->replaceAllUsesWith(NewC);
803
Chris Lattnerd514d822005-02-01 01:23:31 +0000804 // Advance UI to the next non-I use to avoid invalidating it!
805 // Instructions could multiply use V.
806 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000807 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000808 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000809 }
810}
811
812/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
813/// variable, and transforms the program as if it always contained the result of
814/// the specified malloc. Because it is always the result of the specified
815/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000816/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000817static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000818 MallocInst *MI,
819 LLVMContext* Context) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000820 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000821 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
822
Reid Spencerb83eb642006-10-20 07:07:24 +0000823 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000824 // If we have an array allocation, transform it to a single element
825 // allocation to make the code below simpler.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000826 Type *NewTy = Context->getArrayType(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000827 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000828 MallocInst *NewMI =
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000829 new MallocInst(NewTy, Context->getNullValue(Type::Int32Ty),
Nate Begeman14b05292005-11-05 09:21:28 +0000830 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000831 Value* Indices[2];
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000832 Indices[0] = Indices[1] = Context->getNullValue(Type::Int32Ty);
Gabor Greif051a9502008-04-06 20:25:17 +0000833 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
834 NewMI->getName()+".el0", MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000835 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000836 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000837 MI = NewMI;
838 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000839
Chris Lattner7a7ed022004-10-16 18:09:00 +0000840 // Create the new global variable. The contents of the malloc'd memory is
841 // undefined, so initialize with an undef value.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000842 Constant *Init = Context->getUndef(MI->getAllocatedType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000843 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
844 GlobalValue::InternalLinkage, Init,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000845 GV->getName()+".body",
846 (Module *)NULL,
847 GV->isThreadLocal());
Chris Lattner998182b2008-04-26 07:40:11 +0000848 // FIXME: This new global should have the alignment returned by malloc. Code
849 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
850 // this would only guarantee some lower alignment.
Chris Lattner30ba5692004-10-11 05:54:41 +0000851 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanfd939082005-04-21 23:48:37 +0000852
Chris Lattner30ba5692004-10-11 05:54:41 +0000853 // Anything that used the malloc now uses the global directly.
854 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000855
856 Constant *RepValue = NewGV;
857 if (NewGV->getType() != GV->getType()->getElementType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000858 RepValue = Context->getConstantExprBitCast(RepValue,
Reid Spencerd977d862006-12-12 23:36:14 +0000859 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000860
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000861 // If there is a comparison against null, we will insert a global bool to
862 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000863 GlobalVariable *InitBool =
Reid Spencer4fe16d62007-01-11 18:21:29 +0000864 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000865 Context->getConstantIntFalse(), GV->getName()+".init",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000866 (Module *)NULL, GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000867 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000868
Chris Lattner30ba5692004-10-11 05:54:41 +0000869 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000870 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000871 while (!GV->use_empty())
872 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000873 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000874 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000875 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000876 LoadUse = RepValue;
877 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000878 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
879 // Replace the cmp X, 0 with a use of the bool value.
880 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000881 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000882 switch (CI->getPredicate()) {
883 default: assert(0 && "Unknown ICmp Predicate!");
884 case ICmpInst::ICMP_ULT:
885 case ICmpInst::ICMP_SLT:
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000886 LV = Context->getConstantIntFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000887 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000888 case ICmpInst::ICMP_ULE:
889 case ICmpInst::ICMP_SLE:
890 case ICmpInst::ICMP_EQ:
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000891 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000892 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000893 case ICmpInst::ICMP_NE:
894 case ICmpInst::ICMP_UGE:
895 case ICmpInst::ICMP_SGE:
896 case ICmpInst::ICMP_UGT:
897 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000898 break; // no change.
899 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000900 CI->replaceAllUsesWith(LV);
901 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000902 }
903 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000904 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000905 } else {
906 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000907 // The global is initialized when the store to it occurs.
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000908 new StoreInst(Context->getConstantIntTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000909 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000910 }
911
Chris Lattnerbc965b92004-12-02 06:25:58 +0000912 // If the initialization boolean was used, insert it, otherwise delete it.
913 if (!InitBoolUsed) {
914 while (!InitBool->use_empty()) // Delete initializations
915 cast<Instruction>(InitBool->use_back())->eraseFromParent();
916 delete InitBool;
917 } else
918 GV->getParent()->getGlobalList().insert(GV, InitBool);
919
920
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000921 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000922 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000923 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000924
925 // To further other optimizations, loop over all users of NewGV and try to
926 // constant prop them. This will promote GEP instructions with constant
927 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
928 ConstantPropUsersOf(NewGV);
929 if (RepValue != NewGV)
930 ConstantPropUsersOf(RepValue);
931
932 return NewGV;
933}
Chris Lattner708148e2004-10-10 23:14:11 +0000934
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000935/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
936/// to make sure that there are no complex uses of V. We permit simple things
937/// like dereferencing the pointer, but not storing through the address, unless
938/// it is to the specified global.
939static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000940 GlobalVariable *GV,
941 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000942 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foad0906b1b2009-06-06 17:49:35 +0000943 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000944
945 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
946 continue; // Fine, ignore.
947 }
948
949 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000950 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
951 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000952 continue; // Otherwise, storing through it, or storing into GV... fine.
953 }
954
955 if (isa<GetElementPtrInst>(Inst)) {
956 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000957 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000958 continue;
959 }
960
961 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000962 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
963 // cycles.
964 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000965 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
966 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000967 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000968 }
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000969
970 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
971 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
972 return false;
973 continue;
974 }
975
976 return false;
977 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000978 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000979}
980
Chris Lattner86395032006-09-30 23:32:09 +0000981/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
982/// somewhere. Transform all uses of the allocation into loads from the
983/// global and uses of the resultant pointer. Further, delete the store into
984/// GV. This assumes that these value pass the
985/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
986static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
987 GlobalVariable *GV) {
988 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000989 Instruction *U = cast<Instruction>(*Alloc->use_begin());
990 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +0000991 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
992 // If this is the store of the allocation into the global, remove it.
993 if (SI->getOperand(1) == GV) {
994 SI->eraseFromParent();
995 continue;
996 }
Chris Lattnera637a8b2007-09-13 18:00:31 +0000997 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
998 // Insert the load in the corresponding predecessor, not right before the
999 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001000 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001001 } else if (isa<BitCastInst>(U)) {
1002 // Must be bitcast between the malloc and store to initialize the global.
1003 ReplaceUsesOfMallocWithGlobal(U, GV);
1004 U->eraseFromParent();
1005 continue;
1006 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1007 // If this is a "GEP bitcast" and the user is a store to the global, then
1008 // just process it as a bitcast.
1009 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1010 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1011 if (SI->getOperand(1) == GV) {
1012 // Must be bitcast GEP between the malloc and store to initialize
1013 // the global.
1014 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1015 GEPI->eraseFromParent();
1016 continue;
1017 }
Chris Lattner86395032006-09-30 23:32:09 +00001018 }
Chris Lattner101f44e2008-12-15 21:44:34 +00001019
Chris Lattner86395032006-09-30 23:32:09 +00001020 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001021 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001022 U->replaceUsesOfWith(Alloc, NL);
1023 }
1024}
1025
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001026/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1027/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1028/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001029static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Cheng5d163962009-06-02 00:56:07 +00001030 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1031 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001032 // We permit two users of the load: setcc comparing against the null
1033 // pointer, and a getelementptr of a specific form.
1034 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1035 Instruction *User = cast<Instruction>(*UI);
1036
1037 // Comparison against null is ok.
1038 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1039 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1040 return false;
1041 continue;
1042 }
1043
1044 // getelementptr is also ok, but only a simple form.
1045 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1046 // Must index into the array and into the struct.
1047 if (GEPI->getNumOperands() < 3)
1048 return false;
1049
1050 // Otherwise the GEP is ok.
1051 continue;
1052 }
1053
1054 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001055 if (!LoadUsingPHIsPerLoad.insert(PN))
1056 // This means some phi nodes are dependent on each other.
1057 // Avoid infinite looping!
1058 return false;
1059 if (!LoadUsingPHIs.insert(PN))
1060 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001061 continue;
1062
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001063 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001064 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1065 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001066 return false;
1067
1068 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001069 }
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001070
1071 // Otherwise we don't know what this is, not ok.
1072 return false;
1073 }
1074
1075 return true;
1076}
1077
1078
1079/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1080/// GV are simple enough to perform HeapSRA, return true.
1081static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1082 MallocInst *MI) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001083 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Cheng5d163962009-06-02 00:56:07 +00001084 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001085 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1086 ++UI)
Evan Cheng5d163962009-06-02 00:56:07 +00001087 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1088 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1089 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001090 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001091 LoadUsingPHIsPerLoad.clear();
1092 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001093
1094 // If we reach here, we know that all uses of the loads and transitive uses
1095 // (through PHI nodes) are simple enough to transform. However, we don't know
1096 // that all inputs the to the PHI nodes are in the same equivalence sets.
1097 // Check to verify that all operands of the PHIs are either PHIS that can be
1098 // transformed, loads from GV, or MI itself.
1099 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1100 E = LoadUsingPHIs.end(); I != E; ++I) {
1101 PHINode *PN = *I;
1102 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1103 Value *InVal = PN->getIncomingValue(op);
1104
1105 // PHI of the stored value itself is ok.
1106 if (InVal == MI) continue;
1107
1108 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1109 // One of the PHIs in our set is (optimistically) ok.
1110 if (LoadUsingPHIs.count(InPN))
1111 continue;
1112 return false;
1113 }
1114
1115 // Load from GV is ok.
1116 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1117 if (LI->getOperand(0) == GV)
1118 continue;
1119
1120 // UNDEF? NULL?
1121
1122 // Anything else is rejected.
1123 return false;
1124 }
1125 }
1126
Chris Lattner86395032006-09-30 23:32:09 +00001127 return true;
1128}
1129
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001130static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1131 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001132 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1133 LLVMContext* Context) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001134 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1135
1136 if (FieldNo >= FieldVals.size())
1137 FieldVals.resize(FieldNo+1);
1138
1139 // If we already have this value, just reuse the previously scalarized
1140 // version.
1141 if (Value *FieldVal = FieldVals[FieldNo])
1142 return FieldVal;
1143
1144 // Depending on what instruction this is, we have several cases.
1145 Value *Result;
1146 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1147 // This is a scalarized version of the load from the global. Just create
1148 // a new Load of the scalarized global.
1149 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1150 InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001151 PHIsToRewrite, Context),
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001152 LI->getName()+".f" + utostr(FieldNo), LI);
1153 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1154 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1155 // field.
1156 const StructType *ST =
1157 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1158
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001159 Result =
1160 PHINode::Create(Context->getPointerTypeUnqual(ST->getElementType(FieldNo)),
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001161 PN->getName()+".f"+utostr(FieldNo), PN);
1162 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1163 } else {
1164 assert(0 && "Unknown usable value");
1165 Result = 0;
1166 }
1167
1168 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001169}
1170
Chris Lattner330245e2007-09-13 17:29:05 +00001171/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1172/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001173static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1174 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001175 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1176 LLVMContext* Context) {
Chris Lattner330245e2007-09-13 17:29:05 +00001177 // If this is a comparison against null, handle it.
1178 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1179 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1180 // If we have a setcc of the loaded pointer, we can use a setcc of any
1181 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001182 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001183 InsertedScalarizedValues, PHIsToRewrite,
1184 Context);
Chris Lattner330245e2007-09-13 17:29:05 +00001185
1186 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001187 Context->getNullValue(NPtr->getType()),
Chris Lattner330245e2007-09-13 17:29:05 +00001188 SCI->getName(), SCI);
1189 SCI->replaceAllUsesWith(New);
1190 SCI->eraseFromParent();
1191 return;
1192 }
1193
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001194 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001195 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1196 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1197 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001198
Chris Lattnera637a8b2007-09-13 18:00:31 +00001199 // Load the pointer for this field.
1200 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001201 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001202 InsertedScalarizedValues, PHIsToRewrite,
1203 Context);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001204
1205 // Create the new GEP idx vector.
1206 SmallVector<Value*, 8> GEPIdx;
1207 GEPIdx.push_back(GEPI->getOperand(1));
1208 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1209
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001210 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1211 GEPIdx.begin(), GEPIdx.end(),
Gabor Greif051a9502008-04-06 20:25:17 +00001212 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001213 GEPI->replaceAllUsesWith(NGEPI);
1214 GEPI->eraseFromParent();
1215 return;
1216 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001217
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001218 // Recursively transform the users of PHI nodes. This will lazily create the
1219 // PHIs that are needed for individual elements. Keep track of what PHIs we
1220 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1221 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1222 // already been seen first by another load, so its uses have already been
1223 // processed.
1224 PHINode *PN = cast<PHINode>(LoadUser);
1225 bool Inserted;
1226 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1227 tie(InsertPos, Inserted) =
1228 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1229 if (!Inserted) return;
Chris Lattner309f20f2007-09-13 21:31:36 +00001230
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001231 // If this is the first time we've seen this PHI, recursively process all
1232 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001233 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1234 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001235 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1236 Context);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001237 }
Chris Lattner330245e2007-09-13 17:29:05 +00001238}
1239
Chris Lattner86395032006-09-30 23:32:09 +00001240/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1241/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1242/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001243/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001244static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001245 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001246 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1247 LLVMContext* Context) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001248 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001249 UI != E; ) {
1250 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001251 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1252 Context);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001253 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001254
1255 if (Load->use_empty()) {
1256 Load->eraseFromParent();
1257 InsertedScalarizedValues.erase(Load);
1258 }
Chris Lattner86395032006-09-30 23:32:09 +00001259}
1260
1261/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1262/// it up into multiple allocations of arrays of the fields.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001263static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI,
1264 LLVMContext* Context){
Bill Wendling0a81aac2006-11-26 10:02:32 +00001265 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +00001266 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1267
1268 // There is guaranteed to be at least one use of the malloc (storing
1269 // it into GV). If there are other uses, change them to be uses of
1270 // the global to simplify later code. This also deletes the store
1271 // into GV.
1272 ReplaceUsesOfMallocWithGlobal(MI, GV);
1273
1274 // Okay, at this point, there are no users of the malloc. Insert N
1275 // new mallocs at the same place as MI, and N globals.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001276 std::vector<Value*> FieldGlobals;
Chris Lattner86395032006-09-30 23:32:09 +00001277 std::vector<MallocInst*> FieldMallocs;
1278
1279 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1280 const Type *FieldTy = STy->getElementType(FieldNo);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001281 const Type *PFieldTy = Context->getPointerTypeUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001282
1283 GlobalVariable *NGV =
1284 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001285 Context->getNullValue(PFieldTy),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001286 GV->getName() + ".f" + utostr(FieldNo), GV,
1287 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001288 FieldGlobals.push_back(NGV);
1289
1290 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1291 MI->getName() + ".f" + utostr(FieldNo),MI);
1292 FieldMallocs.push_back(NMI);
1293 new StoreInst(NMI, NGV, MI);
1294 }
1295
1296 // The tricky aspect of this transformation is handling the case when malloc
1297 // fails. In the original code, malloc failing would set the result pointer
1298 // of malloc to null. In this case, some mallocs could succeed and others
1299 // could fail. As such, we emit code that looks like this:
1300 // F0 = malloc(field0)
1301 // F1 = malloc(field1)
1302 // F2 = malloc(field2)
1303 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1304 // if (F0) { free(F0); F0 = 0; }
1305 // if (F1) { free(F1); F1 = 0; }
1306 // if (F2) { free(F2); F2 = 0; }
1307 // }
1308 Value *RunningOr = 0;
1309 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001310 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001311 Context->getNullValue(FieldMallocs[i]->getType()),
Chris Lattner86395032006-09-30 23:32:09 +00001312 "isnull", MI);
1313 if (!RunningOr)
1314 RunningOr = Cond; // First seteq
1315 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001316 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Chris Lattner86395032006-09-30 23:32:09 +00001317 }
1318
1319 // Split the basic block at the old malloc.
1320 BasicBlock *OrigBB = MI->getParent();
1321 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1322
1323 // Create the block to check the first condition. Put all these blocks at the
1324 // end of the function as they are unlikely to be executed.
Gabor Greif051a9502008-04-06 20:25:17 +00001325 BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
1326 OrigBB->getParent());
Chris Lattner86395032006-09-30 23:32:09 +00001327
1328 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1329 // branch on RunningOr.
1330 OrigBB->getTerminator()->eraseFromParent();
Gabor Greif051a9502008-04-06 20:25:17 +00001331 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Chris Lattner86395032006-09-30 23:32:09 +00001332
1333 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1334 // pointer, because some may be null while others are not.
1335 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1336 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001337 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001338 Context->getNullValue(GVVal->getType()),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001339 "tmp", NullPtrBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001340 BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
1341 BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
1342 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001343
1344 // Fill in FreeBlock.
1345 new FreeInst(GVVal, FreeBlock);
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001346 new StoreInst(Context->getNullValue(GVVal->getType()), FieldGlobals[i],
Chris Lattner86395032006-09-30 23:32:09 +00001347 FreeBlock);
Gabor Greif051a9502008-04-06 20:25:17 +00001348 BranchInst::Create(NextBlock, FreeBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001349
1350 NullPtrBlock = NextBlock;
1351 }
1352
Gabor Greif051a9502008-04-06 20:25:17 +00001353 BranchInst::Create(ContBB, NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001354
1355 // MI is no longer needed, remove it.
1356 MI->eraseFromParent();
1357
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001358 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1359 /// update all uses of the load, keep track of what scalarized loads are
1360 /// inserted for a given load.
1361 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1362 InsertedScalarizedValues[GV] = FieldGlobals;
1363
1364 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Chris Lattner86395032006-09-30 23:32:09 +00001365
1366 // Okay, the malloc site is completely handled. All of the uses of GV are now
1367 // loads, and all uses of those loads are simple. Rewrite them to use loads
1368 // of the per-field globals instead.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001369 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1370 Instruction *User = cast<Instruction>(*UI++);
1371
1372 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001373 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1374 Context);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001375 continue;
Chris Lattner39ff1e22007-01-09 23:29:37 +00001376 }
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001377
1378 // Must be a store of null.
1379 StoreInst *SI = cast<StoreInst>(User);
1380 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1381 "Unexpected heap-sra user!");
1382
1383 // Insert a store of null into each global.
1384 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1385 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001386 Constant *Null = Context->getNullValue(PT->getElementType());
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001387 new StoreInst(Null, FieldGlobals[i], SI);
1388 }
1389 // Erase the original store.
1390 SI->eraseFromParent();
Chris Lattner86395032006-09-30 23:32:09 +00001391 }
1392
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001393 // While we have PHIs that are interesting to rewrite, do it.
1394 while (!PHIsToRewrite.empty()) {
1395 PHINode *PN = PHIsToRewrite.back().first;
1396 unsigned FieldNo = PHIsToRewrite.back().second;
1397 PHIsToRewrite.pop_back();
1398 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1399 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1400
1401 // Add all the incoming values. This can materialize more phis.
1402 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1403 Value *InVal = PN->getIncomingValue(i);
1404 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001405 PHIsToRewrite, Context);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001406 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1407 }
1408 }
1409
1410 // Drop all inter-phi links and any loads that made it this far.
1411 for (DenseMap<Value*, std::vector<Value*> >::iterator
1412 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1413 I != E; ++I) {
1414 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1415 PN->dropAllReferences();
1416 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1417 LI->dropAllReferences();
1418 }
1419
1420 // Delete all the phis and loads now that inter-references are dead.
1421 for (DenseMap<Value*, std::vector<Value*> >::iterator
1422 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1423 I != E; ++I) {
1424 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1425 PN->eraseFromParent();
1426 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1427 LI->eraseFromParent();
1428 }
1429
Chris Lattner86395032006-09-30 23:32:09 +00001430 // The old global is now dead, remove it.
1431 GV->eraseFromParent();
1432
1433 ++NumHeapSRA;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001434 return cast<GlobalVariable>(FieldGlobals[0]);
Chris Lattner86395032006-09-30 23:32:09 +00001435}
1436
Chris Lattnere61d0a62008-12-15 21:02:25 +00001437/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1438/// pointer global variable with a single value stored it that is a malloc or
1439/// cast of malloc.
1440static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1441 MallocInst *MI,
1442 Module::global_iterator &GVI,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001443 TargetData &TD,
1444 LLVMContext* Context) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001445 // If this is a malloc of an abstract type, don't touch it.
1446 if (!MI->getAllocatedType()->isSized())
1447 return false;
1448
1449 // We can't optimize this global unless all uses of it are *known* to be
1450 // of the malloc value, not of the null initializer value (consider a use
1451 // that compares the global's value against zero to see if the malloc has
1452 // been reached). To do this, we check to see if all uses of the global
1453 // would trap if the global were null: this proves that they must all
1454 // happen after the malloc.
1455 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1456 return false;
1457
1458 // We can't optimize this if the malloc itself is used in a complex way,
1459 // for example, being stored into multiple globals. This allows the
1460 // malloc to be stored into the specified global, loaded setcc'd, and
1461 // GEP'd. These are all things we could transform to using the global
1462 // for.
1463 {
1464 SmallPtrSet<PHINode*, 8> PHIs;
1465 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1466 return false;
1467 }
1468
1469
1470 // If we have a global that is only initialized with a fixed size malloc,
1471 // transform the program to use global memory instead of malloc'd memory.
1472 // This eliminates dynamic allocation, avoids an indirection accessing the
1473 // data, and exposes the resultant global to further GlobalOpt.
1474 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1475 // Restrict this transformation to only working on small allocations
1476 // (2048 bytes currently), as we don't want to introduce a 16M global or
1477 // something.
1478 if (NElements->getZExtValue()*
Duncan Sands777d2302009-05-09 07:06:46 +00001479 TD.getTypeAllocSize(MI->getAllocatedType()) < 2048) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001480 GVI = OptimizeGlobalAddressOfMalloc(GV, MI, Context);
Chris Lattnere61d0a62008-12-15 21:02:25 +00001481 return true;
1482 }
1483 }
1484
1485 // If the allocation is an array of structures, consider transforming this
1486 // into multiple malloc'd arrays, one for each field. This is basically
1487 // SRoA for malloc'd memory.
Chris Lattner101f44e2008-12-15 21:44:34 +00001488 const Type *AllocTy = MI->getAllocatedType();
1489
1490 // If this is an allocation of a fixed size array of structs, analyze as a
1491 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1492 if (!MI->isArrayAllocation())
1493 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1494 AllocTy = AT->getElementType();
1495
1496 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattnere61d0a62008-12-15 21:02:25 +00001497 // This the structure has an unreasonable number of fields, leave it
1498 // alone.
Chris Lattner101f44e2008-12-15 21:44:34 +00001499 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001500 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner101f44e2008-12-15 21:44:34 +00001501
1502 // If this is a fixed size array, transform the Malloc to be an alloc of
1503 // structs. malloc [100 x struct],1 -> malloc struct, 100
1504 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1505 MallocInst *NewMI =
1506 new MallocInst(AllocSTy,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001507 Context->getConstantInt(Type::Int32Ty, AT->getNumElements()),
Chris Lattner101f44e2008-12-15 21:44:34 +00001508 "", MI);
1509 NewMI->takeName(MI);
1510 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1511 MI->replaceAllUsesWith(Cast);
1512 MI->eraseFromParent();
1513 MI = NewMI;
1514 }
1515
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001516 GVI = PerformHeapAllocSRoA(GV, MI, Context);
Chris Lattnere61d0a62008-12-15 21:02:25 +00001517 return true;
1518 }
1519 }
1520
1521 return false;
1522}
Chris Lattner86395032006-09-30 23:32:09 +00001523
Chris Lattner9b34a612004-10-09 21:48:45 +00001524// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1525// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001526static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001527 Module::global_iterator &GVI,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001528 TargetData &TD, LLVMContext* Context) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001529 // Ignore no-op GEPs and bitcasts.
1530 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001531
Chris Lattner708148e2004-10-10 23:14:11 +00001532 // If we are dealing with a pointer global that is initialized to null and
1533 // only has one (non-null) value stored into it, then we can optimize any
1534 // users of the loaded value (often calls and loads) that would trap if the
1535 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001536 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1537 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001538 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1539 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001540 SOVC =
1541 Context->getConstantExprBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001542
Chris Lattner708148e2004-10-10 23:14:11 +00001543 // Optimize away any trapping uses of the loaded value.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001544 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
Chris Lattner8be80122004-10-10 17:07:12 +00001545 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001546 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001547 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD, Context))
Chris Lattnere61d0a62008-12-15 21:02:25 +00001548 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001549 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001550 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001551
Chris Lattner9b34a612004-10-09 21:48:45 +00001552 return false;
1553}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001554
Chris Lattner58e44f42008-01-14 01:17:44 +00001555/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1556/// two values ever stored into GV are its initializer and OtherVal. See if we
1557/// can shrink the global into a boolean and select between the two values
1558/// whenever it is used. This exposes the values to other scalar optimizations.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001559static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
1560 LLVMContext* Context) {
Chris Lattner58e44f42008-01-14 01:17:44 +00001561 const Type *GVElType = GV->getType()->getElementType();
1562
1563 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001564 // an FP value, pointer or vector, don't do this optimization because a select
1565 // between them is very expensive and unlikely to lead to later
1566 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1567 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner58e44f42008-01-14 01:17:44 +00001568 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
Chris Lattner6f6923f2009-03-07 23:32:02 +00001569 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
Chris Lattner58e44f42008-01-14 01:17:44 +00001570 return false;
1571
1572 // Walk the use list of the global seeing if all the uses are load or store.
1573 // If there is anything else, bail out.
1574 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel771281f2009-03-06 01:39:36 +00001575 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattner58e44f42008-01-14 01:17:44 +00001576 return false;
1577
1578 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1579
Chris Lattner96a86b22004-12-12 05:53:50 +00001580 // Create the new global, initializing it to false.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001581 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001582 GlobalValue::InternalLinkage, Context->getConstantIntFalse(),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001583 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001584 (Module *)NULL,
1585 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001586 GV->getParent()->getGlobalList().insert(GV, NewGV);
1587
1588 Constant *InitVal = GV->getInitializer();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001589 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001590
1591 // If initialized to zero and storing one into the global, we can use a cast
1592 // instead of a select to synthesize the desired value.
1593 bool IsOneZero = false;
1594 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001595 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001596
1597 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001598 Instruction *UI = cast<Instruction>(GV->use_back());
1599 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001600 // Change the store into a boolean store.
1601 bool StoringOther = SI->getOperand(0) == OtherVal;
1602 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001603 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001604 if (StoringOther || SI->getOperand(0) == InitVal)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001605 StoreVal = Context->getConstantInt(Type::Int1Ty, StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001606 else {
1607 // Otherwise, we are storing a previously loaded copy. To do this,
1608 // change the copy from copying the original value to just copying the
1609 // bool.
1610 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1611
1612 // If we're already replaced the input, StoredVal will be a cast or
1613 // select instruction. If not, it will be a load of the original
1614 // global.
1615 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1616 assert(LI->getOperand(0) == GV && "Not a copy!");
1617 // Insert a new load, to preserve the saved value.
1618 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1619 } else {
1620 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1621 "This is not a form that we understand!");
1622 StoreVal = StoredVal->getOperand(0);
1623 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1624 }
1625 }
1626 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001627 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001628 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001629 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001630 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001631 Value *NSI;
1632 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001633 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001634 else
Gabor Greif051a9502008-04-06 20:25:17 +00001635 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001636 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001637 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001638 }
1639 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001640 }
1641
1642 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001643 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001644}
1645
1646
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001647/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1648/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001649bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001650 Module::global_iterator &GVI) {
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001651 SmallPtrSet<PHINode*, 16> PHIUsers;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001652 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001653 GV->removeDeadConstantUsers();
1654
1655 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001656 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001657 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001658 ++NumDeleted;
1659 return true;
1660 }
1661
1662 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001663#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001664 cerr << "Global: " << *GV;
1665 cerr << " isLoaded = " << GS.isLoaded << "\n";
1666 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001667 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001668 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1669 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1670 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1671 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001672 }
1673 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001674 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001675 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001676 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001677 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001678 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001679 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001680 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001681 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001682#endif
1683
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001684 // If this is a first class global and has only one accessing function
1685 // and this function is main (which we know is not recursive we can make
1686 // this global a local variable) we replace the global with a local alloca
1687 // in this function.
1688 //
Dan Gohman399101a2008-05-23 00:17:26 +00001689 // NOTE: It doesn't make sense to promote non single-value types since we
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001690 // are just replacing static memory to stack memory.
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001691 //
1692 // If the global is in different address space, don't bring it to stack.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001693 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001694 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman399101a2008-05-23 00:17:26 +00001695 GV->getType()->getElementType()->isSingleValueType() &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001696 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta059aa8c2009-06-17 06:47:15 +00001697 GS.AccessingFunction->hasExternalLinkage() &&
1698 GV->getType()->getAddressSpace() == 0) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001699 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001700 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1701 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001702 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001703 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1704 if (!isa<UndefValue>(GV->getInitializer()))
1705 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001706
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001707 GV->replaceAllUsesWith(Alloca);
1708 GV->eraseFromParent();
1709 ++NumLocalized;
1710 return true;
1711 }
Chris Lattnercff16732006-09-30 19:40:30 +00001712
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001713 // If the global is never loaded (but may be stored to), it is dead.
1714 // Delete it now.
1715 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001716 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001717
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001718 // Delete any stores we can find to the global. We may not be able to
1719 // make it completely dead though.
Chris Lattner031955d2004-10-10 16:43:46 +00001720 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001721
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001722 // If the global is dead now, delete it.
1723 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001724 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001725 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001726 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001727 }
Chris Lattner930f4752004-10-09 03:32:52 +00001728 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001729
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001730 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001731 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001732 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001733
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001734 // Clean up any obviously simplifiable users now.
1735 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001736
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001737 // If the global is dead now, just nuke it.
1738 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001739 DOUT << " *** Marking constant allowed us to simplify "
1740 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001741 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001742 ++NumDeleted;
1743 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001744
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001745 ++NumMarked;
1746 return true;
Dan Gohman399101a2008-05-23 00:17:26 +00001747 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Chris Lattner998182b2008-04-26 07:40:11 +00001748 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001749 getAnalysis<TargetData>(),
1750 Context)) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001751 GVI = FirstNewGV; // Don't skip the newly produced globals!
1752 return true;
1753 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001754 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001755 // If the initial value for the global was an undef value, and if only
1756 // one other value was stored into it, we can just change the
Duncan Sandsb5024402009-01-13 13:48:44 +00001757 // initializer to be the stored value, then delete all stores to the
Chris Lattner96a86b22004-12-12 05:53:50 +00001758 // global. This allows us to mark it constant.
1759 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1760 if (isa<UndefValue>(GV->getInitializer())) {
1761 // Change the initial value here.
1762 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001763
Chris Lattner96a86b22004-12-12 05:53:50 +00001764 // Clean up any obviously simplifiable users now.
1765 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001766
Chris Lattner96a86b22004-12-12 05:53:50 +00001767 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001768 DOUT << " *** Substituting initializer allowed us to "
1769 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001770 GV->eraseFromParent();
1771 ++NumDeleted;
1772 } else {
1773 GVI = GV;
1774 }
1775 ++NumSubstitute;
1776 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001777 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001778
Chris Lattner9b34a612004-10-09 21:48:45 +00001779 // Try to optimize globals based on the knowledge that only one value
1780 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001781 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001782 getAnalysis<TargetData>(), Context))
Chris Lattner9b34a612004-10-09 21:48:45 +00001783 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001784
1785 // Otherwise, if the global was not a boolean, we can shrink it to be a
1786 // boolean.
1787 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001788 if (TryToShrinkGlobalToBoolean(GV, SOVConstant, Context)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001789 ++NumShrunkToBool;
1790 return true;
1791 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001792 }
1793 }
1794 return false;
1795}
1796
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001797/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1798/// function, changing them to FastCC.
1799static void ChangeCalleesToFastCall(Function *F) {
1800 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001801 CallSite User(cast<Instruction>(*UI));
1802 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001803 }
1804}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001805
Devang Patel05988662008-09-25 21:00:45 +00001806static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001807 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001808 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001809 continue;
1810
Duncan Sands548448a2008-02-18 17:32:13 +00001811 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001812 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001813 }
1814
1815 return Attrs;
1816}
1817
1818static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001819 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001820 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001821 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001822 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001823 }
1824}
1825
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001826bool GlobalOpt::OptimizeFunctions(Module &M) {
1827 bool Changed = false;
1828 // Optimize functions.
1829 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1830 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001831 // Functions without names cannot be referenced outside this module.
1832 if (!F->hasName() && !F->isDeclaration())
1833 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001834 F->removeDeadConstantUsers();
Rafael Espindolabb46f522009-01-15 20:18:42 +00001835 if (F->use_empty() && (F->hasLocalLinkage() ||
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001836 F->hasLinkOnceLinkage())) {
1837 M.getFunctionList().erase(F);
1838 Changed = true;
1839 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001840 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001841 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001842 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001843 // If this function has C calling conventions, is not a varargs
1844 // function, and is only called directly, promote it to use the Fast
1845 // calling convention.
1846 F->setCallingConv(CallingConv::Fast);
1847 ChangeCalleesToFastCall(F);
1848 ++NumFastCallFns;
1849 Changed = true;
1850 }
1851
Devang Patel05988662008-09-25 21:00:45 +00001852 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001853 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001854 // The function is not used by a trampoline intrinsic, so it is safe
1855 // to remove the 'nest' attribute.
1856 RemoveNestAttribute(F);
1857 ++NumNestRemoved;
1858 Changed = true;
1859 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001860 }
1861 }
1862 return Changed;
1863}
1864
1865bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1866 bool Changed = false;
1867 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1868 GVI != E; ) {
1869 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001870 // Global variables without names cannot be referenced outside this module.
1871 if (!GV->hasName() && !GV->isDeclaration())
1872 GV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolabb46f522009-01-15 20:18:42 +00001873 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001874 GV->hasInitializer())
1875 Changed |= ProcessInternalGlobal(GV, GVI);
1876 }
1877 return Changed;
1878}
1879
1880/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1881/// initializers have an init priority of 65535.
1882GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001883 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1884 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001885 if (I->getName() == "llvm.global_ctors") {
1886 // Found it, verify it's an array of { int, void()* }.
1887 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1888 if (!ATy) return 0;
1889 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1890 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc5b206b2006-12-31 05:48:39 +00001891 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001892 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1893 if (!PFTy) return 0;
1894 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1895 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1896 FTy->getNumParams() != 0)
1897 return 0;
1898
1899 // Verify that the initializer is simple enough for us to handle.
1900 if (!I->hasInitializer()) return 0;
1901 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1902 if (!CA) return 0;
Gabor Greif5e463212008-05-29 01:59:18 +00001903 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1904 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001905 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1906 continue;
1907
1908 // Must have a function or null ptr.
1909 if (!isa<Function>(CS->getOperand(1)))
1910 return 0;
1911
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001912 // Init priority must be standard.
1913 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001914 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001915 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001916 } else {
1917 return 0;
1918 }
1919
1920 return I;
1921 }
1922 return 0;
1923}
1924
Chris Lattnerdb973e62005-09-26 02:31:18 +00001925/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1926/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001927static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1928 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1929 std::vector<Function*> Result;
1930 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001931 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1932 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001933 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1934 }
1935 return Result;
1936}
1937
Chris Lattnerdb973e62005-09-26 02:31:18 +00001938/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1939/// specified array, returning the new global to use.
1940static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001941 const std::vector<Function*> &Ctors,
1942 LLVMContext* Context) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001943 // If we made a change, reassemble the initializer list.
1944 std::vector<Constant*> CSVals;
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001945 CSVals.push_back(Context->getConstantInt(Type::Int32Ty, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001946 CSVals.push_back(0);
1947
1948 // Create the new init list.
1949 std::vector<Constant*> CAList;
1950 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001951 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001952 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001953 } else {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001954 const Type *FTy = Context->getFunctionType(Type::VoidTy, false);
1955 const PointerType *PFTy = Context->getPointerTypeUnqual(FTy);
1956 CSVals[1] = Context->getNullValue(PFTy);
1957 CSVals[0] = Context->getConstantInt(Type::Int32Ty, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001958 }
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001959 CAList.push_back(Context->getConstantStruct(CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001960 }
1961
1962 // Create the array initializer.
1963 const Type *StructTy =
1964 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001965 Constant *CA = Context->getConstantArray(ArrayType::get(StructTy,
1966 CAList.size()), CAList);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001967
1968 // If we didn't change the number of elements, don't create a new GV.
1969 if (CA->getType() == GCL->getInitializer()->getType()) {
1970 GCL->setInitializer(CA);
1971 return GCL;
1972 }
1973
1974 // Create the new global and insert it next to the existing list.
1975 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001976 GCL->getLinkage(), CA, "",
1977 (Module *)NULL,
1978 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001979 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001980 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001981
1982 // Nuke the old list, replacing any uses with the new one.
1983 if (!GCL->use_empty()) {
1984 Constant *V = NGV;
1985 if (V->getType() != GCL->getType())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00001986 V = Context->getConstantExprBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001987 GCL->replaceAllUsesWith(V);
1988 }
1989 GCL->eraseFromParent();
1990
1991 if (Ctors.size())
1992 return NGV;
1993 else
1994 return 0;
1995}
Chris Lattner79c11012005-09-26 04:44:35 +00001996
1997
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00001998static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Chris Lattner79c11012005-09-26 04:44:35 +00001999 Value *V) {
2000 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2001 Constant *R = ComputedValues[V];
2002 assert(R && "Reference to an uncomputed value!");
2003 return R;
2004}
2005
2006/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2007/// enough for us to understand. In particular, if it is a cast of something,
2008/// we punt. We basically just support direct accesses to globals and GEP's of
2009/// globals. This should be kept up to date with CommitValueTo.
2010static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner231308c2005-09-27 04:50:03 +00002011 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolabb46f522009-01-15 20:18:42 +00002012 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002013 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00002014 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00002015 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002016 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2017 // Handle a constantexpr gep.
2018 if (CE->getOpcode() == Instruction::GetElementPtr &&
2019 isa<GlobalVariable>(CE->getOperand(0))) {
2020 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolabb46f522009-01-15 20:18:42 +00002021 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00002022 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00002023 return GV->hasInitializer() &&
2024 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2025 }
Chris Lattner79c11012005-09-26 04:44:35 +00002026 return false;
2027}
2028
Chris Lattner798b4d52005-09-26 06:52:44 +00002029/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2030/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2031/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2032static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002033 ConstantExpr *Addr, unsigned OpNo,
2034 LLVMContext* Context) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002035 // Base case of the recursion.
2036 if (OpNo == Addr->getNumOperands()) {
2037 assert(Val->getType() == Init->getType() && "Type mismatch!");
2038 return Val;
2039 }
2040
2041 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2042 std::vector<Constant*> Elts;
2043
2044 // Break up the constant into its elements.
2045 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002046 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2047 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002048 } else if (isa<ConstantAggregateZero>(Init)) {
2049 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002050 Elts.push_back(Context->getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002051 } else if (isa<UndefValue>(Init)) {
2052 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002053 Elts.push_back(Context->getUndef(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002054 } else {
2055 assert(0 && "This code is out of sync with "
2056 " ConstantFoldLoadThroughGEPConstantExpr");
2057 }
2058
2059 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002060 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2061 unsigned Idx = CU->getZExtValue();
2062 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002063 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002064
2065 // Return the modified struct.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002066 return Context->getConstantStruct(&Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00002067 } else {
2068 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2069 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2070
2071 // Break up the array into elements.
2072 std::vector<Constant*> Elts;
2073 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002074 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2075 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002076 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002077 Constant *Elt = Context->getNullValue(ATy->getElementType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002078 Elts.assign(ATy->getNumElements(), Elt);
2079 } else if (isa<UndefValue>(Init)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002080 Constant *Elt = Context->getUndef(ATy->getElementType());
Chris Lattner798b4d52005-09-26 06:52:44 +00002081 Elts.assign(ATy->getNumElements(), Elt);
2082 } else {
2083 assert(0 && "This code is out of sync with "
2084 " ConstantFoldLoadThroughGEPConstantExpr");
2085 }
2086
Reid Spencerb83eb642006-10-20 07:07:24 +00002087 assert(CI->getZExtValue() < ATy->getNumElements());
2088 Elts[CI->getZExtValue()] =
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002089 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
2090 return Context->getConstantArray(ATy, Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002091 }
2092}
2093
Chris Lattner79c11012005-09-26 04:44:35 +00002094/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2095/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002096static void CommitValueTo(Constant *Val, Constant *Addr,
2097 LLVMContext* Context) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002098 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2099 assert(GV->hasInitializer());
2100 GV->setInitializer(Val);
2101 return;
2102 }
2103
2104 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2105 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2106
2107 Constant *Init = GV->getInitializer();
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002108 Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
Chris Lattner798b4d52005-09-26 06:52:44 +00002109 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00002110}
2111
Chris Lattner562a0552005-09-26 05:16:34 +00002112/// ComputeLoadResult - Return the value that would be computed by a load from
2113/// P after the stores reflected by 'memory' have been performed. If we can't
2114/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002115static Constant *ComputeLoadResult(Constant *P,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002116 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002117 // If this memory location has been recently stored, use the stored value: it
2118 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002119 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002120 if (I != Memory.end()) return I->second;
2121
2122 // Access it.
2123 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2124 if (GV->hasInitializer())
2125 return GV->getInitializer();
2126 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002127 }
Chris Lattner798b4d52005-09-26 06:52:44 +00002128
2129 // Handle a constantexpr getelementptr.
2130 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2131 if (CE->getOpcode() == Instruction::GetElementPtr &&
2132 isa<GlobalVariable>(CE->getOperand(0))) {
2133 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2134 if (GV->hasInitializer())
2135 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2136 }
2137
2138 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002139}
2140
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002141/// EvaluateFunction - Evaluate a call to function F, returning true if
2142/// successful, false if we can't evaluate it. ActualArgs contains the formal
2143/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002144static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002145 const std::vector<Constant*> &ActualArgs,
2146 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002147 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002148 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00002149 // Check to see if this function is already executing (recursion). If so,
2150 // bail out. TODO: we might want to accept limited recursion.
2151 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2152 return false;
2153
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002154 LLVMContext* Context = F->getContext();
2155
Chris Lattnercd271422005-09-27 04:45:34 +00002156 CallStack.push_back(F);
2157
Chris Lattner79c11012005-09-26 04:44:35 +00002158 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002159 DenseMap<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00002160
2161 // Initialize arguments to the incoming values specified.
2162 unsigned ArgNo = 0;
2163 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2164 ++AI, ++ArgNo)
2165 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002166
Chris Lattnercdf98be2005-09-26 04:57:38 +00002167 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2168 /// we can only evaluate any one basic block at most once. This set keeps
2169 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002170 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00002171
Chris Lattner79c11012005-09-26 04:44:35 +00002172 // CurInst - The current instruction we're evaluating.
2173 BasicBlock::iterator CurInst = F->begin()->begin();
2174
2175 // This is the main evaluation loop.
2176 while (1) {
2177 Constant *InstResult = 0;
2178
2179 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002180 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002181 Constant *Ptr = getVal(Values, SI->getOperand(1));
2182 if (!isSimpleEnoughPointerToCommit(Ptr))
2183 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002184 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002185 Constant *Val = getVal(Values, SI->getOperand(0));
2186 MutatedMemory[Ptr] = Val;
2187 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002188 InstResult = Context->getConstantExpr(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002189 getVal(Values, BO->getOperand(0)),
2190 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002191 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002192 InstResult = Context->getConstantExprCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002193 getVal(Values, CI->getOperand(0)),
2194 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002195 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002196 InstResult = Context->getConstantExprCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002197 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002198 CI->getType());
2199 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002200 InstResult =
2201 Context->getConstantExprSelect(getVal(Values, SI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002202 getVal(Values, SI->getOperand(1)),
2203 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002204 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2205 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002206 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002207 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2208 i != e; ++i)
2209 GEPOps.push_back(getVal(Values, *i));
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002210 InstResult =
2211 Context->getConstantExprGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002212 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002213 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002214 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2215 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002216 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002217 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002218 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002219 const Type *Ty = AI->getType()->getElementType();
2220 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2221 GlobalValue::InternalLinkage,
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002222 Context->getUndef(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002223 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002224 InstResult = AllocaTmps.back();
2225 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002226
2227 // Debug info can safely be ignored here.
2228 if (isa<DbgInfoIntrinsic>(CI)) {
2229 ++CurInst;
2230 continue;
2231 }
2232
Chris Lattner7cd580f2006-07-07 21:37:01 +00002233 // Cannot handle inline asm.
2234 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2235
Chris Lattnercd271422005-09-27 04:45:34 +00002236 // Resolve function pointers.
2237 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2238 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002239
Chris Lattnercd271422005-09-27 04:45:34 +00002240 std::vector<Constant*> Formals;
Gabor Greif5e463212008-05-29 01:59:18 +00002241 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2242 i != e; ++i)
2243 Formals.push_back(getVal(Values, *i));
Chris Lattnercd271422005-09-27 04:45:34 +00002244
Reid Spencer5cbf9852007-01-30 20:08:39 +00002245 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002246 // If this is a function we can constant fold, do it.
Chris Lattner6c1f5652007-01-30 23:14:52 +00002247 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2248 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002249 InstResult = C;
2250 } else {
2251 return false;
2252 }
2253 } else {
2254 if (Callee->getFunctionType()->isVarArg())
2255 return false;
2256
2257 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002258 // Execute the call, if successful, use the return value.
2259 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2260 MutatedMemory, AllocaTmps))
2261 return false;
2262 InstResult = RetVal;
2263 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002264 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002265 BasicBlock *NewBB = 0;
2266 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2267 if (BI->isUnconditional()) {
2268 NewBB = BI->getSuccessor(0);
2269 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002270 ConstantInt *Cond =
2271 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002272 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002273
Reid Spencer579dca12007-01-12 04:24:46 +00002274 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002275 }
2276 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2277 ConstantInt *Val =
2278 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002279 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002280 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2281 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002282 if (RI->getNumOperands())
2283 RetVal = getVal(Values, RI->getOperand(0));
2284
2285 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002286 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002287 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002288 // invoke, unwind, unreachable.
2289 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002290 }
2291
2292 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002293 // executed the new block before. If so, we have a looping function,
2294 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002295 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002296 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002297
2298 // Okay, we have never been in this block before. Check to see if there
2299 // are any PHI nodes. If so, evaluate them with information about where
2300 // we came from.
2301 BasicBlock *OldBB = CurInst->getParent();
2302 CurInst = NewBB->begin();
2303 PHINode *PN;
2304 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2305 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2306
2307 // Do NOT increment CurInst. We know that the terminator had no value.
2308 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002309 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002310 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002311 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002312 }
2313
2314 if (!CurInst->use_empty())
2315 Values[CurInst] = InstResult;
2316
2317 // Advance program counter.
2318 ++CurInst;
2319 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002320}
2321
2322/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2323/// we can. Return true if we can, false otherwise.
2324static bool EvaluateStaticConstructor(Function *F) {
2325 /// MutatedMemory - For each store we execute, we update this map. Loads
2326 /// check this to get the most up-to-date value. If evaluation is successful,
2327 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002328 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002329
2330 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2331 /// to represent its body. This vector is needed so we can delete the
2332 /// temporary globals when we are done.
2333 std::vector<GlobalVariable*> AllocaTmps;
2334
2335 /// CallStack - This is used to detect recursion. In pathological situations
2336 /// we could hit exponential behavior, but at least there is nothing
2337 /// unbounded.
2338 std::vector<Function*> CallStack;
2339
2340 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002341 Constant *RetValDummy;
2342 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2343 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002344 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002345 // We succeeded at evaluation: commit the result.
Bill Wendling0a81aac2006-11-26 10:02:32 +00002346 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2347 << F->getName() << "' to " << MutatedMemory.size()
2348 << " stores.\n";
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002349 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002350 E = MutatedMemory.end(); I != E; ++I)
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002351 CommitValueTo(I->second, I->first, F->getContext());
Chris Lattnera22fdb02005-09-26 17:07:09 +00002352 }
Chris Lattner79c11012005-09-26 04:44:35 +00002353
Chris Lattnera22fdb02005-09-26 17:07:09 +00002354 // At this point, we are done interpreting. If we created any 'alloca'
2355 // temporaries, release them now.
2356 while (!AllocaTmps.empty()) {
2357 GlobalVariable *Tmp = AllocaTmps.back();
2358 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002359
Chris Lattnera22fdb02005-09-26 17:07:09 +00002360 // If there are still users of the alloca, the program is doing something
2361 // silly, e.g. storing the address of the alloca somewhere and using it
2362 // later. Since this is undefined, we'll just make it be null.
2363 if (!Tmp->use_empty())
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002364 Tmp->replaceAllUsesWith(F->getContext()->getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002365 delete Tmp;
2366 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002367
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002368 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002369}
2370
Chris Lattnerdb973e62005-09-26 02:31:18 +00002371
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002372
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002373/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2374/// Return true if anything changed.
2375bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2376 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2377 bool MadeChange = false;
2378 if (Ctors.empty()) return false;
2379
2380 // Loop over global ctors, optimizing them when we can.
2381 for (unsigned i = 0; i != Ctors.size(); ++i) {
2382 Function *F = Ctors[i];
2383 // Found a null terminator in the middle of the list, prune off the rest of
2384 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002385 if (F == 0) {
2386 if (i != Ctors.size()-1) {
2387 Ctors.resize(i+1);
2388 MadeChange = true;
2389 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002390 break;
2391 }
2392
Chris Lattner79c11012005-09-26 04:44:35 +00002393 // We cannot simplify external ctor functions.
2394 if (F->empty()) continue;
2395
2396 // If we can evaluate the ctor at compile time, do.
2397 if (EvaluateStaticConstructor(F)) {
2398 Ctors.erase(Ctors.begin()+i);
2399 MadeChange = true;
2400 --i;
2401 ++NumCtorsEvaluated;
2402 continue;
2403 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002404 }
2405
2406 if (!MadeChange) return false;
2407
Owen Anderson14ce9ef2009-07-06 01:34:54 +00002408 GCL = InstallGlobalCtors(GCL, Ctors, Context);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002409 return true;
2410}
2411
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002412bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002413 bool Changed = false;
2414
Duncan Sands177d84e2009-01-07 20:01:06 +00002415 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002416 I != E;) {
2417 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002418 // Aliases without names cannot be referenced outside this module.
2419 if (!J->hasName() && !J->isDeclaration())
2420 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002421 // If the aliasee may change at link time, nothing can be done - bail out.
2422 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002423 continue;
2424
Duncan Sands4782b302009-02-15 09:56:08 +00002425 Constant *Aliasee = J->getAliasee();
2426 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002427 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002428 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2429
2430 // Make all users of the alias use the aliasee instead.
2431 if (!J->use_empty()) {
2432 J->replaceAllUsesWith(Aliasee);
2433 ++NumAliasesResolved;
2434 Changed = true;
2435 }
2436
2437 // If the aliasee has internal linkage, give it the name and linkage
2438 // of the alias, and delete the alias. This turns:
2439 // define internal ... @f(...)
2440 // @a = alias ... @f
2441 // into:
2442 // define ... @a(...)
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002443 if (!Target->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002444 continue;
2445
2446 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands7ae5b9e2009-02-17 17:50:04 +00002447 if (J->hasLocalLinkage())
Duncan Sands4782b302009-02-15 09:56:08 +00002448 continue;
2449
Duncan Sandsa37d1192009-02-15 11:54:49 +00002450 // Do not perform the transform if multiple aliases potentially target the
2451 // aliasee. This check also ensures that it is safe to replace the section
2452 // and other attributes of the aliasee with those of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002453 if (!hasOneUse)
2454 continue;
2455
Duncan Sandsa37d1192009-02-15 11:54:49 +00002456 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sands4782b302009-02-15 09:56:08 +00002457 Target->takeName(J);
2458 Target->setLinkage(J->getLinkage());
Duncan Sandsa37d1192009-02-15 11:54:49 +00002459 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sands4782b302009-02-15 09:56:08 +00002460
2461 // Delete the alias.
2462 M.getAliasList().erase(J);
2463 ++NumAliasesRemoved;
2464 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002465 }
2466
2467 return Changed;
2468}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002469
Chris Lattner7a90b682004-10-07 04:16:33 +00002470bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002471 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002472
2473 // Try to find the llvm.globalctors list.
2474 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002475
Chris Lattner7a90b682004-10-07 04:16:33 +00002476 bool LocalChange = true;
2477 while (LocalChange) {
2478 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002479
2480 // Delete functions that are trivially dead, ccc -> fastcc
2481 LocalChange |= OptimizeFunctions(M);
2482
2483 // Optimize global_ctors list.
2484 if (GlobalCtors)
2485 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2486
2487 // Optimize non-address-taken globals.
2488 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002489
2490 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002491 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002492 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002493 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002494
2495 // TODO: Move all global ctors functions to the end of the module for code
2496 // layout.
2497
Chris Lattner079236d2004-02-25 21:34:36 +00002498 return Changed;
2499}