blob: 64cd515f673e53fac8202b75a2063f84eeff880a [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/ConstantFolding.h"
24#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000033#include "llvm/Pass.h"
Duncan Sands548448a2008-02-18 17:32:13 +000034#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000035#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000036#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000038#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000039#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000040#include "llvm/Target/TargetLibraryInfo.h"
Rafael Espindola4ef7eaf2013-07-25 03:23:25 +000041#include "llvm/Transforms/Utils/ModuleUtils.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000042#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000043using namespace llvm;
44
Chris Lattner86453c52006-12-19 22:09:18 +000045STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000046STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000047STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
48STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
49STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
50STATISTIC(NumDeleted , "Number of globals deleted");
51STATISTIC(NumFnDeleted , "Number of functions deleted");
52STATISTIC(NumGlobUses , "Number of global uses devirtualized");
53STATISTIC(NumLocalized , "Number of globals localized");
54STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
55STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
56STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000057STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000058STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
59STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000060STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000061
Chris Lattner86453c52006-12-19 22:09:18 +000062namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000063 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000064 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000065 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000066 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000067 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000068 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000069 GlobalOpt() : ModulePass(ID) {
70 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
71 }
Misha Brukmanfd939082005-04-21 23:48:37 +000072
Chris Lattnerb12914b2004-09-20 04:48:05 +000073 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000074
75 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000076 GlobalVariable *FindGlobalCtors(Module &M);
77 bool OptimizeFunctions(Module &M);
78 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000079 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000080 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000081 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
82 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
83 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
84 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000085 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewycky6a577f82012-02-12 01:13:18 +000086
Micah Villmow3574eca2012-10-08 16:38:25 +000087 DataLayout *TD;
Nick Lewycky6a577f82012-02-12 01:13:18 +000088 TargetLibraryInfo *TLI;
Chris Lattner079236d2004-02-25 21:34:36 +000089 };
Chris Lattner079236d2004-02-25 21:34:36 +000090}
91
Dan Gohman844731a2008-05-13 00:00:25 +000092char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000093INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
94 "Global Variable Optimizer", false, false)
95INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
96INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000097 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000098
Chris Lattner7a90b682004-10-07 04:16:33 +000099ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +0000100
Dan Gohman844731a2008-05-13 00:00:25 +0000101namespace {
102
Chris Lattner7a90b682004-10-07 04:16:33 +0000103/// GlobalStatus - As we analyze each global, keep track of some information
104/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000105/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000106struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000107 /// isCompared - True if the global's address is used in a comparison.
108 bool isCompared;
109
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000110 /// isLoaded - True if the global is ever loaded. If the global isn't ever
111 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000112 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000113
114 /// StoredType - Keep track of what stores to the global look like.
115 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000116 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000117 /// NotStored - There is no store to this global. It can thus be marked
118 /// constant.
119 NotStored,
120
121 /// isInitializerStored - This global is stored to, but the only thing
122 /// stored is the constant it was initialized with. This is only tracked
123 /// for scalar globals.
124 isInitializerStored,
125
126 /// isStoredOnce - This global is stored to, but only its initializer and
127 /// one other value is ever stored to it. If this global isStoredOnce, we
128 /// track the value stored to it in StoredOnceValue below. This is only
129 /// tracked for scalar globals.
130 isStoredOnce,
131
132 /// isStored - This global is stored to by multiple values or something else
133 /// that we cannot track.
134 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000135 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000136
137 /// StoredOnceValue - If only one value (besides the initializer constant) is
138 /// ever stored to this global, keep track of what value it is.
139 Value *StoredOnceValue;
140
Chris Lattner25de4e52006-11-01 18:03:33 +0000141 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
142 /// null/false. When the first accessing function is noticed, it is recorded.
143 /// When a second different accessing function is noticed,
144 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000145 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000146 bool HasMultipleAccessingFunctions;
147
Chris Lattner25de4e52006-11-01 18:03:33 +0000148 /// HasNonInstructionUser - Set to true if this global has a user that is not
149 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000150 bool HasNonInstructionUser;
151
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000152 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
153 AtomicOrdering Ordering;
154
Rafael Espindolac4440e32011-01-19 16:32:21 +0000155 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
156 StoredOnceValue(0), AccessingFunction(0),
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000157 HasMultipleAccessingFunctions(false),
Jakub Staszak5b4af8b2012-12-06 22:08:59 +0000158 HasNonInstructionUser(false), Ordering(NotAtomic) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000159};
Chris Lattnere47ba742004-10-06 20:57:02 +0000160
Dan Gohman844731a2008-05-13 00:00:25 +0000161}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000162
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000163/// StrongerOrdering - Return the stronger of the two ordering. If the two
164/// orderings are acquire and release, then return AcquireRelease.
165///
166static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
167 if (X == Acquire && Y == Release) return AcquireRelease;
168 if (Y == Acquire && X == Release) return AcquireRelease;
169 return (AtomicOrdering)std::max(X, Y);
170}
171
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000172/// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
Nick Lewyckybc384a12012-02-05 19:48:37 +0000173/// by constants itself. Note that constants cannot be cyclic, so this test is
174/// pretty easy to implement recursively.
175///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000176static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000177 if (isa<GlobalValue>(C)) return false;
178
Gabor Greif27236912010-04-07 18:59:26 +0000179 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
180 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000181 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000182 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000183 } else
184 return false;
185 return true;
186}
187
188
Chris Lattner7a90b682004-10-07 04:16:33 +0000189/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
190/// structure. If the global has its address taken, return true to indicate we
191/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000192///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000193static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
194 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000195 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000196 ++UI) {
197 const User *U = *UI;
198 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000199 GS.HasNonInstructionUser = true;
Jakub Staszak582088c2012-12-06 21:57:16 +0000200
Chris Lattnerd91ed102011-01-01 22:31:46 +0000201 // If the result of the constantexpr isn't pointer type, then we won't
202 // know to expect it in various places. Just reject early.
203 if (!isa<PointerType>(CE->getType())) return true;
Jakub Staszak582088c2012-12-06 21:57:16 +0000204
Chris Lattner7a90b682004-10-07 04:16:33 +0000205 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000206 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000207 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000208 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000209 if (GS.AccessingFunction == 0)
210 GS.AccessingFunction = F;
211 else if (GS.AccessingFunction != F)
212 GS.HasMultipleAccessingFunctions = true;
213 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000214 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000215 GS.isLoaded = true;
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000216 // Don't hack on volatile loads.
217 if (LI->isVolatile()) return true;
218 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000219 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000220 // Don't allow a store OF the address, only stores TO the address.
221 if (SI->getOperand(0) == V) return true;
222
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000223 // Don't hack on volatile stores.
224 if (SI->isVolatile()) return true;
Hans Wennborg18398582012-11-15 11:40:00 +0000225
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000226 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000227
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000228 // If this is a direct store to the global (i.e., the global is a scalar
229 // value, not an aggregate), keep more specific information about
230 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000231 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000232 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
233 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000234 Value *StoredVal = SI->getOperand(0);
Hans Wennborg18398582012-11-15 11:40:00 +0000235
236 if (Constant *C = dyn_cast<Constant>(StoredVal)) {
237 if (C->isThreadDependent()) {
238 // The stored value changes between threads; don't track it.
239 return true;
240 }
241 }
242
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000243 if (StoredVal == GV->getInitializer()) {
244 if (GS.StoredType < GlobalStatus::isInitializerStored)
245 GS.StoredType = GlobalStatus::isInitializerStored;
246 } else if (isa<LoadInst>(StoredVal) &&
247 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000248 if (GS.StoredType < GlobalStatus::isInitializerStored)
249 GS.StoredType = GlobalStatus::isInitializerStored;
250 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
251 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000252 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000253 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000254 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000255 // noop.
256 } else {
257 GS.StoredType = GlobalStatus::isStored;
258 }
259 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000260 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000261 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000262 }
Duncan Sandsb2fe7f12012-07-02 18:55:39 +0000263 } else if (isa<BitCastInst>(I)) {
264 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000265 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000266 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000267 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000268 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000269 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000270 // PHI nodes we can check just like select or GEP instructions, but we
271 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000272 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000273 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000274 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000275 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000276 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
277 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000278 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000279 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000280 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000281 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000282 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
283 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
284 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000285 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000286 } else {
287 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000288 }
Gabor Greife6642672010-07-09 16:51:20 +0000289 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000290 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000291 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000292 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000293 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000294 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000295 GS.HasNonInstructionUser = true;
296 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000297 return true;
298 }
Gabor Greife6642672010-07-09 16:51:20 +0000299 }
Chris Lattner079236d2004-02-25 21:34:36 +0000300
301 return false;
302}
303
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000304/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
305/// as a root? If so, we might not really want to eliminate the stores to it.
306static bool isLeakCheckerRoot(GlobalVariable *GV) {
307 // A global variable is a root if it is a pointer, or could plausibly contain
308 // a pointer. There are two challenges; one is that we could have a struct
309 // the has an inner member which is a pointer. We recurse through the type to
310 // detect these (up to a point). The other is that we may actually be a union
311 // of a pointer and another type, and so our LLVM type is an integer which
312 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
313 // potentially contained here.
314
315 if (GV->hasPrivateLinkage())
316 return false;
317
318 SmallVector<Type *, 4> Types;
319 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
320
321 unsigned Limit = 20;
322 do {
323 Type *Ty = Types.pop_back_val();
324 switch (Ty->getTypeID()) {
325 default: break;
326 case Type::PointerTyID: return true;
327 case Type::ArrayTyID:
328 case Type::VectorTyID: {
329 SequentialType *STy = cast<SequentialType>(Ty);
330 Types.push_back(STy->getElementType());
331 break;
332 }
333 case Type::StructTyID: {
334 StructType *STy = cast<StructType>(Ty);
335 if (STy->isOpaque()) return true;
336 for (StructType::element_iterator I = STy->element_begin(),
337 E = STy->element_end(); I != E; ++I) {
338 Type *InnerTy = *I;
339 if (isa<PointerType>(InnerTy)) return true;
340 if (isa<CompositeType>(InnerTy))
341 Types.push_back(InnerTy);
342 }
343 break;
344 }
345 }
346 if (--Limit == 0) return true;
347 } while (!Types.empty());
348 return false;
349}
350
351/// Given a value that is stored to a global but never read, determine whether
352/// it's safe to remove the store and the chain of computation that feeds the
353/// store.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000354static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000355 do {
356 if (isa<Constant>(V))
357 return true;
358 if (!V->hasOneUse())
359 return false;
Nick Lewyckyb8cd66b2012-07-25 21:19:40 +0000360 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
361 isa<GlobalValue>(V))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000362 return false;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000363 if (isAllocationFn(V, TLI))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000364 return true;
365
366 Instruction *I = cast<Instruction>(V);
367 if (I->mayHaveSideEffects())
368 return false;
369 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
370 if (!GEP->hasAllConstantIndices())
371 return false;
372 } else if (I->getNumOperands() != 1) {
373 return false;
374 }
375
376 V = I->getOperand(0);
377 } while (1);
378}
379
380/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
381/// of the global and clean up any that obviously don't assign the global a
382/// value that isn't dynamically allocated.
383///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000384static bool CleanupPointerRootUsers(GlobalVariable *GV,
385 const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000386 // A brief explanation of leak checkers. The goal is to find bugs where
387 // pointers are forgotten, causing an accumulating growth in memory
388 // usage over time. The common strategy for leak checkers is to whitelist the
389 // memory pointed to by globals at exit. This is popular because it also
390 // solves another problem where the main thread of a C++ program may shut down
391 // before other threads that are still expecting to use those globals. To
392 // handle that case, we expect the program may create a singleton and never
393 // destroy it.
394
395 bool Changed = false;
396
397 // If Dead[n].first is the only use of a malloc result, we can delete its
398 // chain of computation and the store to the global in Dead[n].second.
399 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
400
401 // Constants can't be pointers to dynamically allocated memory.
402 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
403 UI != E;) {
404 User *U = *UI++;
405 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
406 Value *V = SI->getValueOperand();
407 if (isa<Constant>(V)) {
408 Changed = true;
409 SI->eraseFromParent();
410 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
411 if (I->hasOneUse())
412 Dead.push_back(std::make_pair(I, SI));
413 }
414 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
415 if (isa<Constant>(MSI->getValue())) {
416 Changed = true;
417 MSI->eraseFromParent();
418 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
419 if (I->hasOneUse())
420 Dead.push_back(std::make_pair(I, MSI));
421 }
422 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
423 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
424 if (MemSrc && MemSrc->isConstant()) {
425 Changed = true;
426 MTI->eraseFromParent();
427 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
428 if (I->hasOneUse())
429 Dead.push_back(std::make_pair(I, MTI));
430 }
431 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
432 if (CE->use_empty()) {
433 CE->destroyConstant();
434 Changed = true;
435 }
436 } else if (Constant *C = dyn_cast<Constant>(U)) {
437 if (SafeToDestroyConstant(C)) {
438 C->destroyConstant();
439 // This could have invalidated UI, start over from scratch.
440 Dead.clear();
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000441 CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000442 return true;
443 }
444 }
445 }
446
447 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000448 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000449 Dead[i].second->eraseFromParent();
450 Instruction *I = Dead[i].first;
451 do {
Michael Gottesmandcf66952013-01-11 23:08:52 +0000452 if (isAllocationFn(I, TLI))
453 break;
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000454 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
455 if (!J)
456 break;
457 I->eraseFromParent();
458 I = J;
Nick Lewycky952f5d52012-07-24 21:33:00 +0000459 } while (1);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000460 I->eraseFromParent();
461 }
462 }
463
464 return Changed;
465}
466
Chris Lattnere47ba742004-10-06 20:57:02 +0000467/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
468/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000469/// quick scan over the use list to clean up the easy and obvious cruft. This
470/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000471static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Micah Villmow3574eca2012-10-08 16:38:25 +0000472 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000473 bool Changed = false;
Bill Wendling2b792362013-04-02 08:16:45 +0000474 SmallVector<User*, 8> WorkList(V->use_begin(), V->use_end());
475 while (!WorkList.empty()) {
476 User *U = WorkList.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000477
Chris Lattner7a90b682004-10-07 04:16:33 +0000478 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000479 if (Init) {
480 // Replace the load with the initializer.
481 LI->replaceAllUsesWith(Init);
482 LI->eraseFromParent();
483 Changed = true;
484 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000485 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000486 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000487 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000488 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000489 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
490 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000491 Constant *SubInit = 0;
492 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000493 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000494 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000495 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000496 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000497 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000498 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000499 }
500
501 if (CE->use_empty()) {
502 CE->destroyConstant();
503 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000504 }
505 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000506 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
507 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
508 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000509 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000510 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000511 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000512 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000513 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000514 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000515
516 // If the initializer is an all-null value and we have an inbounds GEP,
517 // we already know what the result of any load from that GEP is.
518 // TODO: Handle splats.
519 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
520 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000521 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000522 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000523
Chris Lattner031955d2004-10-10 16:43:46 +0000524 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000525 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000526 Changed = true;
527 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000528 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
529 if (MI->getRawDest() == V) {
530 MI->eraseFromParent();
531 Changed = true;
532 }
533
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000534 } else if (Constant *C = dyn_cast<Constant>(U)) {
535 // If we have a chain of dead constantexprs or other things dangling from
536 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000537 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000538 C->destroyConstant();
Nick Lewycky6a577f82012-02-12 01:13:18 +0000539 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000540 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000541 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000542 }
543 }
Chris Lattner031955d2004-10-10 16:43:46 +0000544 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000545}
546
Chris Lattner941db492008-01-14 02:09:12 +0000547/// isSafeSROAElementUse - Return true if the specified instruction is a safe
548/// user of a derived expression from a global that we want to SROA.
549static bool isSafeSROAElementUse(Value *V) {
550 // We might have a dead and dangling constant hanging off of here.
551 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000552 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000553
Chris Lattner941db492008-01-14 02:09:12 +0000554 Instruction *I = dyn_cast<Instruction>(V);
555 if (!I) return false;
556
557 // Loads are ok.
558 if (isa<LoadInst>(I)) return true;
559
560 // Stores *to* the pointer are ok.
561 if (StoreInst *SI = dyn_cast<StoreInst>(I))
562 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000563
Chris Lattner941db492008-01-14 02:09:12 +0000564 // Otherwise, it must be a GEP.
565 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
566 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000567
Chris Lattner941db492008-01-14 02:09:12 +0000568 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
569 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
570 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000571
Chris Lattner941db492008-01-14 02:09:12 +0000572 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
573 I != E; ++I)
574 if (!isSafeSROAElementUse(*I))
575 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000576 return true;
577}
578
Chris Lattner941db492008-01-14 02:09:12 +0000579
580/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
581/// Look at it and its uses and decide whether it is safe to SROA this global.
582///
583static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
584 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000585 if (!isa<GetElementPtrInst>(U) &&
586 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000587 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
588 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000589
Chris Lattner941db492008-01-14 02:09:12 +0000590 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
591 // don't like < 3 operand CE's, and we don't like non-constant integer
592 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
593 // value of C.
594 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
595 !cast<Constant>(U->getOperand(1))->isNullValue() ||
596 !isa<ConstantInt>(U->getOperand(2)))
597 return false;
598
599 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
600 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000601
Chris Lattner941db492008-01-14 02:09:12 +0000602 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000603 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000604 uint64_t NumElements = AT->getNumElements();
605 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000606
Chris Lattner941db492008-01-14 02:09:12 +0000607 // Check to make sure that index falls within the array. If not,
608 // something funny is going on, so we won't do the optimization.
609 //
610 if (Idx->getZExtValue() >= NumElements)
611 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000612
Chris Lattner941db492008-01-14 02:09:12 +0000613 // We cannot scalar repl this level of the array unless any array
614 // sub-indices are in-range constants. In particular, consider:
615 // A[0][i]. We cannot know that the user isn't doing invalid things like
616 // allowing i to index an out-of-range subscript that accesses A[1].
617 //
618 // Scalar replacing *just* the outer index of the array is probably not
619 // going to be a win anyway, so just give up.
620 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000621 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000622 ++GEPI) {
623 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000624 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000625 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000626 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000627 NumElements = SubVectorTy->getNumElements();
628 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000629 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000630 "Indexed GEP type is not array, vector, or struct!");
631 continue;
632 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000633
Chris Lattner941db492008-01-14 02:09:12 +0000634 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
635 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
636 return false;
637 }
638 }
639
640 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
641 if (!isSafeSROAElementUse(*I))
642 return false;
643 return true;
644}
645
646/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
647/// is safe for us to perform this transformation.
648///
649static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
650 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
651 UI != E; ++UI) {
652 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
653 return false;
654 }
655 return true;
656}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000657
Chris Lattner941db492008-01-14 02:09:12 +0000658
Chris Lattner670c8892004-10-08 17:32:09 +0000659/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
660/// variable. This opens the door for other optimizations by exposing the
661/// behavior of the program in a more fine-grained way. We have determined that
662/// this transformation is safe already. We return the first global variable we
663/// insert so that the caller can reprocess it.
Micah Villmow3574eca2012-10-08 16:38:25 +0000664static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000665 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000666 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000667 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000668
Rafael Espindolabb46f522009-01-15 20:18:42 +0000669 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000670 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000671 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000672
Chris Lattner670c8892004-10-08 17:32:09 +0000673 std::vector<GlobalVariable*> NewGlobals;
674 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
675
Chris Lattner998182b2008-04-26 07:40:11 +0000676 // Get the alignment of the global, either explicit or target-specific.
677 unsigned StartAlignment = GV->getAlignment();
678 if (StartAlignment == 0)
679 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000680
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000681 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000682 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000683 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000684 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000685 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000686 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000687 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000688 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000689 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000690 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000691 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000692 Globals.insert(GV, NGV);
693 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000694
Chris Lattner998182b2008-04-26 07:40:11 +0000695 // Calculate the known alignment of the field. If the original aggregate
696 // had 256 byte alignment for example, something might depend on that:
697 // propagate info to each field.
698 uint64_t FieldOffset = Layout.getElementOffset(i);
699 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
700 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
701 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000702 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000703 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000704 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000705 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000706 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000707 else
Chris Lattner998182b2008-04-26 07:40:11 +0000708 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000709
Chris Lattner1f21ef12005-02-23 16:53:04 +0000710 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000711 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000712 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000713
Duncan Sands777d2302009-05-09 07:06:46 +0000714 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000715 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000716 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000717 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000718 assert(In && "Couldn't get element of initializer?");
719
Chris Lattner7b550cc2009-11-06 04:27:31 +0000720 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000721 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000722 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000723 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000724 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000725 Globals.insert(GV, NGV);
726 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000727
Chris Lattner998182b2008-04-26 07:40:11 +0000728 // Calculate the known alignment of the field. If the original aggregate
729 // had 256 byte alignment for example, something might depend on that:
730 // propagate info to each field.
731 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
732 if (NewAlign > EltAlign)
733 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000734 }
735 }
736
737 if (NewGlobals.empty())
738 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000739
David Greene3215b0e2010-01-05 01:28:05 +0000740 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000741
Chris Lattner7b550cc2009-11-06 04:27:31 +0000742 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000743
744 // Loop over all of the uses of the global, replacing the constantexpr geps,
745 // with smaller constantexpr geps or direct references.
746 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000747 User *GEP = GV->use_back();
748 assert(((isa<ConstantExpr>(GEP) &&
749 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
750 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000751
Chris Lattner670c8892004-10-08 17:32:09 +0000752 // Ignore the 1th operand, which has to be zero or else the program is quite
753 // broken (undefined). Get the 2nd operand, which is the structure or array
754 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000755 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000756 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
757
Chris Lattner30ba5692004-10-11 05:54:41 +0000758 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000759
760 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000761 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000762 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000763 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000764 Idxs.push_back(NullInt);
765 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
766 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000767 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000768 } else {
769 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000770 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000771 Idxs.push_back(NullInt);
772 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
773 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000774 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000775 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000776 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000777 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000778 GEP->replaceAllUsesWith(NewPtr);
779
780 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000781 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000782 else
783 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000784 }
785
Chris Lattnere40e2d12004-10-08 20:25:55 +0000786 // Delete the old global, now that it is dead.
787 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000788 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000789
790 // Loop over the new globals array deleting any globals that are obviously
791 // dead. This can arise due to scalarization of a structure or an array that
792 // has elements that are dead.
793 unsigned FirstGlobal = 0;
794 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
795 if (NewGlobals[i]->use_empty()) {
796 Globals.erase(NewGlobals[i]);
797 if (FirstGlobal == i) ++FirstGlobal;
798 }
799
800 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000801}
802
Chris Lattner9b34a612004-10-09 21:48:45 +0000803/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000804/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000805/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000806static bool AllUsesOfValueWillTrapIfNull(const Value *V,
807 SmallPtrSet<const PHINode*, 8> &PHIs) {
808 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000809 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000810 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000811
812 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000813 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000814 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000815 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000816 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000817 return false; // Storing the value.
818 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000819 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000820 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000821 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000822 return false; // Not calling the ptr
823 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000824 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000825 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000826 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000827 return false; // Not calling the ptr
828 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000829 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000830 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000831 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000832 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000833 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000834 // If we've already seen this phi node, ignore it, it has already been
835 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000836 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
837 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000838 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000839 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000840 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000841 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000842 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000843 return false;
844 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000845 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000846 return true;
847}
848
849/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000850/// from GV will trap if the loaded value is null. Note that this also permits
851/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000852static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
853 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000854 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000855 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000856
Gabor Greif6ce02b52010-04-06 19:24:18 +0000857 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
858 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000859 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000860 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000861 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000862 // Ignore stores to the global.
863 } else {
864 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000865 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000866 return false;
867 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000868 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000869 return true;
870}
871
Chris Lattner7b550cc2009-11-06 04:27:31 +0000872static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000873 bool Changed = false;
874 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
875 Instruction *I = cast<Instruction>(*UI++);
876 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
877 LI->setOperand(0, NewV);
878 Changed = true;
879 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
880 if (SI->getOperand(1) == V) {
881 SI->setOperand(1, NewV);
882 Changed = true;
883 }
884 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000885 CallSite CS(I);
886 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000887 // Calling through the pointer! Turn into a direct call, but be careful
888 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000889 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000890 Changed = true;
891 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000892 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
893 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000894 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000895 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000896 }
897
898 if (PassedAsArg) {
899 // Being passed as an argument also. Be careful to not invalidate UI!
900 UI = V->use_begin();
901 }
902 }
903 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
904 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000905 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000906 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000907 if (CI->use_empty()) {
908 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000909 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000910 }
911 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
912 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000913 SmallVector<Constant*, 8> Idxs;
914 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000915 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
916 i != e; ++i)
917 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000918 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000919 else
920 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000921 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000922 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000923 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000924 if (GEPI->use_empty()) {
925 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000926 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000927 }
928 }
929 }
930
931 return Changed;
932}
933
934
935/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
936/// value stored into it. If there are uses of the loaded value that would trap
937/// if the loaded value is dynamically null, then we know that they cannot be
938/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000939static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Micah Villmow3574eca2012-10-08 16:38:25 +0000940 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000941 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000942 bool Changed = false;
943
Chris Lattner92c6bd22009-01-14 00:12:58 +0000944 // Keep track of whether we are able to remove all the uses of the global
945 // other than the store that defines it.
946 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000947
Chris Lattner708148e2004-10-10 23:14:11 +0000948 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000949 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
950 User *GlobalUser = *GUI++;
951 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000952 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000953 // If we were able to delete all uses of the loads
954 if (LI->use_empty()) {
955 LI->eraseFromParent();
956 Changed = true;
957 } else {
958 AllNonStoreUsesGone = false;
959 }
960 } else if (isa<StoreInst>(GlobalUser)) {
961 // Ignore the store that stores "LV" to the global.
962 assert(GlobalUser->getOperand(1) == GV &&
963 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000964 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000965 AllNonStoreUsesGone = false;
966
967 // If we get here we could have other crazy uses that are transitively
968 // loaded.
969 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramerab164232012-09-28 10:01:27 +0000970 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
971 isa<BitCastInst>(GlobalUser) ||
972 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner98a42b22011-05-22 07:15:13 +0000973 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000974 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000975 }
Chris Lattner708148e2004-10-10 23:14:11 +0000976
977 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000978 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000979 ++NumGlobUses;
980 }
981
Chris Lattner708148e2004-10-10 23:14:11 +0000982 // If we nuked all of the loads, then none of the stores are needed either,
983 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000984 if (AllNonStoreUsesGone) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000985 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000986 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000987 } else {
988 Changed = true;
989 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
990 }
Chris Lattner708148e2004-10-10 23:14:11 +0000991 if (GV->use_empty()) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000992 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
993 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000994 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000995 ++NumDeleted;
996 }
Chris Lattner708148e2004-10-10 23:14:11 +0000997 }
998 return Changed;
999}
1000
Chris Lattner30ba5692004-10-11 05:54:41 +00001001/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
1002/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001003static void ConstantPropUsersOf(Value *V,
Micah Villmow3574eca2012-10-08 16:38:25 +00001004 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001005 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
1006 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +00001007 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001008 I->replaceAllUsesWith(NewC);
1009
Chris Lattnerd514d822005-02-01 01:23:31 +00001010 // Advance UI to the next non-I use to avoid invalidating it!
1011 // Instructions could multiply use V.
1012 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +00001013 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +00001014 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +00001015 }
1016}
1017
1018/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
1019/// variable, and transforms the program as if it always contained the result of
1020/// the specified malloc. Because it is always the result of the specified
1021/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001022/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001023static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001024 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001025 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +00001026 ConstantInt *NElements,
Micah Villmow3574eca2012-10-08 16:38:25 +00001027 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001028 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +00001029 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001030
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001031 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +00001032 if (NElements->getZExtValue() == 1)
1033 GlobalType = AllocTy;
1034 else
1035 // If we have an array allocation, the global variable is of an array.
1036 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +00001037
1038 // Create the new global variable. The contents of the malloc'd memory is
1039 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001040 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +00001041 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +00001042 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +00001043 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +00001044 GV->getName()+".body",
1045 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001046 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001047
Chris Lattnera6874652010-02-25 22:33:52 +00001048 // If there are bitcast users of the malloc (which is typical, usually we have
1049 // a malloc + bitcast) then replace them with uses of the new global. Update
1050 // other users to use the global as well.
1051 BitCastInst *TheBC = 0;
1052 while (!CI->use_empty()) {
1053 Instruction *User = cast<Instruction>(CI->use_back());
1054 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1055 if (BCI->getType() == NewGV->getType()) {
1056 BCI->replaceAllUsesWith(NewGV);
1057 BCI->eraseFromParent();
1058 } else {
1059 BCI->setOperand(0, NewGV);
1060 }
1061 } else {
1062 if (TheBC == 0)
1063 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1064 User->replaceUsesOfWith(CI, TheBC);
1065 }
1066 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001067
Victor Hernandez83d63912009-09-18 22:35:49 +00001068 Constant *RepValue = NewGV;
1069 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001070 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +00001071 GV->getType()->getElementType());
1072
1073 // If there is a comparison against null, we will insert a global bool to
1074 // keep track of whether the global was initialized yet or not.
1075 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001076 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +00001077 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001078 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +00001079 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001080 bool InitBoolUsed = false;
1081
1082 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +00001083 while (!GV->use_empty()) {
1084 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001085 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001086 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1087 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001088 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +00001089 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +00001090 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001091
Chris Lattnera6874652010-02-25 22:33:52 +00001092 LoadInst *LI = cast<LoadInst>(GV->use_back());
1093 while (!LI->use_empty()) {
1094 Use &LoadUse = LI->use_begin().getUse();
1095 if (!isa<ICmpInst>(LoadUse.getUser())) {
1096 LoadUse = RepValue;
1097 continue;
1098 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001099
Chris Lattnera6874652010-02-25 22:33:52 +00001100 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1101 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001102 // Sink the load to where the compare was, if atomic rules allow us to.
1103 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1104 LI->getOrdering(), LI->getSynchScope(),
1105 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +00001106 InitBoolUsed = true;
1107 switch (ICI->getPredicate()) {
1108 default: llvm_unreachable("Unknown ICmp Predicate!");
1109 case ICmpInst::ICMP_ULT:
1110 case ICmpInst::ICMP_SLT: // X < null -> always false
1111 LV = ConstantInt::getFalse(GV->getContext());
1112 break;
1113 case ICmpInst::ICMP_ULE:
1114 case ICmpInst::ICMP_SLE:
1115 case ICmpInst::ICMP_EQ:
1116 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1117 break;
1118 case ICmpInst::ICMP_NE:
1119 case ICmpInst::ICMP_UGE:
1120 case ICmpInst::ICMP_SGE:
1121 case ICmpInst::ICMP_UGT:
1122 case ICmpInst::ICMP_SGT:
1123 break; // no change.
1124 }
1125 ICI->replaceAllUsesWith(LV);
1126 ICI->eraseFromParent();
1127 }
1128 LI->eraseFromParent();
1129 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001130
1131 // If the initialization boolean was used, insert it, otherwise delete it.
1132 if (!InitBoolUsed) {
1133 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +00001134 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001135 delete InitBool;
1136 } else
1137 GV->getParent()->getGlobalList().insert(GV, InitBool);
1138
Chris Lattnera6874652010-02-25 22:33:52 +00001139 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +00001140 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001141 CI->eraseFromParent();
1142
1143 // To further other optimizations, loop over all users of NewGV and try to
1144 // constant prop them. This will promote GEP instructions with constant
1145 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001146 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001147 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +00001148 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001149
1150 return NewGV;
1151}
1152
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001153/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1154/// to make sure that there are no complex uses of V. We permit simple things
1155/// like dereferencing the pointer, but not storing through the address, unless
1156/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +00001157static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1158 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +00001159 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001160 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +00001161 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001162 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +00001163
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001164 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1165 continue; // Fine, ignore.
1166 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001167
Gabor Greif0b520db2010-04-06 18:58:22 +00001168 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001169 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1170 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001171 continue; // Otherwise, storing through it, or storing into GV... fine.
1172 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001173
Chris Lattnera2fb2342010-04-10 18:19:22 +00001174 // Must index into the array and into the struct.
1175 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001176 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001177 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001178 continue;
1179 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001180
Gabor Greif0b520db2010-04-06 18:58:22 +00001181 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001182 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1183 // cycles.
1184 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001185 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1186 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001187 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001188 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001189
Gabor Greif0b520db2010-04-06 18:58:22 +00001190 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001191 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1192 return false;
1193 continue;
1194 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001195
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001196 return false;
1197 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001198 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001199}
1200
Chris Lattner86395032006-09-30 23:32:09 +00001201/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1202/// somewhere. Transform all uses of the allocation into loads from the
1203/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001204/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001205/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001206static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001207 GlobalVariable *GV) {
1208 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001209 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1210 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001211 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1212 // If this is the store of the allocation into the global, remove it.
1213 if (SI->getOperand(1) == GV) {
1214 SI->eraseFromParent();
1215 continue;
1216 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001217 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1218 // Insert the load in the corresponding predecessor, not right before the
1219 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001220 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001221 } else if (isa<BitCastInst>(U)) {
1222 // Must be bitcast between the malloc and store to initialize the global.
1223 ReplaceUsesOfMallocWithGlobal(U, GV);
1224 U->eraseFromParent();
1225 continue;
1226 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1227 // If this is a "GEP bitcast" and the user is a store to the global, then
1228 // just process it as a bitcast.
1229 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1230 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1231 if (SI->getOperand(1) == GV) {
1232 // Must be bitcast GEP between the malloc and store to initialize
1233 // the global.
1234 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1235 GEPI->eraseFromParent();
1236 continue;
1237 }
Chris Lattner86395032006-09-30 23:32:09 +00001238 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001239
Chris Lattner86395032006-09-30 23:32:09 +00001240 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001241 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001242 U->replaceUsesOfWith(Alloc, NL);
1243 }
1244}
1245
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001246/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1247/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1248/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001249static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001250 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1251 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001252 // We permit two users of the load: setcc comparing against the null
1253 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001254 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1255 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001256 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001257
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001258 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001259 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001260 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1261 return false;
1262 continue;
1263 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001264
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001265 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001266 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001267 // Must index into the array and into the struct.
1268 if (GEPI->getNumOperands() < 3)
1269 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001270
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001271 // Otherwise the GEP is ok.
1272 continue;
1273 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001274
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001275 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001276 if (!LoadUsingPHIsPerLoad.insert(PN))
1277 // This means some phi nodes are dependent on each other.
1278 // Avoid infinite looping!
1279 return false;
1280 if (!LoadUsingPHIs.insert(PN))
1281 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001282 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001283
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001284 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001285 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1286 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001287 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001288
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001289 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001290 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001291
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001292 // Otherwise we don't know what this is, not ok.
1293 return false;
1294 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001295
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001296 return true;
1297}
1298
1299
1300/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1301/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001302static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001303 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001304 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1305 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001306 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1307 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001308 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001309 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1310 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001311 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001312 LoadUsingPHIsPerLoad.clear();
1313 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001314
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001315 // If we reach here, we know that all uses of the loads and transitive uses
1316 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001317 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001318 // Check to verify that all operands of the PHIs are either PHIS that can be
1319 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001320 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1321 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001322 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001323 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1324 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001325
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001326 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001327 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001328
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001329 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001330 // One of the PHIs in our set is (optimistically) ok.
1331 if (LoadUsingPHIs.count(InPN))
1332 continue;
1333 return false;
1334 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001335
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001336 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001337 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001338 if (LI->getOperand(0) == GV)
1339 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001340
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001341 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001342
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001343 // Anything else is rejected.
1344 return false;
1345 }
1346 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001347
Chris Lattner86395032006-09-30 23:32:09 +00001348 return true;
1349}
1350
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001351static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1352 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001353 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001354 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001355
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001356 if (FieldNo >= FieldVals.size())
1357 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001358
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001359 // If we already have this value, just reuse the previously scalarized
1360 // version.
1361 if (Value *FieldVal = FieldVals[FieldNo])
1362 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001363
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001364 // Depending on what instruction this is, we have several cases.
1365 Value *Result;
1366 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1367 // This is a scalarized version of the load from the global. Just create
1368 // a new Load of the scalarized global.
1369 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1370 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001371 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001372 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001373 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1374 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1375 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001376 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001377 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001378
Jay Foadd8b4fb42011-03-30 11:19:20 +00001379 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001380 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001381 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001382 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001383 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001384 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1385 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001386 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001387 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001388
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001389 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001390}
1391
Chris Lattner330245e2007-09-13 17:29:05 +00001392/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1393/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001394static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001395 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001396 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001397 // If this is a comparison against null, handle it.
1398 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1399 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1400 // If we have a setcc of the loaded pointer, we can use a setcc of any
1401 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001402 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001403 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001404
Owen Anderson333c4002009-07-09 23:48:35 +00001405 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001406 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001407 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001408 SCI->replaceAllUsesWith(New);
1409 SCI->eraseFromParent();
1410 return;
1411 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001412
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001413 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001414 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1415 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1416 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001417
Chris Lattnera637a8b2007-09-13 18:00:31 +00001418 // Load the pointer for this field.
1419 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001420 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001421 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001422
Chris Lattnera637a8b2007-09-13 18:00:31 +00001423 // Create the new GEP idx vector.
1424 SmallVector<Value*, 8> GEPIdx;
1425 GEPIdx.push_back(GEPI->getOperand(1));
1426 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001427
Jay Foada9203102011-07-25 09:48:08 +00001428 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001429 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001430 GEPI->replaceAllUsesWith(NGEPI);
1431 GEPI->eraseFromParent();
1432 return;
1433 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001434
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001435 // Recursively transform the users of PHI nodes. This will lazily create the
1436 // PHIs that are needed for individual elements. Keep track of what PHIs we
1437 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1438 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1439 // already been seen first by another load, so its uses have already been
1440 // processed.
1441 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001442 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1443 std::vector<Value*>())).second)
1444 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001445
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001446 // If this is the first time we've seen this PHI, recursively process all
1447 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001448 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1449 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001450 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001451 }
Chris Lattner330245e2007-09-13 17:29:05 +00001452}
1453
Chris Lattner86395032006-09-30 23:32:09 +00001454/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1455/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1456/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001457/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001458static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001459 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001460 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001461 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001462 UI != E; ) {
1463 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001464 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001465 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001466
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001467 if (Load->use_empty()) {
1468 Load->eraseFromParent();
1469 InsertedScalarizedValues.erase(Load);
1470 }
Chris Lattner86395032006-09-30 23:32:09 +00001471}
1472
Victor Hernandez83d63912009-09-18 22:35:49 +00001473/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1474/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001475static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001476 Value *NElems, DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001477 const TargetLibraryInfo *TLI) {
David Greene3215b0e2010-01-05 01:28:05 +00001478 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001479 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001480 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001481
1482 // There is guaranteed to be at least one use of the malloc (storing
1483 // it into GV). If there are other uses, change them to be uses of
1484 // the global to simplify later code. This also deletes the store
1485 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001486 ReplaceUsesOfMallocWithGlobal(CI, GV);
1487
Victor Hernandez83d63912009-09-18 22:35:49 +00001488 // Okay, at this point, there are no users of the malloc. Insert N
1489 // new mallocs at the same place as CI, and N globals.
1490 std::vector<Value*> FieldGlobals;
1491 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001492
Victor Hernandez83d63912009-09-18 22:35:49 +00001493 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001494 Type *FieldTy = STy->getElementType(FieldNo);
1495 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001496
Victor Hernandez83d63912009-09-18 22:35:49 +00001497 GlobalVariable *NGV =
1498 new GlobalVariable(*GV->getParent(),
1499 PFieldTy, false, GlobalValue::InternalLinkage,
1500 Constant::getNullValue(PFieldTy),
1501 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001502 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001503 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001504
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001505 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001506 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001507 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001508 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001509 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1510 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001511 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001512 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001513 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001514 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001515 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001516
Victor Hernandez83d63912009-09-18 22:35:49 +00001517 // The tricky aspect of this transformation is handling the case when malloc
1518 // fails. In the original code, malloc failing would set the result pointer
1519 // of malloc to null. In this case, some mallocs could succeed and others
1520 // could fail. As such, we emit code that looks like this:
1521 // F0 = malloc(field0)
1522 // F1 = malloc(field1)
1523 // F2 = malloc(field2)
1524 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1525 // if (F0) { free(F0); F0 = 0; }
1526 // if (F1) { free(F1); F1 = 0; }
1527 // if (F2) { free(F2); F2 = 0; }
1528 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001529 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001530 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1531 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001532 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001533 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001534 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1535 Constant::getNullValue(FieldMallocs[i]->getType()),
1536 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001537 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001538 }
1539
1540 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001541 BasicBlock *OrigBB = CI->getParent();
1542 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001543
Victor Hernandez83d63912009-09-18 22:35:49 +00001544 // Create the block to check the first condition. Put all these blocks at the
1545 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001546 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1547 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001548 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001549
Victor Hernandez83d63912009-09-18 22:35:49 +00001550 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1551 // branch on RunningOr.
1552 OrigBB->getTerminator()->eraseFromParent();
1553 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001554
Victor Hernandez83d63912009-09-18 22:35:49 +00001555 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1556 // pointer, because some may be null while others are not.
1557 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1558 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001559 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001560 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001561 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001562 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001563 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001564 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001565 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1566 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001567
1568 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001569 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001570 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1571 FreeBlock);
1572 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001573
Victor Hernandez83d63912009-09-18 22:35:49 +00001574 NullPtrBlock = NextBlock;
1575 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001576
Victor Hernandez83d63912009-09-18 22:35:49 +00001577 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001578
1579 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001580 CI->eraseFromParent();
1581
1582 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1583 /// update all uses of the load, keep track of what scalarized loads are
1584 /// inserted for a given load.
1585 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1586 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001587
Victor Hernandez83d63912009-09-18 22:35:49 +00001588 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001589
Victor Hernandez83d63912009-09-18 22:35:49 +00001590 // Okay, the malloc site is completely handled. All of the uses of GV are now
1591 // loads, and all uses of those loads are simple. Rewrite them to use loads
1592 // of the per-field globals instead.
1593 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1594 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001595
Victor Hernandez83d63912009-09-18 22:35:49 +00001596 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001597 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001598 continue;
1599 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001600
Victor Hernandez83d63912009-09-18 22:35:49 +00001601 // Must be a store of null.
1602 StoreInst *SI = cast<StoreInst>(User);
1603 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1604 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001605
Victor Hernandez83d63912009-09-18 22:35:49 +00001606 // Insert a store of null into each global.
1607 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001608 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001609 Constant *Null = Constant::getNullValue(PT->getElementType());
1610 new StoreInst(Null, FieldGlobals[i], SI);
1611 }
1612 // Erase the original store.
1613 SI->eraseFromParent();
1614 }
1615
1616 // While we have PHIs that are interesting to rewrite, do it.
1617 while (!PHIsToRewrite.empty()) {
1618 PHINode *PN = PHIsToRewrite.back().first;
1619 unsigned FieldNo = PHIsToRewrite.back().second;
1620 PHIsToRewrite.pop_back();
1621 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1622 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1623
1624 // Add all the incoming values. This can materialize more phis.
1625 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1626 Value *InVal = PN->getIncomingValue(i);
1627 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001628 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001629 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1630 }
1631 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001632
Victor Hernandez83d63912009-09-18 22:35:49 +00001633 // Drop all inter-phi links and any loads that made it this far.
1634 for (DenseMap<Value*, std::vector<Value*> >::iterator
1635 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1636 I != E; ++I) {
1637 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1638 PN->dropAllReferences();
1639 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1640 LI->dropAllReferences();
1641 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001642
Victor Hernandez83d63912009-09-18 22:35:49 +00001643 // Delete all the phis and loads now that inter-references are dead.
1644 for (DenseMap<Value*, std::vector<Value*> >::iterator
1645 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1646 I != E; ++I) {
1647 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1648 PN->eraseFromParent();
1649 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1650 LI->eraseFromParent();
1651 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001652
Victor Hernandez83d63912009-09-18 22:35:49 +00001653 // The old global is now dead, remove it.
1654 GV->eraseFromParent();
1655
1656 ++NumHeapSRA;
1657 return cast<GlobalVariable>(FieldGlobals[0]);
1658}
1659
Chris Lattnere61d0a62008-12-15 21:02:25 +00001660/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1661/// pointer global variable with a single value stored it that is a malloc or
1662/// cast of malloc.
1663static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001664 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001665 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001666 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001667 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001668 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001669 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001670 if (!TD)
1671 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001672
Victor Hernandez83d63912009-09-18 22:35:49 +00001673 // If this is a malloc of an abstract type, don't touch it.
1674 if (!AllocTy->isSized())
1675 return false;
1676
1677 // We can't optimize this global unless all uses of it are *known* to be
1678 // of the malloc value, not of the null initializer value (consider a use
1679 // that compares the global's value against zero to see if the malloc has
1680 // been reached). To do this, we check to see if all uses of the global
1681 // would trap if the global were null: this proves that they must all
1682 // happen after the malloc.
1683 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1684 return false;
1685
1686 // We can't optimize this if the malloc itself is used in a complex way,
1687 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001688 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001689 // GEP'd. These are all things we could transform to using the global
1690 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001691 SmallPtrSet<const PHINode*, 8> PHIs;
1692 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1693 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001694
1695 // If we have a global that is only initialized with a fixed size malloc,
1696 // transform the program to use global memory instead of malloc'd memory.
1697 // This eliminates dynamic allocation, avoids an indirection accessing the
1698 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001699 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001700 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng86cd4452010-04-14 20:52:55 +00001701 if (!NElems)
1702 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001703
Evan Cheng86cd4452010-04-14 20:52:55 +00001704 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1705 // Restrict this transformation to only working on small allocations
1706 // (2048 bytes currently), as we don't want to introduce a 16M global or
1707 // something.
1708 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001709 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001710 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001711 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001712
Evan Cheng86cd4452010-04-14 20:52:55 +00001713 // If the allocation is an array of structures, consider transforming this
1714 // into multiple malloc'd arrays, one for each field. This is basically
1715 // SRoA for malloc'd memory.
1716
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001717 if (Ordering != NotAtomic)
1718 return false;
1719
Evan Cheng86cd4452010-04-14 20:52:55 +00001720 // If this is an allocation of a fixed size array of structs, analyze as a
1721 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001722 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001723 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001724 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001725
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001726 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001727 if (!AllocSTy)
1728 return false;
1729
1730 // This the structure has an unreasonable number of fields, leave it
1731 // alone.
1732 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1733 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1734
1735 // If this is a fixed size array, transform the Malloc to be an alloc of
1736 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001737 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001738 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001739 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1740 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1741 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1742 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1743 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001744 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001745 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1746 CI->replaceAllUsesWith(Cast);
1747 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001748 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1749 CI = cast<CallInst>(BCI->getOperand(0));
1750 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001751 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001752 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001753
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001754 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1755 TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001756 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001757 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001758
Victor Hernandez83d63912009-09-18 22:35:49 +00001759 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001760}
Victor Hernandez83d63912009-09-18 22:35:49 +00001761
Chris Lattner9b34a612004-10-09 21:48:45 +00001762// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1763// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001764static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001765 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001766 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001767 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001768 // Ignore no-op GEPs and bitcasts.
1769 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001770
Chris Lattner708148e2004-10-10 23:14:11 +00001771 // If we are dealing with a pointer global that is initialized to null and
1772 // only has one (non-null) value stored into it, then we can optimize any
1773 // users of the loaded value (often calls and loads) that would trap if the
1774 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001775 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001776 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001777 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1778 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001779 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001780
Chris Lattner708148e2004-10-10 23:14:11 +00001781 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001782 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001783 return true;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001784 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1785 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001786 if (MallocType &&
1787 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1788 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001789 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001790 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001791 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001792
Chris Lattner9b34a612004-10-09 21:48:45 +00001793 return false;
1794}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001795
Chris Lattner58e44f42008-01-14 01:17:44 +00001796/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1797/// two values ever stored into GV are its initializer and OtherVal. See if we
1798/// can shrink the global into a boolean and select between the two values
1799/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001800static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001801 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001802
Chris Lattner58e44f42008-01-14 01:17:44 +00001803 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001804 // an FP value, pointer or vector, don't do this optimization because a select
1805 // between them is very expensive and unlikely to lead to later
1806 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1807 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001808 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001809 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001810 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001811 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001812
Chris Lattner58e44f42008-01-14 01:17:44 +00001813 // Walk the use list of the global seeing if all the uses are load or store.
1814 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001815 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1816 User *U = *I;
1817 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001818 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001819 }
1820
David Greene3215b0e2010-01-05 01:28:05 +00001821 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001822
Chris Lattner96a86b22004-12-12 05:53:50 +00001823 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001824 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1825 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001826 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001827 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001828 GV->getName()+".b",
Joey Gouly1d505a32013-01-10 10:31:11 +00001829 GV->getThreadLocalMode(),
1830 GV->getType()->getAddressSpace());
Chris Lattner96a86b22004-12-12 05:53:50 +00001831 GV->getParent()->getGlobalList().insert(GV, NewGV);
1832
1833 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001834 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001835 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001836
1837 // If initialized to zero and storing one into the global, we can use a cast
1838 // instead of a select to synthesize the desired value.
1839 bool IsOneZero = false;
1840 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001841 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001842
1843 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001844 Instruction *UI = cast<Instruction>(GV->use_back());
1845 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001846 // Change the store into a boolean store.
1847 bool StoringOther = SI->getOperand(0) == OtherVal;
1848 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001849 Value *StoreVal;
Bill Wendling17fe48c2013-02-13 23:00:51 +00001850 if (StoringOther || SI->getOperand(0) == InitVal) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001851 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1852 StoringOther);
Bill Wendling17fe48c2013-02-13 23:00:51 +00001853 } else {
Chris Lattner38c25562004-12-12 19:34:41 +00001854 // Otherwise, we are storing a previously loaded copy. To do this,
1855 // change the copy from copying the original value to just copying the
1856 // bool.
1857 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1858
Gabor Greif9e4f2432010-06-24 14:42:01 +00001859 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001860 // select instruction. If not, it will be a load of the original
1861 // global.
1862 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1863 assert(LI->getOperand(0) == GV && "Not a copy!");
1864 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001865 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1866 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001867 } else {
1868 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1869 "This is not a form that we understand!");
1870 StoreVal = StoredVal->getOperand(0);
1871 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1872 }
1873 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001874 new StoreInst(StoreVal, NewGV, false, 0,
1875 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001876 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001877 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001878 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001879 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1880 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001881 Value *NSI;
1882 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001883 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001884 else
Gabor Greif051a9502008-04-06 20:25:17 +00001885 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001886 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001887 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001888 }
1889 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001890 }
1891
Bill Wendling17fe48c2013-02-13 23:00:51 +00001892 // Retain the name of the old global variable. People who are debugging their
1893 // programs may expect these variables to be named the same.
1894 NewGV->takeName(GV);
Chris Lattner96a86b22004-12-12 05:53:50 +00001895 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001896 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001897}
1898
1899
Nick Lewyckydb292a62012-02-12 00:52:26 +00001900/// ProcessGlobal - Analyze the specified global variable and optimize it if
1901/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001902bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1903 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001904 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001905 return false;
1906
1907 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001908 GV->removeDeadConstantUsers();
1909
1910 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001911 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001912 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001913 ++NumDeleted;
1914 return true;
1915 }
1916
Rafael Espindola2f135d42012-06-15 18:00:24 +00001917 if (!GV->hasLocalLinkage())
1918 return false;
1919
Rafael Espindolac4440e32011-01-19 16:32:21 +00001920 SmallPtrSet<const PHINode*, 16> PHIUsers;
1921 GlobalStatus GS;
1922
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001923 if (AnalyzeGlobal(GV, GS, PHIUsers))
1924 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001925
Rafael Espindolac4440e32011-01-19 16:32:21 +00001926 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1927 GV->setUnnamedAddr(true);
1928 NumUnnamed++;
1929 }
1930
1931 if (GV->isConstant() || !GV->hasInitializer())
1932 return false;
1933
1934 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1935}
1936
1937/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1938/// it if possible. If we make a change, return true.
1939bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1940 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001941 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001942 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001943 // If this is a first class global and has only one accessing function
Eli Bendersky201cdb12013-07-08 23:57:07 +00001944 // and this function is main (which we know is not recursive), we replace
1945 // the global with a local alloca in this function.
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001946 //
1947 // NOTE: It doesn't make sense to promote non single-value types since we
1948 // are just replacing static memory to stack memory.
1949 //
1950 // If the global is in different address space, don't bring it to stack.
1951 if (!GS.HasMultipleAccessingFunctions &&
1952 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1953 GV->getType()->getElementType()->isSingleValueType() &&
1954 GS.AccessingFunction->getName() == "main" &&
1955 GS.AccessingFunction->hasExternalLinkage() &&
1956 GV->getType()->getAddressSpace() == 0) {
1957 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001958 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001959 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001960 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001961 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001962 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001963 if (!isa<UndefValue>(GV->getInitializer()))
1964 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001965
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001966 GV->replaceAllUsesWith(Alloca);
1967 GV->eraseFromParent();
1968 ++NumLocalized;
1969 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001970 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001971
1972 // If the global is never loaded (but may be stored to), it is dead.
1973 // Delete it now.
1974 if (!GS.isLoaded) {
1975 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1976
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001977 bool Changed;
1978 if (isLeakCheckerRoot(GV)) {
1979 // Delete any constant stores to the global.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001980 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001981 } else {
1982 // Delete any stores we can find to the global. We may not be able to
1983 // make it completely dead though.
1984 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1985 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001986
1987 // If the global is dead now, delete it.
1988 if (GV->use_empty()) {
1989 GV->eraseFromParent();
1990 ++NumDeleted;
1991 Changed = true;
1992 }
1993 return Changed;
1994
1995 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00001996 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001997 GV->setConstant(true);
1998
1999 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002000 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002001
2002 // If the global is dead now, just nuke it.
2003 if (GV->use_empty()) {
2004 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
2005 << "all users and delete global!\n");
2006 GV->eraseFromParent();
2007 ++NumDeleted;
2008 }
2009
2010 ++NumMarked;
2011 return true;
2012 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmow3574eca2012-10-08 16:38:25 +00002013 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002014 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
2015 GVI = FirstNewGV; // Don't skip the newly produced globals!
2016 return true;
2017 }
2018 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
2019 // If the initial value for the global was an undef value, and if only
2020 // one other value was stored into it, we can just change the
2021 // initializer to be the stored value, then delete all stores to the
2022 // global. This allows us to mark it constant.
2023 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2024 if (isa<UndefValue>(GV->getInitializer())) {
2025 // Change the initial value here.
2026 GV->setInitializer(SOVConstant);
2027
2028 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002029 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002030
2031 if (GV->use_empty()) {
2032 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00002033 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002034 GV->eraseFromParent();
2035 ++NumDeleted;
2036 } else {
2037 GVI = GV;
2038 }
2039 ++NumSubstitute;
2040 return true;
2041 }
2042
2043 // Try to optimize globals based on the knowledge that only one value
2044 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00002045 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00002046 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002047 return true;
2048
2049 // Otherwise, if the global was not a boolean, we can shrink it to be a
2050 // boolean.
2051 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2052 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
2053 ++NumShrunkToBool;
2054 return true;
2055 }
2056 }
2057
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002058 return false;
2059}
2060
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002061/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2062/// function, changing them to FastCC.
2063static void ChangeCalleesToFastCall(Function *F) {
2064 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002065 if (isa<BlockAddress>(*UI))
2066 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002067 CallSite User(cast<Instruction>(*UI));
2068 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002069 }
2070}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002071
Bill Wendling99faa3b2012-12-07 23:16:57 +00002072static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00002073 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling8e47daf2013-01-25 23:09:36 +00002074 unsigned Index = Attrs.getSlotIndex(i);
2075 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands548448a2008-02-18 17:32:13 +00002076 continue;
2077
Duncan Sands548448a2008-02-18 17:32:13 +00002078 // There can be only one.
Bill Wendling8e47daf2013-01-25 23:09:36 +00002079 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00002080 }
2081
2082 return Attrs;
2083}
2084
2085static void RemoveNestAttribute(Function *F) {
Bill Wendling5886b7b2012-10-14 06:39:53 +00002086 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002087 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002088 if (isa<BlockAddress>(*UI))
2089 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002090 CallSite User(cast<Instruction>(*UI));
Bill Wendling5886b7b2012-10-14 06:39:53 +00002091 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002092 }
2093}
2094
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002095bool GlobalOpt::OptimizeFunctions(Module &M) {
2096 bool Changed = false;
2097 // Optimize functions.
2098 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2099 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002100 // Functions without names cannot be referenced outside this module.
2101 if (!F->hasName() && !F->isDeclaration())
2102 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002103 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00002104 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00002105 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002106 Changed = true;
2107 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002108 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002109 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002110 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002111 // If this function has C calling conventions, is not a varargs
2112 // function, and is only called directly, promote it to use the Fast
2113 // calling convention.
2114 F->setCallingConv(CallingConv::Fast);
2115 ChangeCalleesToFastCall(F);
2116 ++NumFastCallFns;
2117 Changed = true;
2118 }
2119
Bill Wendling034b94b2012-12-19 07:18:57 +00002120 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002121 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002122 // The function is not used by a trampoline intrinsic, so it is safe
2123 // to remove the 'nest' attribute.
2124 RemoveNestAttribute(F);
2125 ++NumNestRemoved;
2126 Changed = true;
2127 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002128 }
2129 }
2130 return Changed;
2131}
2132
2133bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2134 bool Changed = false;
2135 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2136 GVI != E; ) {
2137 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002138 // Global variables without names cannot be referenced outside this module.
2139 if (!GV->hasName() && !GV->isDeclaration())
2140 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002141 // Simplify the initializer.
2142 if (GV->hasInitializer())
2143 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00002144 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002145 if (New && New != CE)
2146 GV->setInitializer(New);
2147 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00002148
2149 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002150 }
2151 return Changed;
2152}
2153
Nick Lewycky2c44a802011-04-08 07:30:21 +00002154/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002155/// initializers have an init priority of 65535.
2156GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002157 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2158 if (GV == 0) return 0;
Jakub Staszak582088c2012-12-06 21:57:16 +00002159
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002160 // Verify that the initializer is simple enough for us to handle. We are
2161 // only allowed to optimize the initializer if it is unique.
2162 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002163
2164 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2165 return GV;
2166 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00002167
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002168 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002169 if (isa<ConstantAggregateZero>(*i))
2170 continue;
2171 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002172 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2173 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002174
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002175 // Must have a function or null ptr.
2176 if (!isa<Function>(CS->getOperand(1)))
2177 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002178
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002179 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00002180 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2181 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002182 return 0;
2183 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002184
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002185 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002186}
2187
Chris Lattnerdb973e62005-09-26 02:31:18 +00002188/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2189/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002190static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002191 if (GV->getInitializer()->isNullValue())
2192 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002193 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2194 std::vector<Function*> Result;
2195 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002196 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2197 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002198 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2199 }
2200 return Result;
2201}
2202
Chris Lattnerdb973e62005-09-26 02:31:18 +00002203/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2204/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002205static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002206 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002207 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002208 Constant *CSVals[2];
2209 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2210 CSVals[1] = 0;
2211
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002212 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002213 cast <StructType>(
2214 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002215
Chris Lattnerdb973e62005-09-26 02:31:18 +00002216 // Create the new init list.
2217 std::vector<Constant*> CAList;
2218 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002219 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002220 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002221 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002222 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002223 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002224 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002225 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002226 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002227 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002228 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002229 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002230 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002231
Chris Lattnerdb973e62005-09-26 02:31:18 +00002232 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002233 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002234 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002235
Chris Lattnerdb973e62005-09-26 02:31:18 +00002236 // If we didn't change the number of elements, don't create a new GV.
2237 if (CA->getType() == GCL->getInitializer()->getType()) {
2238 GCL->setInitializer(CA);
2239 return GCL;
2240 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002241
Chris Lattnerdb973e62005-09-26 02:31:18 +00002242 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002243 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002244 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002245 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002246 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002247 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002248
Chris Lattnerdb973e62005-09-26 02:31:18 +00002249 // Nuke the old list, replacing any uses with the new one.
2250 if (!GCL->use_empty()) {
2251 Constant *V = NGV;
2252 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002253 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002254 GCL->replaceAllUsesWith(V);
2255 }
2256 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002257
Chris Lattnerdb973e62005-09-26 02:31:18 +00002258 if (Ctors.size())
2259 return NGV;
2260 else
2261 return 0;
2262}
Chris Lattner79c11012005-09-26 04:44:35 +00002263
2264
Jakub Staszak582088c2012-12-06 21:57:16 +00002265static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002266isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002267 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002268 const DataLayout *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002269
2270
2271/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2272/// handled by the code generator. We don't want to generate something like:
2273/// void *X = &X/42;
2274/// because the code generator doesn't have a relocation that can handle that.
2275///
2276/// This function should be called if C was not found (but just got inserted)
2277/// in SimpleConstants to avoid having to rescan the same constants all the
2278/// time.
2279static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002280 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002281 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002282 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2283 // all supported.
2284 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2285 isa<GlobalValue>(C))
2286 return true;
Jakub Staszak582088c2012-12-06 21:57:16 +00002287
Chris Lattner1945d582010-12-07 04:33:29 +00002288 // Aggregate values are safe if all their elements are.
2289 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2290 isa<ConstantVector>(C)) {
2291 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2292 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002293 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002294 return false;
2295 }
2296 return true;
2297 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002298
Chris Lattner1945d582010-12-07 04:33:29 +00002299 // We don't know exactly what relocations are allowed in constant expressions,
2300 // so we allow &global+constantoffset, which is safe and uniformly supported
2301 // across targets.
2302 ConstantExpr *CE = cast<ConstantExpr>(C);
2303 switch (CE->getOpcode()) {
2304 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002305 // Bitcast is fine if the casted value is fine.
2306 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2307
Chris Lattner1945d582010-12-07 04:33:29 +00002308 case Instruction::IntToPtr:
2309 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002310 // int <=> ptr is fine if the int type is the same size as the
2311 // pointer type.
2312 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2313 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2314 return false;
2315 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002316
Chris Lattner1945d582010-12-07 04:33:29 +00002317 // GEP is fine if it is simple + constant offset.
2318 case Instruction::GetElementPtr:
2319 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2320 if (!isa<ConstantInt>(CE->getOperand(i)))
2321 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002322 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002323
Chris Lattner1945d582010-12-07 04:33:29 +00002324 case Instruction::Add:
2325 // We allow simple+cst.
2326 if (!isa<ConstantInt>(CE->getOperand(1)))
2327 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002328 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002329 }
2330 return false;
2331}
2332
Jakub Staszak582088c2012-12-06 21:57:16 +00002333static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002334isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002335 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002336 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002337 // If we already checked this constant, we win.
2338 if (!SimpleConstants.insert(C)) return true;
2339 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002340 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002341}
2342
2343
Chris Lattner79c11012005-09-26 04:44:35 +00002344/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002345/// enough for us to understand. In particular, if it is a cast to anything
2346/// other than from one pointer type to another pointer type, we punt.
2347/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002348/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002349static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002350 // Conservatively, avoid aggregate types. This is because we don't
2351 // want to worry about them partially overlapping other stores.
2352 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2353 return false;
2354
Dan Gohmanfd54a892009-09-07 22:31:26 +00002355 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002356 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002357 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002358 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002359
Owen Andersone95a32c2011-01-14 22:31:13 +00002360 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002361 // Handle a constantexpr gep.
2362 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002363 isa<GlobalVariable>(CE->getOperand(0)) &&
2364 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002365 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002366 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002367 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002368 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002369 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002370
Dan Gohman80bdc962009-09-07 22:44:55 +00002371 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002372 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002373 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002374
2375 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002376 // notional bounds of the corresponding static array types.
2377 if (!CE->isGEPWithNoNotionalOverIndexing())
2378 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002379
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002380 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak582088c2012-12-06 21:57:16 +00002381
Owen Andersoncff6b372011-01-14 22:19:20 +00002382 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2383 // and we know how to evaluate it by moving the bitcast from the pointer
2384 // operand to the value operand.
2385 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002386 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002387 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2388 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002389 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002390 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002391 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002392
Chris Lattner79c11012005-09-26 04:44:35 +00002393 return false;
2394}
2395
Chris Lattner798b4d52005-09-26 06:52:44 +00002396/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2397/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2398/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2399static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Shengefcdb292012-12-01 10:54:28 +00002400 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002401 // Base case of the recursion.
2402 if (OpNo == Addr->getNumOperands()) {
2403 assert(Val->getType() == Init->getType() && "Type mismatch!");
2404 return Val;
2405 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002406
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002407 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002408 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002409 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002410 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2411 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002412
Chris Lattner798b4d52005-09-26 06:52:44 +00002413 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002414 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2415 unsigned Idx = CU->getZExtValue();
2416 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Shengefcdb292012-12-01 10:54:28 +00002417 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002418
Chris Lattner798b4d52005-09-26 06:52:44 +00002419 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002420 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002421 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002422
Chris Lattnerb065b062011-06-20 04:01:31 +00002423 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002424 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002425
2426 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002427 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002428 NumElts = ATy->getNumElements();
2429 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002430 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002431
2432 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002433 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2434 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002435
2436 assert(CI->getZExtValue() < NumElts);
2437 Elts[CI->getZExtValue()] =
Zhou Shengefcdb292012-12-01 10:54:28 +00002438 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnerb065b062011-06-20 04:01:31 +00002439
2440 if (Init->getType()->isArrayTy())
2441 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2442 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002443}
2444
Chris Lattner79c11012005-09-26 04:44:35 +00002445/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2446/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002447static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002448 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2449 assert(GV->hasInitializer());
2450 GV->setInitializer(Val);
2451 return;
2452 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002453
Chris Lattner798b4d52005-09-26 06:52:44 +00002454 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2455 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Shengefcdb292012-12-01 10:54:28 +00002456 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002457}
2458
Nick Lewycky7fa76772012-02-20 03:25:59 +00002459namespace {
2460
2461/// Evaluator - This class evaluates LLVM IR, producing the Constant
2462/// representing each SSA instruction. Changes to global variables are stored
2463/// in a mapping that can be iterated over after the evaluation is complete.
2464/// Once an evaluation call fails, the evaluation object should not be reused.
2465class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002466public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002467 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002468 : TD(TD), TLI(TLI) {
2469 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2470 }
2471
Nick Lewycky7fa76772012-02-20 03:25:59 +00002472 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002473 DeleteContainerPointers(ValueStack);
2474 while (!AllocaTmps.empty()) {
2475 GlobalVariable *Tmp = AllocaTmps.back();
2476 AllocaTmps.pop_back();
2477
2478 // If there are still users of the alloca, the program is doing something
2479 // silly, e.g. storing the address of the alloca somewhere and using it
2480 // later. Since this is undefined, we'll just make it be null.
2481 if (!Tmp->use_empty())
2482 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2483 delete Tmp;
2484 }
2485 }
2486
2487 /// EvaluateFunction - Evaluate a call to function F, returning true if
2488 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2489 /// arguments for the function.
2490 bool EvaluateFunction(Function *F, Constant *&RetVal,
2491 const SmallVectorImpl<Constant*> &ActualArgs);
2492
2493 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2494 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2495 /// control flows into, or null upon return.
2496 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2497
2498 Constant *getVal(Value *V) {
2499 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2500 Constant *R = ValueStack.back()->lookup(V);
2501 assert(R && "Reference to an uncomputed value!");
2502 return R;
2503 }
2504
2505 void setVal(Value *V, Constant *C) {
2506 ValueStack.back()->operator[](V) = C;
2507 }
2508
2509 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2510 return MutatedMemory;
2511 }
2512
2513 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2514 return Invariants;
2515 }
2516
2517private:
2518 Constant *ComputeLoadResult(Constant *P);
2519
2520 /// ValueStack - As we compute SSA register values, we store their contents
2521 /// here. The back of the vector contains the current function and the stack
2522 /// contains the values in the calling frames.
2523 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2524
2525 /// CallStack - This is used to detect recursion. In pathological situations
2526 /// we could hit exponential behavior, but at least there is nothing
2527 /// unbounded.
2528 SmallVector<Function*, 4> CallStack;
2529
2530 /// MutatedMemory - For each store we execute, we update this map. Loads
2531 /// check this to get the most up-to-date value. If evaluation is successful,
2532 /// this state is committed to the process.
2533 DenseMap<Constant*, Constant*> MutatedMemory;
2534
2535 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2536 /// to represent its body. This vector is needed so we can delete the
2537 /// temporary globals when we are done.
2538 SmallVector<GlobalVariable*, 32> AllocaTmps;
2539
2540 /// Invariants - These global variables have been marked invariant by the
2541 /// static constructor.
2542 SmallPtrSet<GlobalVariable*, 8> Invariants;
2543
2544 /// SimpleConstants - These are constants we have checked and know to be
2545 /// simple enough to live in a static initializer of a global.
2546 SmallPtrSet<Constant*, 8> SimpleConstants;
2547
Micah Villmow3574eca2012-10-08 16:38:25 +00002548 const DataLayout *TD;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002549 const TargetLibraryInfo *TLI;
2550};
2551
Nick Lewycky7fa76772012-02-20 03:25:59 +00002552} // anonymous namespace
2553
Chris Lattner562a0552005-09-26 05:16:34 +00002554/// ComputeLoadResult - Return the value that would be computed by a load from
2555/// P after the stores reflected by 'memory' have been performed. If we can't
2556/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002557Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002558 // If this memory location has been recently stored, use the stored value: it
2559 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002560 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2561 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002562
Chris Lattner04de1cf2005-09-26 05:15:37 +00002563 // Access it.
2564 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002565 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002566 return GV->getInitializer();
2567 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002568 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002569
Chris Lattner798b4d52005-09-26 06:52:44 +00002570 // Handle a constantexpr getelementptr.
2571 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2572 if (CE->getOpcode() == Instruction::GetElementPtr &&
2573 isa<GlobalVariable>(CE->getOperand(0))) {
2574 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002575 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002576 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002577 }
2578
2579 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002580}
2581
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002582/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2583/// successful, false if we can't evaluate it. NewBB returns the next BB that
2584/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002585bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2586 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002587 // This is the main evaluation loop.
2588 while (1) {
2589 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002590
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002591 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2592
Chris Lattner79c11012005-09-26 04:44:35 +00002593 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002594 if (!SI->isSimple()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002595 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2596 return false; // no volatile/atomic accesses.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002597 }
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002598 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002599 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002600 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Nick Lewyckya641c072012-02-21 22:08:06 +00002601 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002602 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002603 }
2604 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002605 // If this is too complex for us to commit, reject it.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002606 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattnercd271422005-09-27 04:45:34 +00002607 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002608 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002609
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002610 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002611
2612 // If this might be too difficult for the backend to handle (e.g. the addr
2613 // of one global variable divided by another) then we can't commit it.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002614 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002615 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2616 << "\n");
Chris Lattner1945d582010-12-07 04:33:29 +00002617 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002618 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002619
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002620 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002621 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002622 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Andersoncff6b372011-01-14 22:19:20 +00002623 // If we're evaluating a store through a bitcast, then we need
2624 // to pull the bitcast off the pointer type and push it onto the
2625 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002626 Ptr = CE->getOperand(0);
Jakub Staszak582088c2012-12-06 21:57:16 +00002627
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002628 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak582088c2012-12-06 21:57:16 +00002629
Owen Anderson66f708f2011-01-16 04:33:33 +00002630 // In order to push the bitcast onto the stored value, a bitcast
2631 // from NewTy to Val's type must be legal. If it's not, we can try
2632 // introspecting NewTy to find a legal conversion.
2633 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2634 // If NewTy is a struct, we can convert the pointer to the struct
2635 // into a pointer to its first member.
2636 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002637 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002638 NewTy = STy->getTypeAtIndex(0U);
2639
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002640 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002641 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2642 Constant * const IdxList[] = {IdxZero, IdxZero};
2643
Jay Foadb4263a62011-07-22 08:52:50 +00002644 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002645 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2646 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2647
Owen Anderson66f708f2011-01-16 04:33:33 +00002648 // If we can't improve the situation by introspecting NewTy,
2649 // we have to give up.
2650 } else {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002651 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2652 "evaluate.\n");
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002653 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002654 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002655 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002656
Owen Anderson66f708f2011-01-16 04:33:33 +00002657 // If we found compatible types, go ahead and push the bitcast
2658 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002659 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002660
Michael Gottesmandcf66952013-01-11 23:08:52 +00002661 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Andersoncff6b372011-01-14 22:19:20 +00002662 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002663 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002664
Chris Lattner79c11012005-09-26 04:44:35 +00002665 MutatedMemory[Ptr] = Val;
2666 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002667 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002668 getVal(BO->getOperand(0)),
2669 getVal(BO->getOperand(1)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002670 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002671 << "\n");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002672 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002673 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002674 getVal(CI->getOperand(0)),
2675 getVal(CI->getOperand(1)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002676 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002677 << "\n");
Chris Lattner79c11012005-09-26 04:44:35 +00002678 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002679 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002680 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002681 CI->getType());
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002682 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002683 << "\n");
Chris Lattner79c11012005-09-26 04:44:35 +00002684 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002685 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2686 getVal(SI->getOperand(1)),
2687 getVal(SI->getOperand(2)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002688 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002689 << "\n");
Chris Lattner04de1cf2005-09-26 05:15:37 +00002690 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002691 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002692 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002693 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2694 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002695 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002696 InstResult =
2697 ConstantExpr::getGetElementPtr(P, GEPOps,
2698 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002699 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002700 << "\n");
Chris Lattner04de1cf2005-09-26 05:15:37 +00002701 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002702
2703 if (!LI->isSimple()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002704 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2705 return false; // no volatile/atomic accesses.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002706 }
2707
Nick Lewyckya641c072012-02-21 22:08:06 +00002708 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002709 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Nick Lewyckya641c072012-02-21 22:08:06 +00002710 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002711 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2712 "folding: " << *Ptr << "\n");
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002713 }
Nick Lewyckya641c072012-02-21 22:08:06 +00002714 InstResult = ComputeLoadResult(Ptr);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002715 if (InstResult == 0) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002716 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2717 "\n");
2718 return false; // Could not evaluate load.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002719 }
2720
2721 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattnera22fdb02005-09-26 17:07:09 +00002722 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002723 if (AI->isArrayAllocation()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002724 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2725 return false; // Cannot handle array allocs.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002726 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002727 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002728 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002729 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002730 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002731 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002732 InstResult = AllocaTmps.back();
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002733 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002734 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2735 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002736
2737 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002738 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002739 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel412a4462009-03-09 23:04:12 +00002740 ++CurInst;
2741 continue;
2742 }
2743
Chris Lattner7cd580f2006-07-07 21:37:01 +00002744 // Cannot handle inline asm.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002745 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002746 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2747 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002748 }
Chris Lattner7cd580f2006-07-07 21:37:01 +00002749
Nick Lewycky81266c52012-02-17 06:59:21 +00002750 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2751 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002752 if (MSI->isVolatile()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002753 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2754 "intrinsic.\n");
2755 return false;
2756 }
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002757 Constant *Ptr = getVal(MSI->getDest());
2758 Constant *Val = getVal(MSI->getValue());
2759 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002760 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2761 // This memset is a no-op.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002762 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002763 ++CurInst;
2764 continue;
2765 }
2766 }
2767
2768 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2769 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002770 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002771 ++CurInst;
2772 continue;
2773 }
2774
2775 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2776 // We don't insert an entry into Values, as it doesn't have a
2777 // meaningful return value.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002778 if (!II->use_empty()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002779 DEBUG(dbgs() << "Found unused invariant_start. Cant evaluate.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002780 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002781 }
Nick Lewycky81266c52012-02-17 06:59:21 +00002782 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002783 Value *PtrArg = getVal(II->getArgOperand(1));
2784 Value *Ptr = PtrArg->stripPointerCasts();
2785 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2786 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Nick Lewyckyb97b1622013-07-25 02:55:14 +00002787 if (TD && !Size->isAllOnesValue() &&
Nick Lewycky0ef05572012-02-20 23:32:26 +00002788 Size->getValue().getLimitedValue() >=
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002789 TD->getTypeStoreSize(ElemTy)) {
Nick Lewycky81266c52012-02-17 06:59:21 +00002790 Invariants.insert(GV);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002791 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2792 << "\n");
2793 } else {
2794 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2795 "invariant.\n");
2796 }
Nick Lewycky81266c52012-02-17 06:59:21 +00002797 }
2798 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002799 ++CurInst;
2800 continue;
2801 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002802
Michael Gottesmandcf66952013-01-11 23:08:52 +00002803 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewycky1f237b02011-05-29 18:41:56 +00002804 return false;
2805 }
2806
Chris Lattnercd271422005-09-27 04:45:34 +00002807 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002808 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002809 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002810 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002811 return false; // Cannot resolve.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002812 }
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002813
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002814 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002815 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002816 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002817
Reid Spencer5cbf9852007-01-30 20:08:39 +00002818 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002819 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002820 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002821 InstResult = C;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002822 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2823 *InstResult << "\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002824 } else {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002825 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002826 return false;
2827 }
2828 } else {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002829 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002830 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002831 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002832 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002833
Benjamin Kramer08135892013-01-12 15:34:31 +00002834 Constant *RetVal = 0;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002835 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002836 ValueStack.push_back(new DenseMap<Value*, Constant*>);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002837 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002838 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002839 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002840 }
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002841 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002842 InstResult = RetVal;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002843
Michael Gottesmandcf66952013-01-11 23:08:52 +00002844 if (InstResult != NULL) {
2845 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2846 InstResult << "\n\n");
2847 } else {
2848 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2849 }
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002850 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002851 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002852 DEBUG(dbgs() << "Found a terminator instruction.\n");
2853
Chris Lattnercdf98be2005-09-26 04:57:38 +00002854 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2855 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002856 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002857 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002858 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002859 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002860 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002861
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002862 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002863 }
2864 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2865 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002866 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002867 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002868 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002869 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002870 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002871 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002872 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002873 else
2874 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002875 } else if (isa<ReturnInst>(CurInst)) {
2876 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002877 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002878 // invoke, unwind, resume, unreachable.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002879 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattnercd271422005-09-27 04:45:34 +00002880 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002881 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002882
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002883 // We succeeded at evaluating this block!
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002884 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002885 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002886 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002887 // Did not know how to evaluate this!
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002888 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesmandcf66952013-01-11 23:08:52 +00002889 "\n");
Chris Lattnercd271422005-09-27 04:45:34 +00002890 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002891 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002892
Chris Lattner1945d582010-12-07 04:33:29 +00002893 if (!CurInst->use_empty()) {
2894 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002895 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Jakub Staszak582088c2012-12-06 21:57:16 +00002896
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002897 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002898 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002899
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002900 // If we just processed an invoke, we finished evaluating the block.
2901 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2902 NextBB = II->getNormalDest();
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002903 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002904 return true;
2905 }
2906
Chris Lattner79c11012005-09-26 04:44:35 +00002907 // Advance program counter.
2908 ++CurInst;
2909 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002910}
2911
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002912/// EvaluateFunction - Evaluate a call to function F, returning true if
2913/// successful, false if we can't evaluate it. ActualArgs contains the formal
2914/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002915bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2916 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002917 // Check to see if this function is already executing (recursion). If so,
2918 // bail out. TODO: we might want to accept limited recursion.
2919 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2920 return false;
2921
2922 CallStack.push_back(F);
2923
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002924 // Initialize arguments to the incoming values specified.
2925 unsigned ArgNo = 0;
2926 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2927 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002928 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002929
2930 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2931 // we can only evaluate any one basic block at most once. This set keeps
2932 // track of what we have executed so we can detect recursive cases etc.
2933 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2934
2935 // CurBB - The current basic block we're evaluating.
2936 BasicBlock *CurBB = F->begin();
2937
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002938 BasicBlock::iterator CurInst = CurBB->begin();
2939
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002940 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002941 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002942 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2943
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002944 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002945 return false;
2946
2947 if (NextBB == 0) {
2948 // Successfully running until there's no next block means that we found
2949 // the return. Fill it the return value and pop the call stack.
2950 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2951 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002952 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002953 CallStack.pop_back();
2954 return true;
2955 }
2956
2957 // Okay, we succeeded in evaluating this control flow. See if we have
2958 // executed the new block before. If so, we have a looping function,
2959 // which we cannot evaluate in reasonable time.
2960 if (!ExecutedBlocks.insert(NextBB))
2961 return false; // looped!
2962
2963 // Okay, we have never been in this block before. Check to see if there
2964 // are any PHI nodes. If so, evaluate them with information about where
2965 // we came from.
2966 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002967 for (CurInst = NextBB->begin();
2968 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002969 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002970
2971 // Advance to the next block.
2972 CurBB = NextBB;
2973 }
2974}
2975
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002976/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2977/// we can. Return true if we can, false otherwise.
Micah Villmow3574eca2012-10-08 16:38:25 +00002978static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosier00737bd2011-12-01 21:29:16 +00002979 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002980 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002981 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002982 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002983 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2984 SmallVector<Constant*, 0>());
Jakub Staszak582088c2012-12-06 21:57:16 +00002985
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002986 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002987 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002988 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002989 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002990 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002991 for (DenseMap<Constant*, Constant*>::const_iterator I =
2992 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002993 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002994 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002995 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2996 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2997 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002998 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002999 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003000
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00003001 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00003002}
3003
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003004/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
3005/// Return true if anything changed.
3006bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
3007 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
3008 bool MadeChange = false;
3009 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003010
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003011 // Loop over global ctors, optimizing them when we can.
3012 for (unsigned i = 0; i != Ctors.size(); ++i) {
3013 Function *F = Ctors[i];
3014 // Found a null terminator in the middle of the list, prune off the rest of
3015 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00003016 if (F == 0) {
3017 if (i != Ctors.size()-1) {
3018 Ctors.resize(i+1);
3019 MadeChange = true;
3020 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003021 break;
3022 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00003023 DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003024
Chris Lattner79c11012005-09-26 04:44:35 +00003025 // We cannot simplify external ctor functions.
3026 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003027
Chris Lattner79c11012005-09-26 04:44:35 +00003028 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00003029 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00003030 Ctors.erase(Ctors.begin()+i);
3031 MadeChange = true;
3032 --i;
3033 ++NumCtorsEvaluated;
3034 continue;
3035 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003036 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003037
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003038 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003039
Chris Lattner7b550cc2009-11-06 04:27:31 +00003040 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003041 return true;
3042}
3043
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003044static int compareNames(const void *A, const void *B) {
3045 const GlobalValue *VA = *reinterpret_cast<GlobalValue* const*>(A);
3046 const GlobalValue *VB = *reinterpret_cast<GlobalValue* const*>(B);
3047 if (VA->getName() < VB->getName())
3048 return -1;
3049 if (VB->getName() < VA->getName())
3050 return 1;
3051 return 0;
3052}
Rafael Espindola95f88532013-05-09 17:22:59 +00003053
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003054static void setUsedInitializer(GlobalVariable &V,
3055 SmallPtrSet<GlobalValue *, 8> Init) {
Rafael Espindola64f2f912013-07-20 23:33:15 +00003056 if (Init.empty()) {
3057 V.eraseFromParent();
3058 return;
3059 }
3060
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003061 SmallVector<llvm::Constant *, 8> UsedArray;
3062 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext());
Rafael Espindola95f88532013-05-09 17:22:59 +00003063
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003064 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Init.begin(), E = Init.end();
3065 I != E; ++I) {
3066 Constant *Cast = llvm::ConstantExpr::getBitCast(*I, Int8PtrTy);
3067 UsedArray.push_back(Cast);
Rafael Espindola95f88532013-05-09 17:22:59 +00003068 }
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003069 // Sort to get deterministic order.
3070 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
3071 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola95f88532013-05-09 17:22:59 +00003072
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003073 Module *M = V.getParent();
3074 V.removeFromParent();
3075 GlobalVariable *NV =
3076 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
3077 llvm::ConstantArray::get(ATy, UsedArray), "");
3078 NV->takeName(&V);
3079 NV->setSection("llvm.metadata");
3080 delete &V;
Rafael Espindola95f88532013-05-09 17:22:59 +00003081}
3082
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003083namespace {
Rafael Espindola70968312013-07-19 18:44:51 +00003084/// \brief An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003085class LLVMUsed {
3086 SmallPtrSet<GlobalValue *, 8> Used;
3087 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
3088 GlobalVariable *UsedV;
3089 GlobalVariable *CompilerUsedV;
3090
3091public:
Rafael Espindola2d680822013-07-25 02:50:08 +00003092 LLVMUsed(Module &M) {
Rafael Espindola4ef7eaf2013-07-25 03:23:25 +00003093 UsedV = collectUsedGlobalVariables(M, Used, false);
3094 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola95f88532013-05-09 17:22:59 +00003095 }
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003096 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
3097 iterator usedBegin() { return Used.begin(); }
3098 iterator usedEnd() { return Used.end(); }
3099 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
3100 iterator compilerUsedEnd() { return CompilerUsed.end(); }
3101 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
3102 bool compilerUsedCount(GlobalValue *GV) const {
3103 return CompilerUsed.count(GV);
3104 }
3105 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
3106 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
3107 bool usedInsert(GlobalValue *GV) { return Used.insert(GV); }
3108 bool compilerUsedInsert(GlobalValue *GV) { return CompilerUsed.insert(GV); }
Rafael Espindola95f88532013-05-09 17:22:59 +00003109
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003110 void syncVariablesAndSets() {
3111 if (UsedV)
3112 setUsedInitializer(*UsedV, Used);
3113 if (CompilerUsedV)
3114 setUsedInitializer(*CompilerUsedV, CompilerUsed);
3115 }
3116};
Rafael Espindola95f88532013-05-09 17:22:59 +00003117}
3118
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003119static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
3120 if (GA.use_empty()) // No use at all.
3121 return false;
3122
3123 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
3124 "We should have removed the duplicated "
Rafael Espindola70968312013-07-19 18:44:51 +00003125 "element from llvm.compiler.used");
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003126 if (!GA.hasOneUse())
3127 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola70968312013-07-19 18:44:51 +00003128 // llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003129 return true;
3130
Rafael Espindola70968312013-07-19 18:44:51 +00003131 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003132 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola95f88532013-05-09 17:22:59 +00003133}
3134
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003135static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
3136 const LLVMUsed &U) {
3137 unsigned N = 2;
3138 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
3139 "We should have removed the duplicated "
Rafael Espindola70968312013-07-19 18:44:51 +00003140 "element from llvm.compiler.used");
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003141 if (U.usedCount(&V) || U.compilerUsedCount(&V))
3142 ++N;
3143 return V.hasNUsesOrMore(N);
3144}
3145
3146static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
3147 if (!GA.hasLocalLinkage())
3148 return true;
3149
3150 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
3151}
3152
3153static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget) {
3154 RenameTarget = false;
Rafael Espindola95f88532013-05-09 17:22:59 +00003155 bool Ret = false;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003156 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola95f88532013-05-09 17:22:59 +00003157 Ret = true;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003158
3159 // If the alias is externally visible, we may still be able to simplify it.
3160 if (!mayHaveOtherReferences(GA, U))
3161 return Ret;
3162
3163 // If the aliasee has internal linkage, give it the name and linkage
3164 // of the alias, and delete the alias. This turns:
3165 // define internal ... @f(...)
3166 // @a = alias ... @f
3167 // into:
3168 // define ... @a(...)
3169 Constant *Aliasee = GA.getAliasee();
3170 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
3171 if (!Target->hasLocalLinkage())
3172 return Ret;
3173
3174 // Do not perform the transform if multiple aliases potentially target the
3175 // aliasee. This check also ensures that it is safe to replace the section
3176 // and other attributes of the aliasee with those of the alias.
3177 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
3178 return Ret;
3179
3180 RenameTarget = true;
3181 return true;
Rafael Espindola95f88532013-05-09 17:22:59 +00003182}
3183
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003184bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003185 bool Changed = false;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003186 LLVMUsed Used(M);
3187
3188 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.usedBegin(),
3189 E = Used.usedEnd();
3190 I != E; ++I)
3191 Used.compilerUsedErase(*I);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003192
Duncan Sands177d84e2009-01-07 20:01:06 +00003193 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00003194 I != E;) {
3195 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003196 // Aliases without names cannot be referenced outside this module.
3197 if (!J->hasName() && !J->isDeclaration())
3198 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00003199 // If the aliasee may change at link time, nothing can be done - bail out.
3200 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003201 continue;
3202
Duncan Sands4782b302009-02-15 09:56:08 +00003203 Constant *Aliasee = J->getAliasee();
3204 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00003205 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00003206
3207 // Make all users of the alias use the aliasee instead.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003208 bool RenameTarget;
3209 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola95f88532013-05-09 17:22:59 +00003210 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00003211
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003212 J->replaceAllUsesWith(Aliasee);
3213 ++NumAliasesResolved;
3214 Changed = true;
Duncan Sands4782b302009-02-15 09:56:08 +00003215
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003216 if (RenameTarget) {
Duncan Sands7a154cf2009-12-08 10:10:20 +00003217 // Give the aliasee the name, linkage and other attributes of the alias.
3218 Target->takeName(J);
3219 Target->setLinkage(J->getLinkage());
3220 Target->GlobalValue::copyAttributesFrom(J);
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003221
3222 if (Used.usedErase(J))
3223 Used.usedInsert(Target);
3224
3225 if (Used.compilerUsedErase(J))
3226 Used.compilerUsedInsert(Target);
Rafael Espindola100fbdd2013-06-12 16:45:47 +00003227 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003228 continue;
3229
Duncan Sands4782b302009-02-15 09:56:08 +00003230 // Delete the alias.
3231 M.getAliasList().erase(J);
3232 ++NumAliasesRemoved;
3233 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003234 }
3235
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003236 Used.syncVariablesAndSets();
3237
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003238 return Changed;
3239}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003240
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003241static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3242 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00003243 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003244
3245 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak582088c2012-12-06 21:57:16 +00003246
Anders Carlssona201c4c2011-03-20 17:59:11 +00003247 if (!Fn)
3248 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003249
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003250 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak582088c2012-12-06 21:57:16 +00003251
3252 // Checking that the function has the right return type, the right number of
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003253 // parameters and that they all have pointer types should be enough.
3254 if (!FTy->getReturnType()->isIntegerTy() ||
3255 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003256 !FTy->getParamType(0)->isPointerTy() ||
3257 !FTy->getParamType(1)->isPointerTy() ||
3258 !FTy->getParamType(2)->isPointerTy())
3259 return 0;
3260
3261 return Fn;
3262}
3263
3264/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3265/// destructor and can therefore be eliminated.
3266/// Note that we assume that other optimization passes have already simplified
3267/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003268/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3269/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003270static bool cxxDtorIsEmpty(const Function &Fn,
3271 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003272 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003273 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003274 if (Fn.isDeclaration())
3275 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003276
3277 if (++Fn.begin() != Fn.end())
3278 return false;
3279
3280 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3281 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3282 I != E; ++I) {
3283 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003284 // Ignore debug intrinsics.
3285 if (isa<DbgInfoIntrinsic>(CI))
3286 continue;
3287
Anders Carlssona201c4c2011-03-20 17:59:11 +00003288 const Function *CalledFn = CI->getCalledFunction();
3289
3290 if (!CalledFn)
3291 return false;
3292
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003293 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3294
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003295 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003296 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003297 return false;
3298
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003299 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003300 return false;
3301 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003302 return true; // We're done.
3303 else if (I->mayHaveSideEffects())
3304 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003305 }
3306
3307 return false;
3308}
3309
3310bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3311 /// Itanium C++ ABI p3.3.5:
3312 ///
3313 /// After constructing a global (or local static) object, that will require
3314 /// destruction on exit, a termination function is registered as follows:
3315 ///
3316 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3317 ///
3318 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3319 /// call f(p) when DSO d is unloaded, before all such termination calls
3320 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003321 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003322
3323 // This pass will look for calls to __cxa_atexit where the function is trivial
3324 // and remove them.
3325 bool Changed = false;
3326
Jakub Staszak582088c2012-12-06 21:57:16 +00003327 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
Anders Carlssona201c4c2011-03-20 17:59:11 +00003328 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003329 // We're only interested in calls. Theoretically, we could handle invoke
3330 // instructions as well, but neither llvm-gcc nor clang generate invokes
3331 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003332 CallInst *CI = dyn_cast<CallInst>(*I++);
3333 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003334 continue;
3335
Jakub Staszak582088c2012-12-06 21:57:16 +00003336 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003337 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003338 if (!DtorFn)
3339 continue;
3340
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003341 SmallPtrSet<const Function *, 8> CalledFunctions;
3342 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003343 continue;
3344
3345 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003346 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3347 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003348
Anders Carlssona201c4c2011-03-20 17:59:11 +00003349 ++NumCXXDtorsRemoved;
3350
3351 Changed |= true;
3352 }
3353
3354 return Changed;
3355}
3356
Chris Lattner7a90b682004-10-07 04:16:33 +00003357bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003358 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003359
Micah Villmow3574eca2012-10-08 16:38:25 +00003360 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003361 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003362
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003363 // Try to find the llvm.globalctors list.
3364 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003365
Chris Lattner7a90b682004-10-07 04:16:33 +00003366 bool LocalChange = true;
3367 while (LocalChange) {
3368 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003369
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003370 // Delete functions that are trivially dead, ccc -> fastcc
3371 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003372
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003373 // Optimize global_ctors list.
3374 if (GlobalCtors)
3375 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003376
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003377 // Optimize non-address-taken globals.
3378 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003379
3380 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003381 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003382
Manman Ren51502702013-05-14 21:52:44 +00003383 // Try to remove trivial global destructors if they are not removed
3384 // already.
3385 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003386 if (CXAAtExitFn)
3387 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3388
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003389 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003390 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003391
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003392 // TODO: Move all global ctors functions to the end of the module for code
3393 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003394
Chris Lattner079236d2004-02-25 21:34:36 +00003395 return Changed;
3396}