blob: 2e869e6e45de87510caaeea3c0c544dc08523623 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
Jay Foad562b84b2011-04-11 09:35:34 +000024#include "llvm/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000025#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000027#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000028#include "llvm/Target/TargetData.h"
Chad Rosier00737bd2011-12-01 21:29:16 +000029#include "llvm/Target/TargetLibraryInfo.h"
Duncan Sands548448a2008-02-18 17:32:13 +000030#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000034#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000040#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000041#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000042using namespace llvm;
43
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000045STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000046STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49STATISTIC(NumDeleted , "Number of globals deleted");
50STATISTIC(NumFnDeleted , "Number of functions deleted");
51STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52STATISTIC(NumLocalized , "Number of globals localized");
53STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000056STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000057STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000059STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000060
Chris Lattner86453c52006-12-19 22:09:18 +000061namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000062 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000065 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000066 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000068 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
70 }
Misha Brukmanfd939082005-04-21 23:48:37 +000071
Chris Lattnerb12914b2004-09-20 04:48:05 +000072 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000073
74 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000075 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000078 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000079 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000080 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Chris Lattner079236d2004-02-25 21:34:36 +000085 };
Chris Lattner079236d2004-02-25 21:34:36 +000086}
87
Dan Gohman844731a2008-05-13 00:00:25 +000088char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000089INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
90 "Global Variable Optimizer", false, false)
91INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
92INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000093 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000094
Chris Lattner7a90b682004-10-07 04:16:33 +000095ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000096
Dan Gohman844731a2008-05-13 00:00:25 +000097namespace {
98
Chris Lattner7a90b682004-10-07 04:16:33 +000099/// GlobalStatus - As we analyze each global, keep track of some information
100/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000101/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000102struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000103 /// isCompared - True if the global's address is used in a comparison.
104 bool isCompared;
105
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000106 /// isLoaded - True if the global is ever loaded. If the global isn't ever
107 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000108 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000109
110 /// StoredType - Keep track of what stores to the global look like.
111 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000112 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000113 /// NotStored - There is no store to this global. It can thus be marked
114 /// constant.
115 NotStored,
116
117 /// isInitializerStored - This global is stored to, but the only thing
118 /// stored is the constant it was initialized with. This is only tracked
119 /// for scalar globals.
120 isInitializerStored,
121
122 /// isStoredOnce - This global is stored to, but only its initializer and
123 /// one other value is ever stored to it. If this global isStoredOnce, we
124 /// track the value stored to it in StoredOnceValue below. This is only
125 /// tracked for scalar globals.
126 isStoredOnce,
127
128 /// isStored - This global is stored to by multiple values or something else
129 /// that we cannot track.
130 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000131 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000132
133 /// StoredOnceValue - If only one value (besides the initializer constant) is
134 /// ever stored to this global, keep track of what value it is.
135 Value *StoredOnceValue;
136
Chris Lattner25de4e52006-11-01 18:03:33 +0000137 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
138 /// null/false. When the first accessing function is noticed, it is recorded.
139 /// When a second different accessing function is noticed,
140 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000141 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000142 bool HasMultipleAccessingFunctions;
143
Chris Lattner25de4e52006-11-01 18:03:33 +0000144 /// HasNonInstructionUser - Set to true if this global has a user that is not
145 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000146 bool HasNonInstructionUser;
147
Chris Lattner25de4e52006-11-01 18:03:33 +0000148 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
149 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000150
Rafael Espindolac4440e32011-01-19 16:32:21 +0000151 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
152 StoredOnceValue(0), AccessingFunction(0),
153 HasMultipleAccessingFunctions(false), HasNonInstructionUser(false),
154 HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000155};
Chris Lattnere47ba742004-10-06 20:57:02 +0000156
Dan Gohman844731a2008-05-13 00:00:25 +0000157}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000158
Jay Foade3acf152009-06-09 21:37:11 +0000159// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
160// by constants itself. Note that constants cannot be cyclic, so this test is
161// pretty easy to implement recursively.
162//
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000163static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000164 if (isa<GlobalValue>(C)) return false;
165
Gabor Greif27236912010-04-07 18:59:26 +0000166 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
167 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000168 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000169 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000170 } else
171 return false;
172 return true;
173}
174
175
Chris Lattner7a90b682004-10-07 04:16:33 +0000176/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
177/// structure. If the global has its address taken, return true to indicate we
178/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000179///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000180static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
181 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000182 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000183 ++UI) {
184 const User *U = *UI;
185 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000186 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000187
188 // If the result of the constantexpr isn't pointer type, then we won't
189 // know to expect it in various places. Just reject early.
190 if (!isa<PointerType>(CE->getType())) return true;
191
Chris Lattner7a90b682004-10-07 04:16:33 +0000192 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000193 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000194 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000195 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000196 if (GS.AccessingFunction == 0)
197 GS.AccessingFunction = F;
198 else if (GS.AccessingFunction != F)
199 GS.HasMultipleAccessingFunctions = true;
200 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000201 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000202 GS.isLoaded = true;
Eli Friedman33cb4452011-08-16 00:20:11 +0000203 // Don't hack on volatile/atomic loads.
204 if (!LI->isSimple()) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000205 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000206 // Don't allow a store OF the address, only stores TO the address.
207 if (SI->getOperand(0) == V) return true;
208
Eli Friedman33cb4452011-08-16 00:20:11 +0000209 // Don't hack on volatile/atomic stores.
210 if (!SI->isSimple()) return true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000211
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000212 // If this is a direct store to the global (i.e., the global is a scalar
213 // value, not an aggregate), keep more specific information about
214 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000215 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000216 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
217 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000218 Value *StoredVal = SI->getOperand(0);
219 if (StoredVal == GV->getInitializer()) {
220 if (GS.StoredType < GlobalStatus::isInitializerStored)
221 GS.StoredType = GlobalStatus::isInitializerStored;
222 } else if (isa<LoadInst>(StoredVal) &&
223 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000224 if (GS.StoredType < GlobalStatus::isInitializerStored)
225 GS.StoredType = GlobalStatus::isInitializerStored;
226 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
227 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000228 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000229 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000230 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000231 // noop.
232 } else {
233 GS.StoredType = GlobalStatus::isStored;
234 }
235 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000236 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000237 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000238 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000239 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000240 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000241 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000242 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000243 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000244 // PHI nodes we can check just like select or GEP instructions, but we
245 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000246 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000247 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000248 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000249 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000250 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000251 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
252 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000253 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000254 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000255 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000256 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000257 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
258 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
259 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000260 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000261 } else {
262 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000263 }
Gabor Greife6642672010-07-09 16:51:20 +0000264 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000265 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000266 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000267 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000268 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000269 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000270 GS.HasNonInstructionUser = true;
271 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000272 return true;
273 }
Gabor Greife6642672010-07-09 16:51:20 +0000274 }
Chris Lattner079236d2004-02-25 21:34:36 +0000275
276 return false;
277}
278
Chris Lattner7b550cc2009-11-06 04:27:31 +0000279static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
Chris Lattner670c8892004-10-08 17:32:09 +0000280 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
281 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000282 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000283
Chris Lattner670c8892004-10-08 17:32:09 +0000284 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
285 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
286 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
287 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000288 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000289 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000290 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000291 if (StructType *STy = dyn_cast<StructType>(Agg->getType())) {
Chris Lattner670c8892004-10-08 17:32:09 +0000292 if (IdxV < STy->getNumElements())
Owen Andersona7235ea2009-07-31 20:28:14 +0000293 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000294 } else if (SequentialType *STy =
Chris Lattner670c8892004-10-08 17:32:09 +0000295 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000296 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000297 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000298 } else if (isa<UndefValue>(Agg)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000299 if (StructType *STy = dyn_cast<StructType>(Agg->getType())) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000300 if (IdxV < STy->getNumElements())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000301 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000302 } else if (SequentialType *STy =
Chris Lattner7a7ed022004-10-16 18:09:00 +0000303 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000304 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000305 }
Chris Lattner670c8892004-10-08 17:32:09 +0000306 }
307 return 0;
308}
Chris Lattner7a90b682004-10-07 04:16:33 +0000309
Chris Lattner7a90b682004-10-07 04:16:33 +0000310
Chris Lattnere47ba742004-10-06 20:57:02 +0000311/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
312/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000313/// quick scan over the use list to clean up the easy and obvious cruft. This
314/// returns true if it made a change.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000315static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000316 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000317 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
318 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000319
Chris Lattner7a90b682004-10-07 04:16:33 +0000320 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000321 if (Init) {
322 // Replace the load with the initializer.
323 LI->replaceAllUsesWith(Init);
324 LI->eraseFromParent();
325 Changed = true;
326 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000327 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000328 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000329 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000330 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000331 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
332 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000333 Constant *SubInit = 0;
334 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000335 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000336 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000337 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000338 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000339 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000340 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000341 }
342
343 if (CE->use_empty()) {
344 CE->destroyConstant();
345 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000346 }
347 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000348 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
349 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
350 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000351 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000352 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Chad Rosieraab8e282011-12-02 01:26:24 +0000353 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000354 ConstantExpr *CE =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000355 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000356 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000357 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000358 }
Chris Lattner7b550cc2009-11-06 04:27:31 +0000359 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000360
Chris Lattner031955d2004-10-10 16:43:46 +0000361 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000362 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000363 Changed = true;
364 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000365 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
366 if (MI->getRawDest() == V) {
367 MI->eraseFromParent();
368 Changed = true;
369 }
370
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000371 } else if (Constant *C = dyn_cast<Constant>(U)) {
372 // If we have a chain of dead constantexprs or other things dangling from
373 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000374 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000375 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000376 // This could have invalidated UI, start over from scratch.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000377 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000378 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000379 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000380 }
381 }
Chris Lattner031955d2004-10-10 16:43:46 +0000382 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000383}
384
Chris Lattner941db492008-01-14 02:09:12 +0000385/// isSafeSROAElementUse - Return true if the specified instruction is a safe
386/// user of a derived expression from a global that we want to SROA.
387static bool isSafeSROAElementUse(Value *V) {
388 // We might have a dead and dangling constant hanging off of here.
389 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000390 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000391
Chris Lattner941db492008-01-14 02:09:12 +0000392 Instruction *I = dyn_cast<Instruction>(V);
393 if (!I) return false;
394
395 // Loads are ok.
396 if (isa<LoadInst>(I)) return true;
397
398 // Stores *to* the pointer are ok.
399 if (StoreInst *SI = dyn_cast<StoreInst>(I))
400 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000401
Chris Lattner941db492008-01-14 02:09:12 +0000402 // Otherwise, it must be a GEP.
403 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
404 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000405
Chris Lattner941db492008-01-14 02:09:12 +0000406 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
407 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
408 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000409
Chris Lattner941db492008-01-14 02:09:12 +0000410 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
411 I != E; ++I)
412 if (!isSafeSROAElementUse(*I))
413 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000414 return true;
415}
416
Chris Lattner941db492008-01-14 02:09:12 +0000417
418/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
419/// Look at it and its uses and decide whether it is safe to SROA this global.
420///
421static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
422 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000423 if (!isa<GetElementPtrInst>(U) &&
424 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000425 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
426 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000427
Chris Lattner941db492008-01-14 02:09:12 +0000428 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
429 // don't like < 3 operand CE's, and we don't like non-constant integer
430 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
431 // value of C.
432 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
433 !cast<Constant>(U->getOperand(1))->isNullValue() ||
434 !isa<ConstantInt>(U->getOperand(2)))
435 return false;
436
437 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
438 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000439
Chris Lattner941db492008-01-14 02:09:12 +0000440 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000441 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000442 uint64_t NumElements = AT->getNumElements();
443 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000444
Chris Lattner941db492008-01-14 02:09:12 +0000445 // Check to make sure that index falls within the array. If not,
446 // something funny is going on, so we won't do the optimization.
447 //
448 if (Idx->getZExtValue() >= NumElements)
449 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000450
Chris Lattner941db492008-01-14 02:09:12 +0000451 // We cannot scalar repl this level of the array unless any array
452 // sub-indices are in-range constants. In particular, consider:
453 // A[0][i]. We cannot know that the user isn't doing invalid things like
454 // allowing i to index an out-of-range subscript that accesses A[1].
455 //
456 // Scalar replacing *just* the outer index of the array is probably not
457 // going to be a win anyway, so just give up.
458 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000459 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000460 ++GEPI) {
461 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000462 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000463 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000464 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000465 NumElements = SubVectorTy->getNumElements();
466 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000467 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000468 "Indexed GEP type is not array, vector, or struct!");
469 continue;
470 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000471
Chris Lattner941db492008-01-14 02:09:12 +0000472 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
473 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
474 return false;
475 }
476 }
477
478 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
479 if (!isSafeSROAElementUse(*I))
480 return false;
481 return true;
482}
483
484/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
485/// is safe for us to perform this transformation.
486///
487static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
488 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
489 UI != E; ++UI) {
490 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
491 return false;
492 }
493 return true;
494}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000495
Chris Lattner941db492008-01-14 02:09:12 +0000496
Chris Lattner670c8892004-10-08 17:32:09 +0000497/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
498/// variable. This opens the door for other optimizations by exposing the
499/// behavior of the program in a more fine-grained way. We have determined that
500/// this transformation is safe already. We return the first global variable we
501/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000502static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000503 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000504 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000505 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000506
Rafael Espindolabb46f522009-01-15 20:18:42 +0000507 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000508 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000509 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000510
Chris Lattner670c8892004-10-08 17:32:09 +0000511 std::vector<GlobalVariable*> NewGlobals;
512 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
513
Chris Lattner998182b2008-04-26 07:40:11 +0000514 // Get the alignment of the global, either explicit or target-specific.
515 unsigned StartAlignment = GV->getAlignment();
516 if (StartAlignment == 0)
517 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000518
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000519 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000520 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000521 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000522 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
523 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000524 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000525 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000526 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000527 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000528 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000529 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000530 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000531 Globals.insert(GV, NGV);
532 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000533
Chris Lattner998182b2008-04-26 07:40:11 +0000534 // Calculate the known alignment of the field. If the original aggregate
535 // had 256 byte alignment for example, something might depend on that:
536 // propagate info to each field.
537 uint64_t FieldOffset = Layout.getElementOffset(i);
538 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
539 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
540 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000541 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000542 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000543 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000544 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000545 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000546 else
Chris Lattner998182b2008-04-26 07:40:11 +0000547 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000548
Chris Lattner1f21ef12005-02-23 16:53:04 +0000549 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000550 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000551 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000552
Duncan Sands777d2302009-05-09 07:06:46 +0000553 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000554 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000555 for (unsigned i = 0, e = NumElements; i != e; ++i) {
556 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000557 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000558 assert(In && "Couldn't get element of initializer?");
559
Chris Lattner7b550cc2009-11-06 04:27:31 +0000560 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000561 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000562 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000563 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000564 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000565 Globals.insert(GV, NGV);
566 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000567
Chris Lattner998182b2008-04-26 07:40:11 +0000568 // Calculate the known alignment of the field. If the original aggregate
569 // had 256 byte alignment for example, something might depend on that:
570 // propagate info to each field.
571 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
572 if (NewAlign > EltAlign)
573 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000574 }
575 }
576
577 if (NewGlobals.empty())
578 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000579
David Greene3215b0e2010-01-05 01:28:05 +0000580 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000581
Chris Lattner7b550cc2009-11-06 04:27:31 +0000582 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000583
584 // Loop over all of the uses of the global, replacing the constantexpr geps,
585 // with smaller constantexpr geps or direct references.
586 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000587 User *GEP = GV->use_back();
588 assert(((isa<ConstantExpr>(GEP) &&
589 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
590 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000591
Chris Lattner670c8892004-10-08 17:32:09 +0000592 // Ignore the 1th operand, which has to be zero or else the program is quite
593 // broken (undefined). Get the 2nd operand, which is the structure or array
594 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000595 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000596 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
597
Chris Lattner30ba5692004-10-11 05:54:41 +0000598 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000599
600 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000601 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000602 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000603 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000604 Idxs.push_back(NullInt);
605 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
606 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000607 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000608 } else {
609 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000610 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000611 Idxs.push_back(NullInt);
612 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
613 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000614 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000615 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000616 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000617 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000618 GEP->replaceAllUsesWith(NewPtr);
619
620 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000621 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000622 else
623 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000624 }
625
Chris Lattnere40e2d12004-10-08 20:25:55 +0000626 // Delete the old global, now that it is dead.
627 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000628 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000629
630 // Loop over the new globals array deleting any globals that are obviously
631 // dead. This can arise due to scalarization of a structure or an array that
632 // has elements that are dead.
633 unsigned FirstGlobal = 0;
634 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
635 if (NewGlobals[i]->use_empty()) {
636 Globals.erase(NewGlobals[i]);
637 if (FirstGlobal == i) ++FirstGlobal;
638 }
639
640 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000641}
642
Chris Lattner9b34a612004-10-09 21:48:45 +0000643/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000644/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000645/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000646static bool AllUsesOfValueWillTrapIfNull(const Value *V,
647 SmallPtrSet<const PHINode*, 8> &PHIs) {
648 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000649 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000650 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000651
652 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000653 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000654 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000655 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000656 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000657 return false; // Storing the value.
658 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000659 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000660 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000661 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000662 return false; // Not calling the ptr
663 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000664 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000665 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000666 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000667 return false; // Not calling the ptr
668 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000669 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000670 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000671 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000672 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000673 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000674 // If we've already seen this phi node, ignore it, it has already been
675 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000676 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
677 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000678 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000679 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000680 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000681 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000682 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000683 return false;
684 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000685 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000686 return true;
687}
688
689/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000690/// from GV will trap if the loaded value is null. Note that this also permits
691/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000692static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
693 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000694 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000695 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000696
Gabor Greif6ce02b52010-04-06 19:24:18 +0000697 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
698 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000699 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000700 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000701 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000702 // Ignore stores to the global.
703 } else {
704 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000705 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000706 return false;
707 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000708 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000709 return true;
710}
711
Chris Lattner7b550cc2009-11-06 04:27:31 +0000712static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000713 bool Changed = false;
714 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
715 Instruction *I = cast<Instruction>(*UI++);
716 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
717 LI->setOperand(0, NewV);
718 Changed = true;
719 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
720 if (SI->getOperand(1) == V) {
721 SI->setOperand(1, NewV);
722 Changed = true;
723 }
724 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000725 CallSite CS(I);
726 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000727 // Calling through the pointer! Turn into a direct call, but be careful
728 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000729 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000730 Changed = true;
731 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000732 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
733 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000734 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000735 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000736 }
737
738 if (PassedAsArg) {
739 // Being passed as an argument also. Be careful to not invalidate UI!
740 UI = V->use_begin();
741 }
742 }
743 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
744 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000745 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000746 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000747 if (CI->use_empty()) {
748 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000749 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000750 }
751 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
752 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000753 SmallVector<Constant*, 8> Idxs;
754 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000755 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
756 i != e; ++i)
757 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000758 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000759 else
760 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000761 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000762 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000763 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000764 if (GEPI->use_empty()) {
765 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000766 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000767 }
768 }
769 }
770
771 return Changed;
772}
773
774
775/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
776/// value stored into it. If there are uses of the loaded value that would trap
777/// if the loaded value is dynamically null, then we know that they cannot be
778/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000779static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000780 bool Changed = false;
781
Chris Lattner92c6bd22009-01-14 00:12:58 +0000782 // Keep track of whether we are able to remove all the uses of the global
783 // other than the store that defines it.
784 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000785
Chris Lattner708148e2004-10-10 23:14:11 +0000786 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000787 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
788 User *GlobalUser = *GUI++;
789 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000790 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000791 // If we were able to delete all uses of the loads
792 if (LI->use_empty()) {
793 LI->eraseFromParent();
794 Changed = true;
795 } else {
796 AllNonStoreUsesGone = false;
797 }
798 } else if (isa<StoreInst>(GlobalUser)) {
799 // Ignore the store that stores "LV" to the global.
800 assert(GlobalUser->getOperand(1) == GV &&
801 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000802 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000803 AllNonStoreUsesGone = false;
804
805 // If we get here we could have other crazy uses that are transitively
806 // loaded.
807 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000808 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
809 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000810 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000811 }
Chris Lattner708148e2004-10-10 23:14:11 +0000812
813 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000814 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000815 ++NumGlobUses;
816 }
817
Chris Lattner708148e2004-10-10 23:14:11 +0000818 // If we nuked all of the loads, then none of the stores are needed either,
819 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000820 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000821 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000822 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000823 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000824 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000825 ++NumDeleted;
826 }
827 Changed = true;
828 }
829 return Changed;
830}
831
Chris Lattner30ba5692004-10-11 05:54:41 +0000832/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
833/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000834static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000835 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
836 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chad Rosieraab8e282011-12-02 01:26:24 +0000837 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000838 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000839 I->replaceAllUsesWith(NewC);
840
Chris Lattnerd514d822005-02-01 01:23:31 +0000841 // Advance UI to the next non-I use to avoid invalidating it!
842 // Instructions could multiply use V.
843 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000844 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000845 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000846 }
847}
848
849/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
850/// variable, and transforms the program as if it always contained the result of
851/// the specified malloc. Because it is always the result of the specified
852/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000853/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000854static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000855 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000856 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000857 ConstantInt *NElements,
Victor Hernandez83d63912009-09-18 22:35:49 +0000858 TargetData* TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000859 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000860
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000861 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +0000862 if (NElements->getZExtValue() == 1)
863 GlobalType = AllocTy;
864 else
865 // If we have an array allocation, the global variable is of an array.
866 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000867
868 // Create the new global variable. The contents of the malloc'd memory is
869 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000870 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000871 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000872 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000873 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000874 GV->getName()+".body",
875 GV,
876 GV->isThreadLocal());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000877
Chris Lattnera6874652010-02-25 22:33:52 +0000878 // If there are bitcast users of the malloc (which is typical, usually we have
879 // a malloc + bitcast) then replace them with uses of the new global. Update
880 // other users to use the global as well.
881 BitCastInst *TheBC = 0;
882 while (!CI->use_empty()) {
883 Instruction *User = cast<Instruction>(CI->use_back());
884 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
885 if (BCI->getType() == NewGV->getType()) {
886 BCI->replaceAllUsesWith(NewGV);
887 BCI->eraseFromParent();
888 } else {
889 BCI->setOperand(0, NewGV);
890 }
891 } else {
892 if (TheBC == 0)
893 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
894 User->replaceUsesOfWith(CI, TheBC);
895 }
896 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000897
Victor Hernandez83d63912009-09-18 22:35:49 +0000898 Constant *RepValue = NewGV;
899 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000900 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000901 GV->getType()->getElementType());
902
903 // If there is a comparison against null, we will insert a global bool to
904 // keep track of whether the global was initialized yet or not.
905 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000906 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000907 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000908 ConstantInt::getFalse(GV->getContext()),
909 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000910 bool InitBoolUsed = false;
911
912 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000913 while (!GV->use_empty()) {
914 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000915 // The global is initialized when the store to it occurs.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000916 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000917 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000918 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000919 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000920
Chris Lattnera6874652010-02-25 22:33:52 +0000921 LoadInst *LI = cast<LoadInst>(GV->use_back());
922 while (!LI->use_empty()) {
923 Use &LoadUse = LI->use_begin().getUse();
924 if (!isa<ICmpInst>(LoadUse.getUser())) {
925 LoadUse = RepValue;
926 continue;
927 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000928
Chris Lattnera6874652010-02-25 22:33:52 +0000929 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
930 // Replace the cmp X, 0 with a use of the bool value.
931 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
932 InitBoolUsed = true;
933 switch (ICI->getPredicate()) {
934 default: llvm_unreachable("Unknown ICmp Predicate!");
935 case ICmpInst::ICMP_ULT:
936 case ICmpInst::ICMP_SLT: // X < null -> always false
937 LV = ConstantInt::getFalse(GV->getContext());
938 break;
939 case ICmpInst::ICMP_ULE:
940 case ICmpInst::ICMP_SLE:
941 case ICmpInst::ICMP_EQ:
942 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
943 break;
944 case ICmpInst::ICMP_NE:
945 case ICmpInst::ICMP_UGE:
946 case ICmpInst::ICMP_SGE:
947 case ICmpInst::ICMP_UGT:
948 case ICmpInst::ICMP_SGT:
949 break; // no change.
950 }
951 ICI->replaceAllUsesWith(LV);
952 ICI->eraseFromParent();
953 }
954 LI->eraseFromParent();
955 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000956
957 // If the initialization boolean was used, insert it, otherwise delete it.
958 if (!InitBoolUsed) {
959 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000960 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000961 delete InitBool;
962 } else
963 GV->getParent()->getGlobalList().insert(GV, InitBool);
964
Chris Lattnera6874652010-02-25 22:33:52 +0000965 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000966 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000967 CI->eraseFromParent();
968
969 // To further other optimizations, loop over all users of NewGV and try to
970 // constant prop them. This will promote GEP instructions with constant
971 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000972 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000973 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000974 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000975
976 return NewGV;
977}
978
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000979/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
980/// to make sure that there are no complex uses of V. We permit simple things
981/// like dereferencing the pointer, but not storing through the address, unless
982/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000983static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
984 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000985 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000986 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000987 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000988 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000989
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000990 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
991 continue; // Fine, ignore.
992 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000993
Gabor Greif0b520db2010-04-06 18:58:22 +0000994 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000995 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
996 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000997 continue; // Otherwise, storing through it, or storing into GV... fine.
998 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000999
Chris Lattnera2fb2342010-04-10 18:19:22 +00001000 // Must index into the array and into the struct.
1001 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001002 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001003 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001004 continue;
1005 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001006
Gabor Greif0b520db2010-04-06 18:58:22 +00001007 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001008 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1009 // cycles.
1010 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001011 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1012 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001013 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001014 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001015
Gabor Greif0b520db2010-04-06 18:58:22 +00001016 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001017 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1018 return false;
1019 continue;
1020 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001021
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001022 return false;
1023 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001024 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001025}
1026
Chris Lattner86395032006-09-30 23:32:09 +00001027/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1028/// somewhere. Transform all uses of the allocation into loads from the
1029/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001030/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001031/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001032static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001033 GlobalVariable *GV) {
1034 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001035 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1036 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001037 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1038 // If this is the store of the allocation into the global, remove it.
1039 if (SI->getOperand(1) == GV) {
1040 SI->eraseFromParent();
1041 continue;
1042 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001043 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1044 // Insert the load in the corresponding predecessor, not right before the
1045 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001046 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001047 } else if (isa<BitCastInst>(U)) {
1048 // Must be bitcast between the malloc and store to initialize the global.
1049 ReplaceUsesOfMallocWithGlobal(U, GV);
1050 U->eraseFromParent();
1051 continue;
1052 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1053 // If this is a "GEP bitcast" and the user is a store to the global, then
1054 // just process it as a bitcast.
1055 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1056 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1057 if (SI->getOperand(1) == GV) {
1058 // Must be bitcast GEP between the malloc and store to initialize
1059 // the global.
1060 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1061 GEPI->eraseFromParent();
1062 continue;
1063 }
Chris Lattner86395032006-09-30 23:32:09 +00001064 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001065
Chris Lattner86395032006-09-30 23:32:09 +00001066 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001067 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001068 U->replaceUsesOfWith(Alloc, NL);
1069 }
1070}
1071
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001072/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1073/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1074/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001075static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001076 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1077 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001078 // We permit two users of the load: setcc comparing against the null
1079 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001080 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1081 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001082 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001083
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001084 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001085 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001086 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1087 return false;
1088 continue;
1089 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001090
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001091 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001092 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001093 // Must index into the array and into the struct.
1094 if (GEPI->getNumOperands() < 3)
1095 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001096
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001097 // Otherwise the GEP is ok.
1098 continue;
1099 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001100
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001101 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001102 if (!LoadUsingPHIsPerLoad.insert(PN))
1103 // This means some phi nodes are dependent on each other.
1104 // Avoid infinite looping!
1105 return false;
1106 if (!LoadUsingPHIs.insert(PN))
1107 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001108 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001109
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001110 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001111 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1112 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001113 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001114
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001115 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001116 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001117
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001118 // Otherwise we don't know what this is, not ok.
1119 return false;
1120 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001121
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001122 return true;
1123}
1124
1125
1126/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1127/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001128static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001129 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001130 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1131 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001132 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1133 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001134 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001135 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1136 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001137 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001138 LoadUsingPHIsPerLoad.clear();
1139 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001140
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001141 // If we reach here, we know that all uses of the loads and transitive uses
1142 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001143 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001144 // Check to verify that all operands of the PHIs are either PHIS that can be
1145 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001146 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1147 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001148 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001149 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1150 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001151
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001152 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001153 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001154
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001155 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001156 // One of the PHIs in our set is (optimistically) ok.
1157 if (LoadUsingPHIs.count(InPN))
1158 continue;
1159 return false;
1160 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001161
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001162 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001163 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001164 if (LI->getOperand(0) == GV)
1165 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001166
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001167 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001168
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001169 // Anything else is rejected.
1170 return false;
1171 }
1172 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001173
Chris Lattner86395032006-09-30 23:32:09 +00001174 return true;
1175}
1176
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001177static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1178 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001179 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001180 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001181
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001182 if (FieldNo >= FieldVals.size())
1183 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001184
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001185 // If we already have this value, just reuse the previously scalarized
1186 // version.
1187 if (Value *FieldVal = FieldVals[FieldNo])
1188 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001189
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001190 // Depending on what instruction this is, we have several cases.
1191 Value *Result;
1192 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1193 // This is a scalarized version of the load from the global. Just create
1194 // a new Load of the scalarized global.
1195 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1196 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001197 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001198 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001199 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1200 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1201 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001202 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001203 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001204
Jay Foadd8b4fb42011-03-30 11:19:20 +00001205 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001206 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001207 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001208 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001209 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001210 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1211 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001212 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001213 Result = 0;
1214 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001215
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001216 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001217}
1218
Chris Lattner330245e2007-09-13 17:29:05 +00001219/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1220/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001221static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001222 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001223 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001224 // If this is a comparison against null, handle it.
1225 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1226 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1227 // If we have a setcc of the loaded pointer, we can use a setcc of any
1228 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001229 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001230 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001231
Owen Anderson333c4002009-07-09 23:48:35 +00001232 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001233 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001234 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001235 SCI->replaceAllUsesWith(New);
1236 SCI->eraseFromParent();
1237 return;
1238 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001239
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001240 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001241 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1242 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1243 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001244
Chris Lattnera637a8b2007-09-13 18:00:31 +00001245 // Load the pointer for this field.
1246 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001247 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001248 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001249
Chris Lattnera637a8b2007-09-13 18:00:31 +00001250 // Create the new GEP idx vector.
1251 SmallVector<Value*, 8> GEPIdx;
1252 GEPIdx.push_back(GEPI->getOperand(1));
1253 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001254
Jay Foada9203102011-07-25 09:48:08 +00001255 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001256 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001257 GEPI->replaceAllUsesWith(NGEPI);
1258 GEPI->eraseFromParent();
1259 return;
1260 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001261
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001262 // Recursively transform the users of PHI nodes. This will lazily create the
1263 // PHIs that are needed for individual elements. Keep track of what PHIs we
1264 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1265 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1266 // already been seen first by another load, so its uses have already been
1267 // processed.
1268 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001269 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1270 std::vector<Value*>())).second)
1271 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001272
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001273 // If this is the first time we've seen this PHI, recursively process all
1274 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001275 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1276 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001277 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001278 }
Chris Lattner330245e2007-09-13 17:29:05 +00001279}
1280
Chris Lattner86395032006-09-30 23:32:09 +00001281/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1282/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1283/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001284/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001285static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001286 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001287 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001288 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001289 UI != E; ) {
1290 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001291 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001292 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001293
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001294 if (Load->use_empty()) {
1295 Load->eraseFromParent();
1296 InsertedScalarizedValues.erase(Load);
1297 }
Chris Lattner86395032006-09-30 23:32:09 +00001298}
1299
Victor Hernandez83d63912009-09-18 22:35:49 +00001300/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1301/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001302static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1303 Value* NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001304 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001305 Type* MAT = getMallocAllocatedType(CI);
1306 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001307
1308 // There is guaranteed to be at least one use of the malloc (storing
1309 // it into GV). If there are other uses, change them to be uses of
1310 // the global to simplify later code. This also deletes the store
1311 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001312 ReplaceUsesOfMallocWithGlobal(CI, GV);
1313
Victor Hernandez83d63912009-09-18 22:35:49 +00001314 // Okay, at this point, there are no users of the malloc. Insert N
1315 // new mallocs at the same place as CI, and N globals.
1316 std::vector<Value*> FieldGlobals;
1317 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001318
Victor Hernandez83d63912009-09-18 22:35:49 +00001319 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001320 Type *FieldTy = STy->getElementType(FieldNo);
1321 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001322
Victor Hernandez83d63912009-09-18 22:35:49 +00001323 GlobalVariable *NGV =
1324 new GlobalVariable(*GV->getParent(),
1325 PFieldTy, false, GlobalValue::InternalLinkage,
1326 Constant::getNullValue(PFieldTy),
1327 GV->getName() + ".f" + Twine(FieldNo), GV,
1328 GV->isThreadLocal());
1329 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001330
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001331 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001332 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001333 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001334 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001335 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1336 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001337 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001338 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001339 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001340 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001341 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001342
Victor Hernandez83d63912009-09-18 22:35:49 +00001343 // The tricky aspect of this transformation is handling the case when malloc
1344 // fails. In the original code, malloc failing would set the result pointer
1345 // of malloc to null. In this case, some mallocs could succeed and others
1346 // could fail. As such, we emit code that looks like this:
1347 // F0 = malloc(field0)
1348 // F1 = malloc(field1)
1349 // F2 = malloc(field2)
1350 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1351 // if (F0) { free(F0); F0 = 0; }
1352 // if (F1) { free(F1); F1 = 0; }
1353 // if (F2) { free(F2); F2 = 0; }
1354 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001355 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001356 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1357 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001358 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001359 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001360 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1361 Constant::getNullValue(FieldMallocs[i]->getType()),
1362 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001363 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001364 }
1365
1366 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001367 BasicBlock *OrigBB = CI->getParent();
1368 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001369
Victor Hernandez83d63912009-09-18 22:35:49 +00001370 // Create the block to check the first condition. Put all these blocks at the
1371 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001372 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1373 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001374 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001375
Victor Hernandez83d63912009-09-18 22:35:49 +00001376 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1377 // branch on RunningOr.
1378 OrigBB->getTerminator()->eraseFromParent();
1379 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001380
Victor Hernandez83d63912009-09-18 22:35:49 +00001381 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1382 // pointer, because some may be null while others are not.
1383 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1384 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001385 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001386 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001387 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001388 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001389 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001390 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001391 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1392 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001393
1394 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001395 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001396 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1397 FreeBlock);
1398 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001399
Victor Hernandez83d63912009-09-18 22:35:49 +00001400 NullPtrBlock = NextBlock;
1401 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001402
Victor Hernandez83d63912009-09-18 22:35:49 +00001403 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001404
1405 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001406 CI->eraseFromParent();
1407
1408 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1409 /// update all uses of the load, keep track of what scalarized loads are
1410 /// inserted for a given load.
1411 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1412 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001413
Victor Hernandez83d63912009-09-18 22:35:49 +00001414 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001415
Victor Hernandez83d63912009-09-18 22:35:49 +00001416 // Okay, the malloc site is completely handled. All of the uses of GV are now
1417 // loads, and all uses of those loads are simple. Rewrite them to use loads
1418 // of the per-field globals instead.
1419 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1420 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001421
Victor Hernandez83d63912009-09-18 22:35:49 +00001422 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001423 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001424 continue;
1425 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001426
Victor Hernandez83d63912009-09-18 22:35:49 +00001427 // Must be a store of null.
1428 StoreInst *SI = cast<StoreInst>(User);
1429 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1430 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001431
Victor Hernandez83d63912009-09-18 22:35:49 +00001432 // Insert a store of null into each global.
1433 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001434 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001435 Constant *Null = Constant::getNullValue(PT->getElementType());
1436 new StoreInst(Null, FieldGlobals[i], SI);
1437 }
1438 // Erase the original store.
1439 SI->eraseFromParent();
1440 }
1441
1442 // While we have PHIs that are interesting to rewrite, do it.
1443 while (!PHIsToRewrite.empty()) {
1444 PHINode *PN = PHIsToRewrite.back().first;
1445 unsigned FieldNo = PHIsToRewrite.back().second;
1446 PHIsToRewrite.pop_back();
1447 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1448 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1449
1450 // Add all the incoming values. This can materialize more phis.
1451 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1452 Value *InVal = PN->getIncomingValue(i);
1453 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001454 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001455 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1456 }
1457 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001458
Victor Hernandez83d63912009-09-18 22:35:49 +00001459 // Drop all inter-phi links and any loads that made it this far.
1460 for (DenseMap<Value*, std::vector<Value*> >::iterator
1461 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1462 I != E; ++I) {
1463 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1464 PN->dropAllReferences();
1465 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1466 LI->dropAllReferences();
1467 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001468
Victor Hernandez83d63912009-09-18 22:35:49 +00001469 // Delete all the phis and loads now that inter-references are dead.
1470 for (DenseMap<Value*, std::vector<Value*> >::iterator
1471 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1472 I != E; ++I) {
1473 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1474 PN->eraseFromParent();
1475 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1476 LI->eraseFromParent();
1477 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001478
Victor Hernandez83d63912009-09-18 22:35:49 +00001479 // The old global is now dead, remove it.
1480 GV->eraseFromParent();
1481
1482 ++NumHeapSRA;
1483 return cast<GlobalVariable>(FieldGlobals[0]);
1484}
1485
Chris Lattnere61d0a62008-12-15 21:02:25 +00001486/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1487/// pointer global variable with a single value stored it that is a malloc or
1488/// cast of malloc.
1489static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001490 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001491 Type *AllocTy,
Victor Hernandez83d63912009-09-18 22:35:49 +00001492 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001493 TargetData *TD) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001494 if (!TD)
1495 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001496
Victor Hernandez83d63912009-09-18 22:35:49 +00001497 // If this is a malloc of an abstract type, don't touch it.
1498 if (!AllocTy->isSized())
1499 return false;
1500
1501 // We can't optimize this global unless all uses of it are *known* to be
1502 // of the malloc value, not of the null initializer value (consider a use
1503 // that compares the global's value against zero to see if the malloc has
1504 // been reached). To do this, we check to see if all uses of the global
1505 // would trap if the global were null: this proves that they must all
1506 // happen after the malloc.
1507 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1508 return false;
1509
1510 // We can't optimize this if the malloc itself is used in a complex way,
1511 // for example, being stored into multiple globals. This allows the
1512 // malloc to be stored into the specified global, loaded setcc'd, and
1513 // GEP'd. These are all things we could transform to using the global
1514 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001515 SmallPtrSet<const PHINode*, 8> PHIs;
1516 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1517 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001518
1519 // If we have a global that is only initialized with a fixed size malloc,
1520 // transform the program to use global memory instead of malloc'd memory.
1521 // This eliminates dynamic allocation, avoids an indirection accessing the
1522 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001523 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001524 Value *NElems = getMallocArraySize(CI, TD, true);
1525 if (!NElems)
1526 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001527
Evan Cheng86cd4452010-04-14 20:52:55 +00001528 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1529 // Restrict this transformation to only working on small allocations
1530 // (2048 bytes currently), as we don't want to introduce a 16M global or
1531 // something.
1532 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1533 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1534 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001535 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001536
Evan Cheng86cd4452010-04-14 20:52:55 +00001537 // If the allocation is an array of structures, consider transforming this
1538 // into multiple malloc'd arrays, one for each field. This is basically
1539 // SRoA for malloc'd memory.
1540
1541 // If this is an allocation of a fixed size array of structs, analyze as a
1542 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001543 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001544 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001545 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001546
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001547 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001548 if (!AllocSTy)
1549 return false;
1550
1551 // This the structure has an unreasonable number of fields, leave it
1552 // alone.
1553 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1554 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1555
1556 // If this is a fixed size array, transform the Malloc to be an alloc of
1557 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001558 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1559 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001560 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1561 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1562 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1563 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1564 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001565 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001566 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1567 CI->replaceAllUsesWith(Cast);
1568 CI->eraseFromParent();
1569 CI = dyn_cast<BitCastInst>(Malloc) ?
1570 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1571 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001572
Evan Cheng86cd4452010-04-14 20:52:55 +00001573 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1574 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001575 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001576
Victor Hernandez83d63912009-09-18 22:35:49 +00001577 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001578}
Victor Hernandez83d63912009-09-18 22:35:49 +00001579
Chris Lattner9b34a612004-10-09 21:48:45 +00001580// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1581// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001582static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001583 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001584 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001585 // Ignore no-op GEPs and bitcasts.
1586 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001587
Chris Lattner708148e2004-10-10 23:14:11 +00001588 // If we are dealing with a pointer global that is initialized to null and
1589 // only has one (non-null) value stored into it, then we can optimize any
1590 // users of the loaded value (often calls and loads) that would trap if the
1591 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001592 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001593 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001594 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1595 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001596 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001597
Chris Lattner708148e2004-10-10 23:14:11 +00001598 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001599 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001600 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001601 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001602 Type* MallocType = getMallocAllocatedType(CI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001603 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001604 GVI, TD))
1605 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001606 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001607 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001608
Chris Lattner9b34a612004-10-09 21:48:45 +00001609 return false;
1610}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001611
Chris Lattner58e44f42008-01-14 01:17:44 +00001612/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1613/// two values ever stored into GV are its initializer and OtherVal. See if we
1614/// can shrink the global into a boolean and select between the two values
1615/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001616static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001617 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001618
Chris Lattner58e44f42008-01-14 01:17:44 +00001619 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001620 // an FP value, pointer or vector, don't do this optimization because a select
1621 // between them is very expensive and unlikely to lead to later
1622 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1623 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001624 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001625 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001626 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001627 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001628
Chris Lattner58e44f42008-01-14 01:17:44 +00001629 // Walk the use list of the global seeing if all the uses are load or store.
1630 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001631 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1632 User *U = *I;
1633 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001634 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001635 }
1636
David Greene3215b0e2010-01-05 01:28:05 +00001637 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001638
Chris Lattner96a86b22004-12-12 05:53:50 +00001639 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001640 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1641 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001642 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001643 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001644 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001645 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001646 GV->getParent()->getGlobalList().insert(GV, NewGV);
1647
1648 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001649 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001650 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001651
1652 // If initialized to zero and storing one into the global, we can use a cast
1653 // instead of a select to synthesize the desired value.
1654 bool IsOneZero = false;
1655 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001656 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001657
1658 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001659 Instruction *UI = cast<Instruction>(GV->use_back());
1660 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001661 // Change the store into a boolean store.
1662 bool StoringOther = SI->getOperand(0) == OtherVal;
1663 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001664 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001665 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001666 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1667 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001668 else {
1669 // Otherwise, we are storing a previously loaded copy. To do this,
1670 // change the copy from copying the original value to just copying the
1671 // bool.
1672 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1673
Gabor Greif9e4f2432010-06-24 14:42:01 +00001674 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001675 // select instruction. If not, it will be a load of the original
1676 // global.
1677 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1678 assert(LI->getOperand(0) == GV && "Not a copy!");
1679 // Insert a new load, to preserve the saved value.
1680 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1681 } else {
1682 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1683 "This is not a form that we understand!");
1684 StoreVal = StoredVal->getOperand(0);
1685 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1686 }
1687 }
1688 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001689 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001690 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001691 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001692 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001693 Value *NSI;
1694 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001695 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001696 else
Gabor Greif051a9502008-04-06 20:25:17 +00001697 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001698 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001699 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001700 }
1701 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001702 }
1703
1704 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001705 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001706}
1707
1708
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001709/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1710/// it if possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001711bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1712 Module::global_iterator &GVI) {
1713 if (!GV->hasLocalLinkage())
1714 return false;
1715
1716 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001717 GV->removeDeadConstantUsers();
1718
1719 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001720 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001721 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001722 ++NumDeleted;
1723 return true;
1724 }
1725
Rafael Espindolac4440e32011-01-19 16:32:21 +00001726 SmallPtrSet<const PHINode*, 16> PHIUsers;
1727 GlobalStatus GS;
1728
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001729 if (AnalyzeGlobal(GV, GS, PHIUsers))
1730 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001731
Rafael Espindolac4440e32011-01-19 16:32:21 +00001732 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1733 GV->setUnnamedAddr(true);
1734 NumUnnamed++;
1735 }
1736
1737 if (GV->isConstant() || !GV->hasInitializer())
1738 return false;
1739
1740 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1741}
1742
1743/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1744/// it if possible. If we make a change, return true.
1745bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1746 Module::global_iterator &GVI,
1747 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
1748 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001749 // If this is a first class global and has only one accessing function
1750 // and this function is main (which we know is not recursive we can make
1751 // this global a local variable) we replace the global with a local alloca
1752 // in this function.
1753 //
1754 // NOTE: It doesn't make sense to promote non single-value types since we
1755 // are just replacing static memory to stack memory.
1756 //
1757 // If the global is in different address space, don't bring it to stack.
1758 if (!GS.HasMultipleAccessingFunctions &&
1759 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1760 GV->getType()->getElementType()->isSingleValueType() &&
1761 GS.AccessingFunction->getName() == "main" &&
1762 GS.AccessingFunction->hasExternalLinkage() &&
1763 GV->getType()->getAddressSpace() == 0) {
1764 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1765 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1766 ->getEntryBlock().begin());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001767 Type* ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001768 // FIXME: Pass Global's alignment when globals have alignment
1769 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1770 if (!isa<UndefValue>(GV->getInitializer()))
1771 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001772
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001773 GV->replaceAllUsesWith(Alloca);
1774 GV->eraseFromParent();
1775 ++NumLocalized;
1776 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001777 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001778
1779 // If the global is never loaded (but may be stored to), it is dead.
1780 // Delete it now.
1781 if (!GS.isLoaded) {
1782 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1783
1784 // Delete any stores we can find to the global. We may not be able to
1785 // make it completely dead though.
1786 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1787
1788 // If the global is dead now, delete it.
1789 if (GV->use_empty()) {
1790 GV->eraseFromParent();
1791 ++NumDeleted;
1792 Changed = true;
1793 }
1794 return Changed;
1795
1796 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1797 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1798 GV->setConstant(true);
1799
1800 // Clean up any obviously simplifiable users now.
1801 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1802
1803 // If the global is dead now, just nuke it.
1804 if (GV->use_empty()) {
1805 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1806 << "all users and delete global!\n");
1807 GV->eraseFromParent();
1808 ++NumDeleted;
1809 }
1810
1811 ++NumMarked;
1812 return true;
1813 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1814 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1815 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1816 GVI = FirstNewGV; // Don't skip the newly produced globals!
1817 return true;
1818 }
1819 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1820 // If the initial value for the global was an undef value, and if only
1821 // one other value was stored into it, we can just change the
1822 // initializer to be the stored value, then delete all stores to the
1823 // global. This allows us to mark it constant.
1824 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1825 if (isa<UndefValue>(GV->getInitializer())) {
1826 // Change the initial value here.
1827 GV->setInitializer(SOVConstant);
1828
1829 // Clean up any obviously simplifiable users now.
1830 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1831
1832 if (GV->use_empty()) {
1833 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1834 << "simplify all users and delete global!\n");
1835 GV->eraseFromParent();
1836 ++NumDeleted;
1837 } else {
1838 GVI = GV;
1839 }
1840 ++NumSubstitute;
1841 return true;
1842 }
1843
1844 // Try to optimize globals based on the knowledge that only one value
1845 // (besides its initializer) is ever stored to the global.
1846 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1847 getAnalysisIfAvailable<TargetData>()))
1848 return true;
1849
1850 // Otherwise, if the global was not a boolean, we can shrink it to be a
1851 // boolean.
1852 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1853 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1854 ++NumShrunkToBool;
1855 return true;
1856 }
1857 }
1858
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001859 return false;
1860}
1861
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001862/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1863/// function, changing them to FastCC.
1864static void ChangeCalleesToFastCall(Function *F) {
1865 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001866 CallSite User(cast<Instruction>(*UI));
1867 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001868 }
1869}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001870
Devang Patel05988662008-09-25 21:00:45 +00001871static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001872 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001873 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001874 continue;
1875
Duncan Sands548448a2008-02-18 17:32:13 +00001876 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001877 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001878 }
1879
1880 return Attrs;
1881}
1882
1883static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001884 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001885 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001886 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001887 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001888 }
1889}
1890
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001891bool GlobalOpt::OptimizeFunctions(Module &M) {
1892 bool Changed = false;
1893 // Optimize functions.
1894 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1895 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001896 // Functions without names cannot be referenced outside this module.
1897 if (!F->hasName() && !F->isDeclaration())
1898 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001899 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00001900 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001901 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001902 Changed = true;
1903 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001904 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001905 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001906 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001907 // If this function has C calling conventions, is not a varargs
1908 // function, and is only called directly, promote it to use the Fast
1909 // calling convention.
1910 F->setCallingConv(CallingConv::Fast);
1911 ChangeCalleesToFastCall(F);
1912 ++NumFastCallFns;
1913 Changed = true;
1914 }
1915
Devang Patel05988662008-09-25 21:00:45 +00001916 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001917 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001918 // The function is not used by a trampoline intrinsic, so it is safe
1919 // to remove the 'nest' attribute.
1920 RemoveNestAttribute(F);
1921 ++NumNestRemoved;
1922 Changed = true;
1923 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001924 }
1925 }
1926 return Changed;
1927}
1928
1929bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1930 bool Changed = false;
1931 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1932 GVI != E; ) {
1933 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001934 // Global variables without names cannot be referenced outside this module.
1935 if (!GV->hasName() && !GV->isDeclaration())
1936 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001937 // Simplify the initializer.
1938 if (GV->hasInitializer())
1939 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohmanf860db22010-04-02 03:04:37 +00001940 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chad Rosieraab8e282011-12-02 01:26:24 +00001941 TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1942 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001943 if (New && New != CE)
1944 GV->setInitializer(New);
1945 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001946
1947 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001948 }
1949 return Changed;
1950}
1951
Nick Lewycky2c44a802011-04-08 07:30:21 +00001952/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001953/// initializers have an init priority of 65535.
1954GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001955 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1956 if (GV == 0) return 0;
1957
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001958 // Verify that the initializer is simple enough for us to handle. We are
1959 // only allowed to optimize the initializer if it is unique.
1960 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001961
1962 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1963 return GV;
1964 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00001965
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001966 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001967 if (isa<ConstantAggregateZero>(*i))
1968 continue;
1969 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001970 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1971 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001972
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001973 // Must have a function or null ptr.
1974 if (!isa<Function>(CS->getOperand(1)))
1975 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001976
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001977 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001978 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1979 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001980 return 0;
1981 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001982
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001983 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001984}
1985
Chris Lattnerdb973e62005-09-26 02:31:18 +00001986/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1987/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001988static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001989 if (GV->getInitializer()->isNullValue())
1990 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001991 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1992 std::vector<Function*> Result;
1993 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001994 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1995 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001996 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1997 }
1998 return Result;
1999}
2000
Chris Lattnerdb973e62005-09-26 02:31:18 +00002001/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2002/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002003static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002004 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002005 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002006 Constant *CSVals[2];
2007 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2008 CSVals[1] = 0;
2009
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002010 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002011 cast <StructType>(
2012 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002013
Chris Lattnerdb973e62005-09-26 02:31:18 +00002014 // Create the new init list.
2015 std::vector<Constant*> CAList;
2016 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002017 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002018 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002019 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002020 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002021 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002022 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002023 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002024 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002025 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002026 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002027 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002028 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002029
Chris Lattnerdb973e62005-09-26 02:31:18 +00002030 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002031 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002032 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002033
Chris Lattnerdb973e62005-09-26 02:31:18 +00002034 // If we didn't change the number of elements, don't create a new GV.
2035 if (CA->getType() == GCL->getInitializer()->getType()) {
2036 GCL->setInitializer(CA);
2037 return GCL;
2038 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002039
Chris Lattnerdb973e62005-09-26 02:31:18 +00002040 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002041 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002042 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002043 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002044 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002045 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002046
Chris Lattnerdb973e62005-09-26 02:31:18 +00002047 // Nuke the old list, replacing any uses with the new one.
2048 if (!GCL->use_empty()) {
2049 Constant *V = NGV;
2050 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002051 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002052 GCL->replaceAllUsesWith(V);
2053 }
2054 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002055
Chris Lattnerdb973e62005-09-26 02:31:18 +00002056 if (Ctors.size())
2057 return NGV;
2058 else
2059 return 0;
2060}
Chris Lattner79c11012005-09-26 04:44:35 +00002061
2062
Chris Lattner1945d582010-12-07 04:33:29 +00002063static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
Chris Lattner79c11012005-09-26 04:44:35 +00002064 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2065 Constant *R = ComputedValues[V];
2066 assert(R && "Reference to an uncomputed value!");
2067 return R;
2068}
2069
Chris Lattner1945d582010-12-07 04:33:29 +00002070static inline bool
2071isSimpleEnoughValueToCommit(Constant *C,
2072 SmallPtrSet<Constant*, 8> &SimpleConstants);
2073
2074
2075/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2076/// handled by the code generator. We don't want to generate something like:
2077/// void *X = &X/42;
2078/// because the code generator doesn't have a relocation that can handle that.
2079///
2080/// This function should be called if C was not found (but just got inserted)
2081/// in SimpleConstants to avoid having to rescan the same constants all the
2082/// time.
2083static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2084 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2085 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2086 // all supported.
2087 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2088 isa<GlobalValue>(C))
2089 return true;
2090
2091 // Aggregate values are safe if all their elements are.
2092 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2093 isa<ConstantVector>(C)) {
2094 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2095 Constant *Op = cast<Constant>(C->getOperand(i));
2096 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants))
2097 return false;
2098 }
2099 return true;
2100 }
2101
2102 // We don't know exactly what relocations are allowed in constant expressions,
2103 // so we allow &global+constantoffset, which is safe and uniformly supported
2104 // across targets.
2105 ConstantExpr *CE = cast<ConstantExpr>(C);
2106 switch (CE->getOpcode()) {
2107 case Instruction::BitCast:
2108 case Instruction::IntToPtr:
2109 case Instruction::PtrToInt:
2110 // These casts are always fine if the casted value is.
2111 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2112
2113 // GEP is fine if it is simple + constant offset.
2114 case Instruction::GetElementPtr:
2115 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2116 if (!isa<ConstantInt>(CE->getOperand(i)))
2117 return false;
2118 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2119
2120 case Instruction::Add:
2121 // We allow simple+cst.
2122 if (!isa<ConstantInt>(CE->getOperand(1)))
2123 return false;
2124 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2125 }
2126 return false;
2127}
2128
2129static inline bool
2130isSimpleEnoughValueToCommit(Constant *C,
2131 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2132 // If we already checked this constant, we win.
2133 if (!SimpleConstants.insert(C)) return true;
2134 // Check the constant.
2135 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants);
2136}
2137
2138
Chris Lattner79c11012005-09-26 04:44:35 +00002139/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002140/// enough for us to understand. In particular, if it is a cast to anything
2141/// other than from one pointer type to another pointer type, we punt.
2142/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002143/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002144static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002145 // Conservatively, avoid aggregate types. This is because we don't
2146 // want to worry about them partially overlapping other stores.
2147 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2148 return false;
2149
Dan Gohmanfd54a892009-09-07 22:31:26 +00002150 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002151 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002152 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002153 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002154
Owen Andersone95a32c2011-01-14 22:31:13 +00002155 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002156 // Handle a constantexpr gep.
2157 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002158 isa<GlobalVariable>(CE->getOperand(0)) &&
2159 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002160 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002161 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002162 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002163 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002164 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002165
Dan Gohman80bdc962009-09-07 22:44:55 +00002166 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002167 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002168 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002169
2170 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002171 // notional bounds of the corresponding static array types.
2172 if (!CE->isGEPWithNoNotionalOverIndexing())
2173 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002174
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002175 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002176
2177 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2178 // and we know how to evaluate it by moving the bitcast from the pointer
2179 // operand to the value operand.
2180 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002181 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002182 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2183 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002184 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002185 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002186 }
2187
Chris Lattner79c11012005-09-26 04:44:35 +00002188 return false;
2189}
2190
Chris Lattner798b4d52005-09-26 06:52:44 +00002191/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2192/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2193/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2194static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002195 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002196 // Base case of the recursion.
2197 if (OpNo == Addr->getNumOperands()) {
2198 assert(Val->getType() == Init->getType() && "Type mismatch!");
2199 return Val;
2200 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002201
Chris Lattnera0e9a242010-01-07 01:16:21 +00002202 std::vector<Constant*> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002203 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002204
2205 // Break up the constant into its elements.
2206 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002207 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2208 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002209 } else if (isa<ConstantAggregateZero>(Init)) {
2210 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002211 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002212 } else if (isa<UndefValue>(Init)) {
2213 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002214 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002215 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002216 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002217 " ConstantFoldLoadThroughGEPConstantExpr");
2218 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002219
Chris Lattner798b4d52005-09-26 06:52:44 +00002220 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002221 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2222 unsigned Idx = CU->getZExtValue();
2223 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002224 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002225
Chris Lattner798b4d52005-09-26 06:52:44 +00002226 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002227 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002228 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002229
2230 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002231 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002232
2233 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002234 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002235 NumElts = ATy->getNumElements();
2236 else
2237 NumElts = cast<VectorType>(InitTy)->getNumElements();
2238
2239 // Break up the array into elements.
2240 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2241 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2242 Elts.push_back(cast<Constant>(*i));
2243 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2244 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2245 Elts.push_back(cast<Constant>(*i));
2246 } else if (isa<ConstantAggregateZero>(Init)) {
2247 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
2248 } else {
2249 assert(isa<UndefValue>(Init) && "This code is out of sync with "
2250 " ConstantFoldLoadThroughGEPConstantExpr");
2251 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
2252 }
2253
2254 assert(CI->getZExtValue() < NumElts);
2255 Elts[CI->getZExtValue()] =
2256 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2257
2258 if (Init->getType()->isArrayTy())
2259 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2260 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002261}
2262
Chris Lattner79c11012005-09-26 04:44:35 +00002263/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2264/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002265static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002266 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2267 assert(GV->hasInitializer());
2268 GV->setInitializer(Val);
2269 return;
2270 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002271
Chris Lattner798b4d52005-09-26 06:52:44 +00002272 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2273 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002274 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002275}
2276
Chris Lattner562a0552005-09-26 05:16:34 +00002277/// ComputeLoadResult - Return the value that would be computed by a load from
2278/// P after the stores reflected by 'memory' have been performed. If we can't
2279/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002280static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002281 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002282 // If this memory location has been recently stored, use the stored value: it
2283 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002284 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002285 if (I != Memory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002286
Chris Lattner04de1cf2005-09-26 05:15:37 +00002287 // Access it.
2288 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002289 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002290 return GV->getInitializer();
2291 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002292 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002293
Chris Lattner798b4d52005-09-26 06:52:44 +00002294 // Handle a constantexpr getelementptr.
2295 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2296 if (CE->getOpcode() == Instruction::GetElementPtr &&
2297 isa<GlobalVariable>(CE->getOperand(0))) {
2298 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002299 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002300 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002301 }
2302
2303 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002304}
2305
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002306/// EvaluateFunction - Evaluate a call to function F, returning true if
2307/// successful, false if we can't evaluate it. ActualArgs contains the formal
2308/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002309static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002310 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002311 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002312 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner1945d582010-12-07 04:33:29 +00002313 std::vector<GlobalVariable*> &AllocaTmps,
2314 SmallPtrSet<Constant*, 8> &SimpleConstants,
Chad Rosier00737bd2011-12-01 21:29:16 +00002315 const TargetData *TD,
2316 const TargetLibraryInfo *TLI) {
Chris Lattnercd271422005-09-27 04:45:34 +00002317 // Check to see if this function is already executing (recursion). If so,
2318 // bail out. TODO: we might want to accept limited recursion.
2319 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2320 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002321
Chris Lattnercd271422005-09-27 04:45:34 +00002322 CallStack.push_back(F);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002323
Chris Lattner79c11012005-09-26 04:44:35 +00002324 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002325 DenseMap<Value*, Constant*> Values;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002326
Chris Lattnercd271422005-09-27 04:45:34 +00002327 // Initialize arguments to the incoming values specified.
2328 unsigned ArgNo = 0;
2329 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2330 ++AI, ++ArgNo)
2331 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002332
Chris Lattnercdf98be2005-09-26 04:57:38 +00002333 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2334 /// we can only evaluate any one basic block at most once. This set keeps
2335 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002336 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002337
Chris Lattner79c11012005-09-26 04:44:35 +00002338 // CurInst - The current instruction we're evaluating.
2339 BasicBlock::iterator CurInst = F->begin()->begin();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002340
Chris Lattner79c11012005-09-26 04:44:35 +00002341 // This is the main evaluation loop.
2342 while (1) {
2343 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002344
Chris Lattner79c11012005-09-26 04:44:35 +00002345 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002346 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002347 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002348 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002349 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002350 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002351
Chris Lattner79c11012005-09-26 04:44:35 +00002352 Constant *Val = getVal(Values, SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002353
2354 // If this might be too difficult for the backend to handle (e.g. the addr
2355 // of one global variable divided by another) then we can't commit it.
2356 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants))
2357 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002358
2359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2360 if (CE->getOpcode() == Instruction::BitCast) {
2361 // If we're evaluating a store through a bitcast, then we need
2362 // to pull the bitcast off the pointer type and push it onto the
2363 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002364 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002365
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002366 Type *NewTy=cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002367
Owen Anderson66f708f2011-01-16 04:33:33 +00002368 // In order to push the bitcast onto the stored value, a bitcast
2369 // from NewTy to Val's type must be legal. If it's not, we can try
2370 // introspecting NewTy to find a legal conversion.
2371 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2372 // If NewTy is a struct, we can convert the pointer to the struct
2373 // into a pointer to its first member.
2374 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002375 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002376 NewTy = STy->getTypeAtIndex(0U);
2377
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002378 IntegerType *IdxTy =IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002379 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2380 Constant * const IdxList[] = {IdxZero, IdxZero};
2381
Jay Foadb4263a62011-07-22 08:52:50 +00002382 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Owen Andersoncff6b372011-01-14 22:19:20 +00002383
Owen Anderson66f708f2011-01-16 04:33:33 +00002384 // If we can't improve the situation by introspecting NewTy,
2385 // we have to give up.
2386 } else {
2387 return 0;
2388 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002389 }
2390
Owen Anderson66f708f2011-01-16 04:33:33 +00002391 // If we found compatible types, go ahead and push the bitcast
2392 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002393 Val = ConstantExpr::getBitCast(Val, NewTy);
2394 }
2395
Chris Lattner79c11012005-09-26 04:44:35 +00002396 MutatedMemory[Ptr] = Val;
2397 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002398 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002399 getVal(Values, BO->getOperand(0)),
2400 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002401 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002402 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002403 getVal(Values, CI->getOperand(0)),
2404 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002405 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002406 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002407 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002408 CI->getType());
2409 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +00002410 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Eric Christopher551754c2010-04-16 23:37:20 +00002411 getVal(Values, SI->getOperand(1)),
2412 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002413 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2414 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002415 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002416 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2417 i != e; ++i)
2418 GEPOps.push_back(getVal(Values, *i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002419 InstResult =
2420 ConstantExpr::getGetElementPtr(P, GEPOps,
2421 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002422 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002423 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002424 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002425 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002426 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002427 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002428 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002429 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002430 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002431 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002432 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002433 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002434 InstResult = AllocaTmps.back();
Chris Lattnercd271422005-09-27 04:45:34 +00002435 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002436
2437 // Debug info can safely be ignored here.
2438 if (isa<DbgInfoIntrinsic>(CI)) {
2439 ++CurInst;
2440 continue;
2441 }
2442
Chris Lattner7cd580f2006-07-07 21:37:01 +00002443 // Cannot handle inline asm.
Gabor Greifa9b23132010-04-20 13:13:04 +00002444 if (isa<InlineAsm>(CI->getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002445
Nick Lewycky1f237b02011-05-29 18:41:56 +00002446 if (MemSetInst *MSI = dyn_cast<MemSetInst>(CI)) {
2447 if (MSI->isVolatile()) return false;
2448 Constant *Ptr = getVal(Values, MSI->getDest());
2449 Constant *Val = getVal(Values, MSI->getValue());
2450 Constant *DestVal = ComputeLoadResult(getVal(Values, Ptr),
2451 MutatedMemory);
Nick Lewyckybcb85082011-05-29 19:33:36 +00002452 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
Nick Lewycky1f237b02011-05-29 18:41:56 +00002453 // This memset is a no-op.
2454 ++CurInst;
2455 continue;
2456 }
2457 return false;
2458 }
2459
Chris Lattnercd271422005-09-27 04:45:34 +00002460 // Resolve function pointers.
Gabor Greifa3997812010-07-22 10:37:47 +00002461 Function *Callee = dyn_cast<Function>(getVal(Values,
2462 CI->getCalledValue()));
Chris Lattnercd271422005-09-27 04:45:34 +00002463 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002464
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002465 SmallVector<Constant*, 8> Formals;
Gabor Greif9e4f2432010-06-24 14:42:01 +00002466 CallSite CS(CI);
2467 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
Gabor Greif5e463212008-05-29 01:59:18 +00002468 i != e; ++i)
2469 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002470
Reid Spencer5cbf9852007-01-30 20:08:39 +00002471 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002472 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002473 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002474 InstResult = C;
2475 } else {
2476 return false;
2477 }
2478 } else {
2479 if (Callee->getFunctionType()->isVarArg())
2480 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002481
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002482 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002483 // Execute the call, if successful, use the return value.
2484 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
Chad Rosier00737bd2011-12-01 21:29:16 +00002485 MutatedMemory, AllocaTmps, SimpleConstants, TD,
2486 TLI))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002487 return false;
2488 InstResult = RetVal;
2489 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002490 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002491 BasicBlock *NewBB = 0;
2492 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2493 if (BI->isUnconditional()) {
2494 NewBB = BI->getSuccessor(0);
2495 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002496 ConstantInt *Cond =
2497 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002498 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002499
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002500 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002501 }
2502 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2503 ConstantInt *Val =
2504 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002505 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002506 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002507 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2508 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2509 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2510 NewBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002511 else
2512 return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002513 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002514 if (RI->getNumOperands())
2515 RetVal = getVal(Values, RI->getOperand(0));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002516
Chris Lattnercd271422005-09-27 04:45:34 +00002517 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002518 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002519 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002520 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002521 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002522 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002523
Chris Lattnercdf98be2005-09-26 04:57:38 +00002524 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002525 // executed the new block before. If so, we have a looping function,
2526 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002527 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002528 return false; // looped!
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002529
Chris Lattnercdf98be2005-09-26 04:57:38 +00002530 // Okay, we have never been in this block before. Check to see if there
2531 // are any PHI nodes. If so, evaluate them with information about where
2532 // we came from.
2533 BasicBlock *OldBB = CurInst->getParent();
2534 CurInst = NewBB->begin();
2535 PHINode *PN;
2536 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2537 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2538
2539 // Do NOT increment CurInst. We know that the terminator had no value.
2540 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002541 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002542 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002543 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002544 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002545
Chris Lattner1945d582010-12-07 04:33:29 +00002546 if (!CurInst->use_empty()) {
2547 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002548 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002549
Chris Lattner79c11012005-09-26 04:44:35 +00002550 Values[CurInst] = InstResult;
Chris Lattner1945d582010-12-07 04:33:29 +00002551 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002552
Chris Lattner79c11012005-09-26 04:44:35 +00002553 // Advance program counter.
2554 ++CurInst;
2555 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002556}
2557
2558/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2559/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002560static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2561 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002562 /// MutatedMemory - For each store we execute, we update this map. Loads
2563 /// check this to get the most up-to-date value. If evaluation is successful,
2564 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002565 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002566
2567 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2568 /// to represent its body. This vector is needed so we can delete the
2569 /// temporary globals when we are done.
2570 std::vector<GlobalVariable*> AllocaTmps;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002571
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002572 /// CallStack - This is used to detect recursion. In pathological situations
2573 /// we could hit exponential behavior, but at least there is nothing
2574 /// unbounded.
2575 std::vector<Function*> CallStack;
2576
Chris Lattner1945d582010-12-07 04:33:29 +00002577 /// SimpleConstants - These are constants we have checked and know to be
2578 /// simple enough to live in a static initializer of a global.
2579 SmallPtrSet<Constant*, 8> SimpleConstants;
2580
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002581 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002582 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002583 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2584 SmallVector<Constant*, 0>(), CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002585 MutatedMemory, AllocaTmps,
Chad Rosier00737bd2011-12-01 21:29:16 +00002586 SimpleConstants, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002587
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002588 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002589 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002590 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002591 << F->getName() << "' to " << MutatedMemory.size()
2592 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002593 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002594 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002595 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002596 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002597
Chris Lattnera22fdb02005-09-26 17:07:09 +00002598 // At this point, we are done interpreting. If we created any 'alloca'
2599 // temporaries, release them now.
2600 while (!AllocaTmps.empty()) {
2601 GlobalVariable *Tmp = AllocaTmps.back();
2602 AllocaTmps.pop_back();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002603
Chris Lattnera22fdb02005-09-26 17:07:09 +00002604 // If there are still users of the alloca, the program is doing something
2605 // silly, e.g. storing the address of the alloca somewhere and using it
2606 // later. Since this is undefined, we'll just make it be null.
2607 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002608 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002609 delete Tmp;
2610 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002611
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002612 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002613}
2614
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002615/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2616/// Return true if anything changed.
2617bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2618 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2619 bool MadeChange = false;
2620 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002621
Chris Lattner1945d582010-12-07 04:33:29 +00002622 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chad Rosier00737bd2011-12-01 21:29:16 +00002623 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
2624
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002625 // Loop over global ctors, optimizing them when we can.
2626 for (unsigned i = 0; i != Ctors.size(); ++i) {
2627 Function *F = Ctors[i];
2628 // Found a null terminator in the middle of the list, prune off the rest of
2629 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002630 if (F == 0) {
2631 if (i != Ctors.size()-1) {
2632 Ctors.resize(i+1);
2633 MadeChange = true;
2634 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002635 break;
2636 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002637
Chris Lattner79c11012005-09-26 04:44:35 +00002638 // We cannot simplify external ctor functions.
2639 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002640
Chris Lattner79c11012005-09-26 04:44:35 +00002641 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002642 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002643 Ctors.erase(Ctors.begin()+i);
2644 MadeChange = true;
2645 --i;
2646 ++NumCtorsEvaluated;
2647 continue;
2648 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002649 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002650
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002651 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002652
Chris Lattner7b550cc2009-11-06 04:27:31 +00002653 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002654 return true;
2655}
2656
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002657bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002658 bool Changed = false;
2659
Duncan Sands177d84e2009-01-07 20:01:06 +00002660 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002661 I != E;) {
2662 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002663 // Aliases without names cannot be referenced outside this module.
2664 if (!J->hasName() && !J->isDeclaration())
2665 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002666 // If the aliasee may change at link time, nothing can be done - bail out.
2667 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002668 continue;
2669
Duncan Sands4782b302009-02-15 09:56:08 +00002670 Constant *Aliasee = J->getAliasee();
2671 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002672 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002673 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2674
2675 // Make all users of the alias use the aliasee instead.
2676 if (!J->use_empty()) {
2677 J->replaceAllUsesWith(Aliasee);
2678 ++NumAliasesResolved;
2679 Changed = true;
2680 }
2681
Duncan Sands7a154cf2009-12-08 10:10:20 +00002682 // If the alias is externally visible, we may still be able to simplify it.
2683 if (!J->hasLocalLinkage()) {
2684 // If the aliasee has internal linkage, give it the name and linkage
2685 // of the alias, and delete the alias. This turns:
2686 // define internal ... @f(...)
2687 // @a = alias ... @f
2688 // into:
2689 // define ... @a(...)
2690 if (!Target->hasLocalLinkage())
2691 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002692
Duncan Sands7a154cf2009-12-08 10:10:20 +00002693 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002694 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002695 // and other attributes of the aliasee with those of the alias.
2696 if (!hasOneUse)
2697 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002698
Duncan Sands7a154cf2009-12-08 10:10:20 +00002699 // Give the aliasee the name, linkage and other attributes of the alias.
2700 Target->takeName(J);
2701 Target->setLinkage(J->getLinkage());
2702 Target->GlobalValue::copyAttributesFrom(J);
2703 }
Duncan Sands4782b302009-02-15 09:56:08 +00002704
2705 // Delete the alias.
2706 M.getAliasList().erase(J);
2707 ++NumAliasesRemoved;
2708 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002709 }
2710
2711 return Changed;
2712}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002713
Anders Carlssona201c4c2011-03-20 17:59:11 +00002714static Function *FindCXAAtExit(Module &M) {
2715 Function *Fn = M.getFunction("__cxa_atexit");
2716
2717 if (!Fn)
2718 return 0;
2719
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002720 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00002721
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002722 // Checking that the function has the right return type, the right number of
2723 // parameters and that they all have pointer types should be enough.
2724 if (!FTy->getReturnType()->isIntegerTy() ||
2725 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00002726 !FTy->getParamType(0)->isPointerTy() ||
2727 !FTy->getParamType(1)->isPointerTy() ||
2728 !FTy->getParamType(2)->isPointerTy())
2729 return 0;
2730
2731 return Fn;
2732}
2733
2734/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
2735/// destructor and can therefore be eliminated.
2736/// Note that we assume that other optimization passes have already simplified
2737/// the code so we only look for a function with a single basic block, where
2738/// the only allowed instructions are 'ret' or 'call' to empty C++ dtor.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002739static bool cxxDtorIsEmpty(const Function &Fn,
2740 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002741 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002742 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002743 if (Fn.isDeclaration())
2744 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00002745
2746 if (++Fn.begin() != Fn.end())
2747 return false;
2748
2749 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2750 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2751 I != E; ++I) {
2752 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00002753 // Ignore debug intrinsics.
2754 if (isa<DbgInfoIntrinsic>(CI))
2755 continue;
2756
Anders Carlssona201c4c2011-03-20 17:59:11 +00002757 const Function *CalledFn = CI->getCalledFunction();
2758
2759 if (!CalledFn)
2760 return false;
2761
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002762 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2763
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002764 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002765 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002766 return false;
2767
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002768 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002769 return false;
2770 } else if (isa<ReturnInst>(*I))
2771 return true;
2772 else
2773 return false;
2774 }
2775
2776 return false;
2777}
2778
2779bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2780 /// Itanium C++ ABI p3.3.5:
2781 ///
2782 /// After constructing a global (or local static) object, that will require
2783 /// destruction on exit, a termination function is registered as follows:
2784 ///
2785 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2786 ///
2787 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2788 /// call f(p) when DSO d is unloaded, before all such termination calls
2789 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002790 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002791
2792 // This pass will look for calls to __cxa_atexit where the function is trivial
2793 // and remove them.
2794 bool Changed = false;
2795
2796 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
2797 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002798 // We're only interested in calls. Theoretically, we could handle invoke
2799 // instructions as well, but neither llvm-gcc nor clang generate invokes
2800 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002801 CallInst *CI = dyn_cast<CallInst>(*I++);
2802 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002803 continue;
2804
Anders Carlssona201c4c2011-03-20 17:59:11 +00002805 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00002806 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00002807 if (!DtorFn)
2808 continue;
2809
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002810 SmallPtrSet<const Function *, 8> CalledFunctions;
2811 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002812 continue;
2813
2814 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002815 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
2816 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002817
Anders Carlssona201c4c2011-03-20 17:59:11 +00002818 ++NumCXXDtorsRemoved;
2819
2820 Changed |= true;
2821 }
2822
2823 return Changed;
2824}
2825
Chris Lattner7a90b682004-10-07 04:16:33 +00002826bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002827 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002828
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002829 // Try to find the llvm.globalctors list.
2830 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002831
Anders Carlssona201c4c2011-03-20 17:59:11 +00002832 Function *CXAAtExitFn = FindCXAAtExit(M);
2833
Chris Lattner7a90b682004-10-07 04:16:33 +00002834 bool LocalChange = true;
2835 while (LocalChange) {
2836 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002837
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002838 // Delete functions that are trivially dead, ccc -> fastcc
2839 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002840
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002841 // Optimize global_ctors list.
2842 if (GlobalCtors)
2843 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002844
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002845 // Optimize non-address-taken globals.
2846 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002847
2848 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002849 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002850
2851 // Try to remove trivial global destructors.
2852 if (CXAAtExitFn)
2853 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
2854
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002855 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002856 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002857
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002858 // TODO: Move all global ctors functions to the end of the module for code
2859 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002860
Chris Lattner079236d2004-02-25 21:34:36 +00002861 return Changed;
2862}