blob: 20f9de5a831cc957f71b088561d323e68f825b53 [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"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000025#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000026#include "llvm/Constants.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/DataLayout.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000028#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000029#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000030#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000031#include "llvm/Module.h"
Jay Foad562b84b2011-04-11 09:35:34 +000032#include "llvm/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"
Chris Lattnere47ba742004-10-06 20:57:02 +000041#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000042using namespace llvm;
43
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000045STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000046STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49STATISTIC(NumDeleted , "Number of globals deleted");
50STATISTIC(NumFnDeleted , "Number of functions deleted");
51STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52STATISTIC(NumLocalized , "Number of globals localized");
53STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000056STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000057STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000059STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000060
Chris Lattner86453c52006-12-19 22:09:18 +000061namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000062 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000065 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000066 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000068 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
70 }
Misha Brukmanfd939082005-04-21 23:48:37 +000071
Chris Lattnerb12914b2004-09-20 04:48:05 +000072 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000073
74 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000075 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000078 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000079 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000080 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewycky6a577f82012-02-12 01:13:18 +000085
Micah Villmow3574eca2012-10-08 16:38:25 +000086 DataLayout *TD;
Nick Lewycky6a577f82012-02-12 01:13:18 +000087 TargetLibraryInfo *TLI;
Chris Lattner079236d2004-02-25 21:34:36 +000088 };
Chris Lattner079236d2004-02-25 21:34:36 +000089}
90
Dan Gohman844731a2008-05-13 00:00:25 +000091char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000092INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
93 "Global Variable Optimizer", false, false)
94INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
95INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000096 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000097
Chris Lattner7a90b682004-10-07 04:16:33 +000098ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000099
Dan Gohman844731a2008-05-13 00:00:25 +0000100namespace {
101
Chris Lattner7a90b682004-10-07 04:16:33 +0000102/// GlobalStatus - As we analyze each global, keep track of some information
103/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000104/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000105struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000106 /// isCompared - True if the global's address is used in a comparison.
107 bool isCompared;
108
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000109 /// isLoaded - True if the global is ever loaded. If the global isn't ever
110 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000111 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000112
113 /// StoredType - Keep track of what stores to the global look like.
114 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000115 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000116 /// NotStored - There is no store to this global. It can thus be marked
117 /// constant.
118 NotStored,
119
120 /// isInitializerStored - This global is stored to, but the only thing
121 /// stored is the constant it was initialized with. This is only tracked
122 /// for scalar globals.
123 isInitializerStored,
124
125 /// isStoredOnce - This global is stored to, but only its initializer and
126 /// one other value is ever stored to it. If this global isStoredOnce, we
127 /// track the value stored to it in StoredOnceValue below. This is only
128 /// tracked for scalar globals.
129 isStoredOnce,
130
131 /// isStored - This global is stored to by multiple values or something else
132 /// that we cannot track.
133 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000134 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000135
136 /// StoredOnceValue - If only one value (besides the initializer constant) is
137 /// ever stored to this global, keep track of what value it is.
138 Value *StoredOnceValue;
139
Chris Lattner25de4e52006-11-01 18:03:33 +0000140 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
141 /// null/false. When the first accessing function is noticed, it is recorded.
142 /// When a second different accessing function is noticed,
143 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000144 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000145 bool HasMultipleAccessingFunctions;
146
Chris Lattner25de4e52006-11-01 18:03:33 +0000147 /// HasNonInstructionUser - Set to true if this global has a user that is not
148 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000149 bool HasNonInstructionUser;
150
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000151 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
152 AtomicOrdering Ordering;
153
Rafael Espindolac4440e32011-01-19 16:32:21 +0000154 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
155 StoredOnceValue(0), AccessingFunction(0),
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000156 HasMultipleAccessingFunctions(false),
Jakub Staszak5b4af8b2012-12-06 22:08:59 +0000157 HasNonInstructionUser(false), Ordering(NotAtomic) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000158};
Chris Lattnere47ba742004-10-06 20:57:02 +0000159
Dan Gohman844731a2008-05-13 00:00:25 +0000160}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000161
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000162/// StrongerOrdering - Return the stronger of the two ordering. If the two
163/// orderings are acquire and release, then return AcquireRelease.
164///
165static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
166 if (X == Acquire && Y == Release) return AcquireRelease;
167 if (Y == Acquire && X == Release) return AcquireRelease;
168 return (AtomicOrdering)std::max(X, Y);
169}
170
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000171/// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
Nick Lewyckybc384a12012-02-05 19:48:37 +0000172/// by constants itself. Note that constants cannot be cyclic, so this test is
173/// pretty easy to implement recursively.
174///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000175static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000176 if (isa<GlobalValue>(C)) return false;
177
Gabor Greif27236912010-04-07 18:59:26 +0000178 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
179 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000180 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000181 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000182 } else
183 return false;
184 return true;
185}
186
187
Chris Lattner7a90b682004-10-07 04:16:33 +0000188/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
189/// structure. If the global has its address taken, return true to indicate we
190/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000191///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000192static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
193 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000194 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000195 ++UI) {
196 const User *U = *UI;
197 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000198 GS.HasNonInstructionUser = true;
Jakub Staszak582088c2012-12-06 21:57:16 +0000199
Chris Lattnerd91ed102011-01-01 22:31:46 +0000200 // If the result of the constantexpr isn't pointer type, then we won't
201 // know to expect it in various places. Just reject early.
202 if (!isa<PointerType>(CE->getType())) return true;
Jakub Staszak582088c2012-12-06 21:57:16 +0000203
Chris Lattner7a90b682004-10-07 04:16:33 +0000204 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000205 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000206 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000207 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000208 if (GS.AccessingFunction == 0)
209 GS.AccessingFunction = F;
210 else if (GS.AccessingFunction != F)
211 GS.HasMultipleAccessingFunctions = true;
212 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000213 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000214 GS.isLoaded = true;
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000215 // Don't hack on volatile loads.
216 if (LI->isVolatile()) return true;
217 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000218 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000219 // Don't allow a store OF the address, only stores TO the address.
220 if (SI->getOperand(0) == V) return true;
221
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000222 // Don't hack on volatile stores.
223 if (SI->isVolatile()) return true;
Hans Wennborg18398582012-11-15 11:40:00 +0000224
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000225 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000226
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000227 // If this is a direct store to the global (i.e., the global is a scalar
228 // value, not an aggregate), keep more specific information about
229 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000230 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000231 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
232 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000233 Value *StoredVal = SI->getOperand(0);
Hans Wennborg18398582012-11-15 11:40:00 +0000234
235 if (Constant *C = dyn_cast<Constant>(StoredVal)) {
236 if (C->isThreadDependent()) {
237 // The stored value changes between threads; don't track it.
238 return true;
239 }
240 }
241
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000242 if (StoredVal == GV->getInitializer()) {
243 if (GS.StoredType < GlobalStatus::isInitializerStored)
244 GS.StoredType = GlobalStatus::isInitializerStored;
245 } else if (isa<LoadInst>(StoredVal) &&
246 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000247 if (GS.StoredType < GlobalStatus::isInitializerStored)
248 GS.StoredType = GlobalStatus::isInitializerStored;
249 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
250 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000251 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000252 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000253 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000254 // noop.
255 } else {
256 GS.StoredType = GlobalStatus::isStored;
257 }
258 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000259 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000260 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000261 }
Duncan Sandsb2fe7f12012-07-02 18:55:39 +0000262 } else if (isa<BitCastInst>(I)) {
263 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000264 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000265 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000266 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000267 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000268 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000269 // PHI nodes we can check just like select or GEP instructions, but we
270 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000271 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000272 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000273 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000274 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000275 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
276 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000277 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000278 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000279 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000280 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000281 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
282 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
283 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000284 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000285 } else {
286 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000287 }
Gabor Greife6642672010-07-09 16:51:20 +0000288 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000289 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000290 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000291 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000292 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000293 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000294 GS.HasNonInstructionUser = true;
295 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000296 return true;
297 }
Gabor Greife6642672010-07-09 16:51:20 +0000298 }
Chris Lattner079236d2004-02-25 21:34:36 +0000299
300 return false;
301}
302
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000303/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
304/// as a root? If so, we might not really want to eliminate the stores to it.
305static bool isLeakCheckerRoot(GlobalVariable *GV) {
306 // A global variable is a root if it is a pointer, or could plausibly contain
307 // a pointer. There are two challenges; one is that we could have a struct
308 // the has an inner member which is a pointer. We recurse through the type to
309 // detect these (up to a point). The other is that we may actually be a union
310 // of a pointer and another type, and so our LLVM type is an integer which
311 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
312 // potentially contained here.
313
314 if (GV->hasPrivateLinkage())
315 return false;
316
317 SmallVector<Type *, 4> Types;
318 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
319
320 unsigned Limit = 20;
321 do {
322 Type *Ty = Types.pop_back_val();
323 switch (Ty->getTypeID()) {
324 default: break;
325 case Type::PointerTyID: return true;
326 case Type::ArrayTyID:
327 case Type::VectorTyID: {
328 SequentialType *STy = cast<SequentialType>(Ty);
329 Types.push_back(STy->getElementType());
330 break;
331 }
332 case Type::StructTyID: {
333 StructType *STy = cast<StructType>(Ty);
334 if (STy->isOpaque()) return true;
335 for (StructType::element_iterator I = STy->element_begin(),
336 E = STy->element_end(); I != E; ++I) {
337 Type *InnerTy = *I;
338 if (isa<PointerType>(InnerTy)) return true;
339 if (isa<CompositeType>(InnerTy))
340 Types.push_back(InnerTy);
341 }
342 break;
343 }
344 }
345 if (--Limit == 0) return true;
346 } while (!Types.empty());
347 return false;
348}
349
350/// Given a value that is stored to a global but never read, determine whether
351/// it's safe to remove the store and the chain of computation that feeds the
352/// store.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000353static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000354 do {
355 if (isa<Constant>(V))
356 return true;
357 if (!V->hasOneUse())
358 return false;
Nick Lewyckyb8cd66b2012-07-25 21:19:40 +0000359 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
360 isa<GlobalValue>(V))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000361 return false;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000362 if (isAllocationFn(V, TLI))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000363 return true;
364
365 Instruction *I = cast<Instruction>(V);
366 if (I->mayHaveSideEffects())
367 return false;
368 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
369 if (!GEP->hasAllConstantIndices())
370 return false;
371 } else if (I->getNumOperands() != 1) {
372 return false;
373 }
374
375 V = I->getOperand(0);
376 } while (1);
377}
378
379/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
380/// of the global and clean up any that obviously don't assign the global a
381/// value that isn't dynamically allocated.
382///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000383static bool CleanupPointerRootUsers(GlobalVariable *GV,
384 const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000385 // A brief explanation of leak checkers. The goal is to find bugs where
386 // pointers are forgotten, causing an accumulating growth in memory
387 // usage over time. The common strategy for leak checkers is to whitelist the
388 // memory pointed to by globals at exit. This is popular because it also
389 // solves another problem where the main thread of a C++ program may shut down
390 // before other threads that are still expecting to use those globals. To
391 // handle that case, we expect the program may create a singleton and never
392 // destroy it.
393
394 bool Changed = false;
395
396 // If Dead[n].first is the only use of a malloc result, we can delete its
397 // chain of computation and the store to the global in Dead[n].second.
398 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
399
400 // Constants can't be pointers to dynamically allocated memory.
401 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
402 UI != E;) {
403 User *U = *UI++;
404 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
405 Value *V = SI->getValueOperand();
406 if (isa<Constant>(V)) {
407 Changed = true;
408 SI->eraseFromParent();
409 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
410 if (I->hasOneUse())
411 Dead.push_back(std::make_pair(I, SI));
412 }
413 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
414 if (isa<Constant>(MSI->getValue())) {
415 Changed = true;
416 MSI->eraseFromParent();
417 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
418 if (I->hasOneUse())
419 Dead.push_back(std::make_pair(I, MSI));
420 }
421 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
422 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
423 if (MemSrc && MemSrc->isConstant()) {
424 Changed = true;
425 MTI->eraseFromParent();
426 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
427 if (I->hasOneUse())
428 Dead.push_back(std::make_pair(I, MTI));
429 }
430 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
431 if (CE->use_empty()) {
432 CE->destroyConstant();
433 Changed = true;
434 }
435 } else if (Constant *C = dyn_cast<Constant>(U)) {
436 if (SafeToDestroyConstant(C)) {
437 C->destroyConstant();
438 // This could have invalidated UI, start over from scratch.
439 Dead.clear();
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000440 CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000441 return true;
442 }
443 }
444 }
445
446 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000447 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000448 Dead[i].second->eraseFromParent();
449 Instruction *I = Dead[i].first;
450 do {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000451 if (isAllocationFn(I, TLI))
Nick Lewycky952f5d52012-07-24 21:33:00 +0000452 break;
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000453 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
454 if (!J)
455 break;
456 I->eraseFromParent();
457 I = J;
Nick Lewycky952f5d52012-07-24 21:33:00 +0000458 } while (1);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000459 I->eraseFromParent();
460 }
461 }
462
463 return Changed;
464}
465
Chris Lattnere47ba742004-10-06 20:57:02 +0000466/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
467/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000468/// quick scan over the use list to clean up the easy and obvious cruft. This
469/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000470static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Micah Villmow3574eca2012-10-08 16:38:25 +0000471 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000472 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000473 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
474 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000475
Chris Lattner7a90b682004-10-07 04:16:33 +0000476 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000477 if (Init) {
478 // Replace the load with the initializer.
479 LI->replaceAllUsesWith(Init);
480 LI->eraseFromParent();
481 Changed = true;
482 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000483 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000484 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000485 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000486 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000487 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
488 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000489 Constant *SubInit = 0;
490 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000491 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000492 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000493 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000494 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000495 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000496 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000497 }
498
499 if (CE->use_empty()) {
500 CE->destroyConstant();
501 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000502 }
503 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000504 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
505 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
506 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000507 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000508 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000509 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000510 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000511 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000512 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000513
514 // If the initializer is an all-null value and we have an inbounds GEP,
515 // we already know what the result of any load from that GEP is.
516 // TODO: Handle splats.
517 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
518 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000519 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000520 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000521
Chris Lattner031955d2004-10-10 16:43:46 +0000522 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000523 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000524 Changed = true;
525 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000526 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
527 if (MI->getRawDest() == V) {
528 MI->eraseFromParent();
529 Changed = true;
530 }
531
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000532 } else if (Constant *C = dyn_cast<Constant>(U)) {
533 // If we have a chain of dead constantexprs or other things dangling from
534 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000535 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000536 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000537 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000538 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000539 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000540 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000541 }
542 }
Chris Lattner031955d2004-10-10 16:43:46 +0000543 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000544}
545
Chris Lattner941db492008-01-14 02:09:12 +0000546/// isSafeSROAElementUse - Return true if the specified instruction is a safe
547/// user of a derived expression from a global that we want to SROA.
548static bool isSafeSROAElementUse(Value *V) {
549 // We might have a dead and dangling constant hanging off of here.
550 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000551 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000552
Chris Lattner941db492008-01-14 02:09:12 +0000553 Instruction *I = dyn_cast<Instruction>(V);
554 if (!I) return false;
555
556 // Loads are ok.
557 if (isa<LoadInst>(I)) return true;
558
559 // Stores *to* the pointer are ok.
560 if (StoreInst *SI = dyn_cast<StoreInst>(I))
561 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000562
Chris Lattner941db492008-01-14 02:09:12 +0000563 // Otherwise, it must be a GEP.
564 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
565 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000566
Chris Lattner941db492008-01-14 02:09:12 +0000567 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
568 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
569 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000570
Chris Lattner941db492008-01-14 02:09:12 +0000571 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
572 I != E; ++I)
573 if (!isSafeSROAElementUse(*I))
574 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000575 return true;
576}
577
Chris Lattner941db492008-01-14 02:09:12 +0000578
579/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
580/// Look at it and its uses and decide whether it is safe to SROA this global.
581///
582static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
583 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000584 if (!isa<GetElementPtrInst>(U) &&
585 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000586 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
587 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000588
Chris Lattner941db492008-01-14 02:09:12 +0000589 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
590 // don't like < 3 operand CE's, and we don't like non-constant integer
591 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
592 // value of C.
593 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
594 !cast<Constant>(U->getOperand(1))->isNullValue() ||
595 !isa<ConstantInt>(U->getOperand(2)))
596 return false;
597
598 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
599 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000600
Chris Lattner941db492008-01-14 02:09:12 +0000601 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000602 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000603 uint64_t NumElements = AT->getNumElements();
604 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000605
Chris Lattner941db492008-01-14 02:09:12 +0000606 // Check to make sure that index falls within the array. If not,
607 // something funny is going on, so we won't do the optimization.
608 //
609 if (Idx->getZExtValue() >= NumElements)
610 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000611
Chris Lattner941db492008-01-14 02:09:12 +0000612 // We cannot scalar repl this level of the array unless any array
613 // sub-indices are in-range constants. In particular, consider:
614 // A[0][i]. We cannot know that the user isn't doing invalid things like
615 // allowing i to index an out-of-range subscript that accesses A[1].
616 //
617 // Scalar replacing *just* the outer index of the array is probably not
618 // going to be a win anyway, so just give up.
619 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000620 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000621 ++GEPI) {
622 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000623 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000624 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000625 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000626 NumElements = SubVectorTy->getNumElements();
627 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000628 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000629 "Indexed GEP type is not array, vector, or struct!");
630 continue;
631 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000632
Chris Lattner941db492008-01-14 02:09:12 +0000633 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
634 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
635 return false;
636 }
637 }
638
639 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
640 if (!isSafeSROAElementUse(*I))
641 return false;
642 return true;
643}
644
645/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
646/// is safe for us to perform this transformation.
647///
648static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
649 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
650 UI != E; ++UI) {
651 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
652 return false;
653 }
654 return true;
655}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000656
Chris Lattner941db492008-01-14 02:09:12 +0000657
Chris Lattner670c8892004-10-08 17:32:09 +0000658/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
659/// variable. This opens the door for other optimizations by exposing the
660/// behavior of the program in a more fine-grained way. We have determined that
661/// this transformation is safe already. We return the first global variable we
662/// insert so that the caller can reprocess it.
Micah Villmow3574eca2012-10-08 16:38:25 +0000663static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000664 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000665 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000666 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000667
Rafael Espindolabb46f522009-01-15 20:18:42 +0000668 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000669 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000670 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000671
Chris Lattner670c8892004-10-08 17:32:09 +0000672 std::vector<GlobalVariable*> NewGlobals;
673 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
674
Chris Lattner998182b2008-04-26 07:40:11 +0000675 // Get the alignment of the global, either explicit or target-specific.
676 unsigned StartAlignment = GV->getAlignment();
677 if (StartAlignment == 0)
678 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000679
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000680 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000681 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000682 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000683 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000684 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000685 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000686 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000687 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000688 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000689 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000690 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000691 Globals.insert(GV, NGV);
692 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000693
Chris Lattner998182b2008-04-26 07:40:11 +0000694 // Calculate the known alignment of the field. If the original aggregate
695 // had 256 byte alignment for example, something might depend on that:
696 // propagate info to each field.
697 uint64_t FieldOffset = Layout.getElementOffset(i);
698 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
699 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
700 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000701 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000702 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000703 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000704 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000705 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000706 else
Chris Lattner998182b2008-04-26 07:40:11 +0000707 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000708
Chris Lattner1f21ef12005-02-23 16:53:04 +0000709 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000710 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000711 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000712
Duncan Sands777d2302009-05-09 07:06:46 +0000713 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000714 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000715 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000716 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000717 assert(In && "Couldn't get element of initializer?");
718
Chris Lattner7b550cc2009-11-06 04:27:31 +0000719 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000720 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000721 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000722 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000723 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000724 Globals.insert(GV, NGV);
725 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000726
Chris Lattner998182b2008-04-26 07:40:11 +0000727 // Calculate the known alignment of the field. If the original aggregate
728 // had 256 byte alignment for example, something might depend on that:
729 // propagate info to each field.
730 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
731 if (NewAlign > EltAlign)
732 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000733 }
734 }
735
736 if (NewGlobals.empty())
737 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000738
David Greene3215b0e2010-01-05 01:28:05 +0000739 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000740
Chris Lattner7b550cc2009-11-06 04:27:31 +0000741 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000742
743 // Loop over all of the uses of the global, replacing the constantexpr geps,
744 // with smaller constantexpr geps or direct references.
745 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000746 User *GEP = GV->use_back();
747 assert(((isa<ConstantExpr>(GEP) &&
748 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
749 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000750
Chris Lattner670c8892004-10-08 17:32:09 +0000751 // Ignore the 1th operand, which has to be zero or else the program is quite
752 // broken (undefined). Get the 2nd operand, which is the structure or array
753 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000754 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000755 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
756
Chris Lattner30ba5692004-10-11 05:54:41 +0000757 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000758
759 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000760 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000761 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000762 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000763 Idxs.push_back(NullInt);
764 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
765 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000766 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000767 } else {
768 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000769 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000770 Idxs.push_back(NullInt);
771 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
772 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000773 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000774 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000775 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000776 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000777 GEP->replaceAllUsesWith(NewPtr);
778
779 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000780 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000781 else
782 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000783 }
784
Chris Lattnere40e2d12004-10-08 20:25:55 +0000785 // Delete the old global, now that it is dead.
786 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000787 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000788
789 // Loop over the new globals array deleting any globals that are obviously
790 // dead. This can arise due to scalarization of a structure or an array that
791 // has elements that are dead.
792 unsigned FirstGlobal = 0;
793 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
794 if (NewGlobals[i]->use_empty()) {
795 Globals.erase(NewGlobals[i]);
796 if (FirstGlobal == i) ++FirstGlobal;
797 }
798
799 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000800}
801
Chris Lattner9b34a612004-10-09 21:48:45 +0000802/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000803/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000804/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000805static bool AllUsesOfValueWillTrapIfNull(const Value *V,
806 SmallPtrSet<const PHINode*, 8> &PHIs) {
807 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000808 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000809 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000810
811 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000812 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000813 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000814 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000815 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000816 return false; // Storing the value.
817 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000818 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000819 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000820 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000821 return false; // Not calling the ptr
822 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000823 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000824 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000825 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000826 return false; // Not calling the ptr
827 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000828 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000829 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000830 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000831 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000832 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000833 // If we've already seen this phi node, ignore it, it has already been
834 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000835 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
836 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000837 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000838 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000839 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000840 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000841 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000842 return false;
843 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000844 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000845 return true;
846}
847
848/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000849/// from GV will trap if the loaded value is null. Note that this also permits
850/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000851static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
852 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000853 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000854 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000855
Gabor Greif6ce02b52010-04-06 19:24:18 +0000856 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
857 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000858 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000859 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000860 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000861 // Ignore stores to the global.
862 } else {
863 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000864 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000865 return false;
866 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000867 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000868 return true;
869}
870
Chris Lattner7b550cc2009-11-06 04:27:31 +0000871static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000872 bool Changed = false;
873 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
874 Instruction *I = cast<Instruction>(*UI++);
875 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
876 LI->setOperand(0, NewV);
877 Changed = true;
878 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
879 if (SI->getOperand(1) == V) {
880 SI->setOperand(1, NewV);
881 Changed = true;
882 }
883 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000884 CallSite CS(I);
885 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000886 // Calling through the pointer! Turn into a direct call, but be careful
887 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000888 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000889 Changed = true;
890 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000891 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
892 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000893 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000894 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000895 }
896
897 if (PassedAsArg) {
898 // Being passed as an argument also. Be careful to not invalidate UI!
899 UI = V->use_begin();
900 }
901 }
902 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
903 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000904 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000905 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000906 if (CI->use_empty()) {
907 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000908 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000909 }
910 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
911 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000912 SmallVector<Constant*, 8> Idxs;
913 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000914 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
915 i != e; ++i)
916 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000917 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000918 else
919 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000920 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000921 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000922 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000923 if (GEPI->use_empty()) {
924 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000925 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000926 }
927 }
928 }
929
930 return Changed;
931}
932
933
934/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
935/// value stored into it. If there are uses of the loaded value that would trap
936/// if the loaded value is dynamically null, then we know that they cannot be
937/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000938static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Micah Villmow3574eca2012-10-08 16:38:25 +0000939 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000940 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000941 bool Changed = false;
942
Chris Lattner92c6bd22009-01-14 00:12:58 +0000943 // Keep track of whether we are able to remove all the uses of the global
944 // other than the store that defines it.
945 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000946
Chris Lattner708148e2004-10-10 23:14:11 +0000947 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000948 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
949 User *GlobalUser = *GUI++;
950 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000951 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000952 // If we were able to delete all uses of the loads
953 if (LI->use_empty()) {
954 LI->eraseFromParent();
955 Changed = true;
956 } else {
957 AllNonStoreUsesGone = false;
958 }
959 } else if (isa<StoreInst>(GlobalUser)) {
960 // Ignore the store that stores "LV" to the global.
961 assert(GlobalUser->getOperand(1) == GV &&
962 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000963 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000964 AllNonStoreUsesGone = false;
965
966 // If we get here we could have other crazy uses that are transitively
967 // loaded.
968 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramerab164232012-09-28 10:01:27 +0000969 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
970 isa<BitCastInst>(GlobalUser) ||
971 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner98a42b22011-05-22 07:15:13 +0000972 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000973 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000974 }
Chris Lattner708148e2004-10-10 23:14:11 +0000975
976 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000977 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000978 ++NumGlobUses;
979 }
980
Chris Lattner708148e2004-10-10 23:14:11 +0000981 // If we nuked all of the loads, then none of the stores are needed either,
982 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000983 if (AllNonStoreUsesGone) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000984 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000985 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000986 } else {
987 Changed = true;
988 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
989 }
Chris Lattner708148e2004-10-10 23:14:11 +0000990 if (GV->use_empty()) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000991 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
992 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000993 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000994 ++NumDeleted;
995 }
Chris Lattner708148e2004-10-10 23:14:11 +0000996 }
997 return Changed;
998}
999
Chris Lattner30ba5692004-10-11 05:54:41 +00001000/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
1001/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001002static void ConstantPropUsersOf(Value *V,
Micah Villmow3574eca2012-10-08 16:38:25 +00001003 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001004 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
1005 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +00001006 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001007 I->replaceAllUsesWith(NewC);
1008
Chris Lattnerd514d822005-02-01 01:23:31 +00001009 // Advance UI to the next non-I use to avoid invalidating it!
1010 // Instructions could multiply use V.
1011 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +00001012 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +00001013 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +00001014 }
1015}
1016
1017/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
1018/// variable, and transforms the program as if it always contained the result of
1019/// the specified malloc. Because it is always the result of the specified
1020/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001021/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001022static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001023 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001024 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +00001025 ConstantInt *NElements,
Micah Villmow3574eca2012-10-08 16:38:25 +00001026 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001027 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +00001028 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001029
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001030 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +00001031 if (NElements->getZExtValue() == 1)
1032 GlobalType = AllocTy;
1033 else
1034 // If we have an array allocation, the global variable is of an array.
1035 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +00001036
1037 // Create the new global variable. The contents of the malloc'd memory is
1038 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001039 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +00001040 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +00001041 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +00001042 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +00001043 GV->getName()+".body",
1044 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001045 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001046
Chris Lattnera6874652010-02-25 22:33:52 +00001047 // If there are bitcast users of the malloc (which is typical, usually we have
1048 // a malloc + bitcast) then replace them with uses of the new global. Update
1049 // other users to use the global as well.
1050 BitCastInst *TheBC = 0;
1051 while (!CI->use_empty()) {
1052 Instruction *User = cast<Instruction>(CI->use_back());
1053 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1054 if (BCI->getType() == NewGV->getType()) {
1055 BCI->replaceAllUsesWith(NewGV);
1056 BCI->eraseFromParent();
1057 } else {
1058 BCI->setOperand(0, NewGV);
1059 }
1060 } else {
1061 if (TheBC == 0)
1062 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1063 User->replaceUsesOfWith(CI, TheBC);
1064 }
1065 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001066
Victor Hernandez83d63912009-09-18 22:35:49 +00001067 Constant *RepValue = NewGV;
1068 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001069 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +00001070 GV->getType()->getElementType());
1071
1072 // If there is a comparison against null, we will insert a global bool to
1073 // keep track of whether the global was initialized yet or not.
1074 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001075 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +00001076 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001077 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +00001078 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001079 bool InitBoolUsed = false;
1080
1081 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +00001082 while (!GV->use_empty()) {
1083 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001084 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001085 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1086 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001087 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +00001088 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +00001089 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001090
Chris Lattnera6874652010-02-25 22:33:52 +00001091 LoadInst *LI = cast<LoadInst>(GV->use_back());
1092 while (!LI->use_empty()) {
1093 Use &LoadUse = LI->use_begin().getUse();
1094 if (!isa<ICmpInst>(LoadUse.getUser())) {
1095 LoadUse = RepValue;
1096 continue;
1097 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001098
Chris Lattnera6874652010-02-25 22:33:52 +00001099 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1100 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001101 // Sink the load to where the compare was, if atomic rules allow us to.
1102 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1103 LI->getOrdering(), LI->getSynchScope(),
1104 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +00001105 InitBoolUsed = true;
1106 switch (ICI->getPredicate()) {
1107 default: llvm_unreachable("Unknown ICmp Predicate!");
1108 case ICmpInst::ICMP_ULT:
1109 case ICmpInst::ICMP_SLT: // X < null -> always false
1110 LV = ConstantInt::getFalse(GV->getContext());
1111 break;
1112 case ICmpInst::ICMP_ULE:
1113 case ICmpInst::ICMP_SLE:
1114 case ICmpInst::ICMP_EQ:
1115 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1116 break;
1117 case ICmpInst::ICMP_NE:
1118 case ICmpInst::ICMP_UGE:
1119 case ICmpInst::ICMP_SGE:
1120 case ICmpInst::ICMP_UGT:
1121 case ICmpInst::ICMP_SGT:
1122 break; // no change.
1123 }
1124 ICI->replaceAllUsesWith(LV);
1125 ICI->eraseFromParent();
1126 }
1127 LI->eraseFromParent();
1128 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001129
1130 // If the initialization boolean was used, insert it, otherwise delete it.
1131 if (!InitBoolUsed) {
1132 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +00001133 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001134 delete InitBool;
1135 } else
1136 GV->getParent()->getGlobalList().insert(GV, InitBool);
1137
Chris Lattnera6874652010-02-25 22:33:52 +00001138 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +00001139 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001140 CI->eraseFromParent();
1141
1142 // To further other optimizations, loop over all users of NewGV and try to
1143 // constant prop them. This will promote GEP instructions with constant
1144 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001145 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001146 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +00001147 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001148
1149 return NewGV;
1150}
1151
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001152/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1153/// to make sure that there are no complex uses of V. We permit simple things
1154/// like dereferencing the pointer, but not storing through the address, unless
1155/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +00001156static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1157 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +00001158 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001159 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +00001160 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001161 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +00001162
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001163 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1164 continue; // Fine, ignore.
1165 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001166
Gabor Greif0b520db2010-04-06 18:58:22 +00001167 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001168 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1169 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001170 continue; // Otherwise, storing through it, or storing into GV... fine.
1171 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001172
Chris Lattnera2fb2342010-04-10 18:19:22 +00001173 // Must index into the array and into the struct.
1174 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001175 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001176 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001177 continue;
1178 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001179
Gabor Greif0b520db2010-04-06 18:58:22 +00001180 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001181 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1182 // cycles.
1183 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001184 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1185 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001186 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001187 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001188
Gabor Greif0b520db2010-04-06 18:58:22 +00001189 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001190 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1191 return false;
1192 continue;
1193 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001194
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001195 return false;
1196 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001197 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001198}
1199
Chris Lattner86395032006-09-30 23:32:09 +00001200/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1201/// somewhere. Transform all uses of the allocation into loads from the
1202/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001203/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001204/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001205static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001206 GlobalVariable *GV) {
1207 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001208 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1209 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001210 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1211 // If this is the store of the allocation into the global, remove it.
1212 if (SI->getOperand(1) == GV) {
1213 SI->eraseFromParent();
1214 continue;
1215 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001216 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1217 // Insert the load in the corresponding predecessor, not right before the
1218 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001219 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001220 } else if (isa<BitCastInst>(U)) {
1221 // Must be bitcast between the malloc and store to initialize the global.
1222 ReplaceUsesOfMallocWithGlobal(U, GV);
1223 U->eraseFromParent();
1224 continue;
1225 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1226 // If this is a "GEP bitcast" and the user is a store to the global, then
1227 // just process it as a bitcast.
1228 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1229 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1230 if (SI->getOperand(1) == GV) {
1231 // Must be bitcast GEP between the malloc and store to initialize
1232 // the global.
1233 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1234 GEPI->eraseFromParent();
1235 continue;
1236 }
Chris Lattner86395032006-09-30 23:32:09 +00001237 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001238
Chris Lattner86395032006-09-30 23:32:09 +00001239 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001240 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001241 U->replaceUsesOfWith(Alloc, NL);
1242 }
1243}
1244
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001245/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1246/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1247/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001248static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001249 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1250 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001251 // We permit two users of the load: setcc comparing against the null
1252 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001253 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1254 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001255 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001256
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001257 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001258 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001259 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1260 return false;
1261 continue;
1262 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001263
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001264 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001265 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001266 // Must index into the array and into the struct.
1267 if (GEPI->getNumOperands() < 3)
1268 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001269
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001270 // Otherwise the GEP is ok.
1271 continue;
1272 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001273
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001274 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001275 if (!LoadUsingPHIsPerLoad.insert(PN))
1276 // This means some phi nodes are dependent on each other.
1277 // Avoid infinite looping!
1278 return false;
1279 if (!LoadUsingPHIs.insert(PN))
1280 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001281 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001282
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001283 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001284 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1285 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001286 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001287
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001288 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001289 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001290
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001291 // Otherwise we don't know what this is, not ok.
1292 return false;
1293 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001294
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001295 return true;
1296}
1297
1298
1299/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1300/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001301static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001302 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001303 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1304 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001305 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1306 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001307 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001308 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1309 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001310 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001311 LoadUsingPHIsPerLoad.clear();
1312 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001313
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001314 // If we reach here, we know that all uses of the loads and transitive uses
1315 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001316 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001317 // Check to verify that all operands of the PHIs are either PHIS that can be
1318 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001319 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1320 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001321 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001322 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1323 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001324
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001325 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001326 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001327
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001328 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001329 // One of the PHIs in our set is (optimistically) ok.
1330 if (LoadUsingPHIs.count(InPN))
1331 continue;
1332 return false;
1333 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001334
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001335 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001336 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001337 if (LI->getOperand(0) == GV)
1338 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001339
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001340 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001341
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001342 // Anything else is rejected.
1343 return false;
1344 }
1345 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001346
Chris Lattner86395032006-09-30 23:32:09 +00001347 return true;
1348}
1349
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001350static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1351 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001352 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001353 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001354
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001355 if (FieldNo >= FieldVals.size())
1356 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001357
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001358 // If we already have this value, just reuse the previously scalarized
1359 // version.
1360 if (Value *FieldVal = FieldVals[FieldNo])
1361 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001362
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001363 // Depending on what instruction this is, we have several cases.
1364 Value *Result;
1365 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1366 // This is a scalarized version of the load from the global. Just create
1367 // a new Load of the scalarized global.
1368 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1369 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001370 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001371 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001372 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1373 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1374 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001375 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001376 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001377
Jay Foadd8b4fb42011-03-30 11:19:20 +00001378 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001379 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001380 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001381 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001382 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001383 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1384 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001385 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001386 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001387
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001388 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001389}
1390
Chris Lattner330245e2007-09-13 17:29:05 +00001391/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1392/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001393static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001394 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001395 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001396 // If this is a comparison against null, handle it.
1397 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1398 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1399 // If we have a setcc of the loaded pointer, we can use a setcc of any
1400 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001401 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001402 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001403
Owen Anderson333c4002009-07-09 23:48:35 +00001404 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001405 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001406 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001407 SCI->replaceAllUsesWith(New);
1408 SCI->eraseFromParent();
1409 return;
1410 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001411
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001412 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001413 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1414 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1415 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001416
Chris Lattnera637a8b2007-09-13 18:00:31 +00001417 // Load the pointer for this field.
1418 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001419 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001420 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001421
Chris Lattnera637a8b2007-09-13 18:00:31 +00001422 // Create the new GEP idx vector.
1423 SmallVector<Value*, 8> GEPIdx;
1424 GEPIdx.push_back(GEPI->getOperand(1));
1425 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001426
Jay Foada9203102011-07-25 09:48:08 +00001427 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001428 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001429 GEPI->replaceAllUsesWith(NGEPI);
1430 GEPI->eraseFromParent();
1431 return;
1432 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001433
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001434 // Recursively transform the users of PHI nodes. This will lazily create the
1435 // PHIs that are needed for individual elements. Keep track of what PHIs we
1436 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1437 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1438 // already been seen first by another load, so its uses have already been
1439 // processed.
1440 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001441 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1442 std::vector<Value*>())).second)
1443 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001444
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001445 // If this is the first time we've seen this PHI, recursively process all
1446 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001447 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1448 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001449 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001450 }
Chris Lattner330245e2007-09-13 17:29:05 +00001451}
1452
Chris Lattner86395032006-09-30 23:32:09 +00001453/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1454/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1455/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001456/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001457static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001458 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001459 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001460 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001461 UI != E; ) {
1462 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001463 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001464 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001465
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001466 if (Load->use_empty()) {
1467 Load->eraseFromParent();
1468 InsertedScalarizedValues.erase(Load);
1469 }
Chris Lattner86395032006-09-30 23:32:09 +00001470}
1471
Victor Hernandez83d63912009-09-18 22:35:49 +00001472/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1473/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001474static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001475 Value *NElems, DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001476 const TargetLibraryInfo *TLI) {
David Greene3215b0e2010-01-05 01:28:05 +00001477 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001478 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001479 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001480
1481 // There is guaranteed to be at least one use of the malloc (storing
1482 // it into GV). If there are other uses, change them to be uses of
1483 // the global to simplify later code. This also deletes the store
1484 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001485 ReplaceUsesOfMallocWithGlobal(CI, GV);
1486
Victor Hernandez83d63912009-09-18 22:35:49 +00001487 // Okay, at this point, there are no users of the malloc. Insert N
1488 // new mallocs at the same place as CI, and N globals.
1489 std::vector<Value*> FieldGlobals;
1490 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001491
Victor Hernandez83d63912009-09-18 22:35:49 +00001492 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001493 Type *FieldTy = STy->getElementType(FieldNo);
1494 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001495
Victor Hernandez83d63912009-09-18 22:35:49 +00001496 GlobalVariable *NGV =
1497 new GlobalVariable(*GV->getParent(),
1498 PFieldTy, false, GlobalValue::InternalLinkage,
1499 Constant::getNullValue(PFieldTy),
1500 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001501 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001502 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001503
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001504 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001505 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001506 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001507 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001508 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1509 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001510 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001511 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001512 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001513 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001514 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001515
Victor Hernandez83d63912009-09-18 22:35:49 +00001516 // The tricky aspect of this transformation is handling the case when malloc
1517 // fails. In the original code, malloc failing would set the result pointer
1518 // of malloc to null. In this case, some mallocs could succeed and others
1519 // could fail. As such, we emit code that looks like this:
1520 // F0 = malloc(field0)
1521 // F1 = malloc(field1)
1522 // F2 = malloc(field2)
1523 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1524 // if (F0) { free(F0); F0 = 0; }
1525 // if (F1) { free(F1); F1 = 0; }
1526 // if (F2) { free(F2); F2 = 0; }
1527 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001528 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001529 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1530 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001531 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001532 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001533 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1534 Constant::getNullValue(FieldMallocs[i]->getType()),
1535 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001536 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001537 }
1538
1539 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001540 BasicBlock *OrigBB = CI->getParent();
1541 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001542
Victor Hernandez83d63912009-09-18 22:35:49 +00001543 // Create the block to check the first condition. Put all these blocks at the
1544 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001545 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1546 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001547 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001548
Victor Hernandez83d63912009-09-18 22:35:49 +00001549 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1550 // branch on RunningOr.
1551 OrigBB->getTerminator()->eraseFromParent();
1552 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001553
Victor Hernandez83d63912009-09-18 22:35:49 +00001554 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1555 // pointer, because some may be null while others are not.
1556 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1557 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001558 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001559 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001560 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001561 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001562 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001563 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001564 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1565 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001566
1567 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001568 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001569 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1570 FreeBlock);
1571 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001572
Victor Hernandez83d63912009-09-18 22:35:49 +00001573 NullPtrBlock = NextBlock;
1574 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001575
Victor Hernandez83d63912009-09-18 22:35:49 +00001576 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001577
1578 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001579 CI->eraseFromParent();
1580
1581 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1582 /// update all uses of the load, keep track of what scalarized loads are
1583 /// inserted for a given load.
1584 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1585 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001586
Victor Hernandez83d63912009-09-18 22:35:49 +00001587 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001588
Victor Hernandez83d63912009-09-18 22:35:49 +00001589 // Okay, the malloc site is completely handled. All of the uses of GV are now
1590 // loads, and all uses of those loads are simple. Rewrite them to use loads
1591 // of the per-field globals instead.
1592 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1593 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001594
Victor Hernandez83d63912009-09-18 22:35:49 +00001595 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001596 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001597 continue;
1598 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001599
Victor Hernandez83d63912009-09-18 22:35:49 +00001600 // Must be a store of null.
1601 StoreInst *SI = cast<StoreInst>(User);
1602 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1603 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001604
Victor Hernandez83d63912009-09-18 22:35:49 +00001605 // Insert a store of null into each global.
1606 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001607 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001608 Constant *Null = Constant::getNullValue(PT->getElementType());
1609 new StoreInst(Null, FieldGlobals[i], SI);
1610 }
1611 // Erase the original store.
1612 SI->eraseFromParent();
1613 }
1614
1615 // While we have PHIs that are interesting to rewrite, do it.
1616 while (!PHIsToRewrite.empty()) {
1617 PHINode *PN = PHIsToRewrite.back().first;
1618 unsigned FieldNo = PHIsToRewrite.back().second;
1619 PHIsToRewrite.pop_back();
1620 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1621 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1622
1623 // Add all the incoming values. This can materialize more phis.
1624 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1625 Value *InVal = PN->getIncomingValue(i);
1626 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001627 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001628 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1629 }
1630 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001631
Victor Hernandez83d63912009-09-18 22:35:49 +00001632 // Drop all inter-phi links and any loads that made it this far.
1633 for (DenseMap<Value*, std::vector<Value*> >::iterator
1634 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1635 I != E; ++I) {
1636 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1637 PN->dropAllReferences();
1638 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1639 LI->dropAllReferences();
1640 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001641
Victor Hernandez83d63912009-09-18 22:35:49 +00001642 // Delete all the phis and loads now that inter-references are dead.
1643 for (DenseMap<Value*, std::vector<Value*> >::iterator
1644 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1645 I != E; ++I) {
1646 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1647 PN->eraseFromParent();
1648 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1649 LI->eraseFromParent();
1650 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001651
Victor Hernandez83d63912009-09-18 22:35:49 +00001652 // The old global is now dead, remove it.
1653 GV->eraseFromParent();
1654
1655 ++NumHeapSRA;
1656 return cast<GlobalVariable>(FieldGlobals[0]);
1657}
1658
Chris Lattnere61d0a62008-12-15 21:02:25 +00001659/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1660/// pointer global variable with a single value stored it that is a malloc or
1661/// cast of malloc.
1662static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001663 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001664 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001665 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001666 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001667 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001668 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001669 if (!TD)
1670 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001671
Victor Hernandez83d63912009-09-18 22:35:49 +00001672 // If this is a malloc of an abstract type, don't touch it.
1673 if (!AllocTy->isSized())
1674 return false;
1675
1676 // We can't optimize this global unless all uses of it are *known* to be
1677 // of the malloc value, not of the null initializer value (consider a use
1678 // that compares the global's value against zero to see if the malloc has
1679 // been reached). To do this, we check to see if all uses of the global
1680 // would trap if the global were null: this proves that they must all
1681 // happen after the malloc.
1682 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1683 return false;
1684
1685 // We can't optimize this if the malloc itself is used in a complex way,
1686 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001687 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001688 // GEP'd. These are all things we could transform to using the global
1689 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001690 SmallPtrSet<const PHINode*, 8> PHIs;
1691 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1692 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001693
1694 // If we have a global that is only initialized with a fixed size malloc,
1695 // transform the program to use global memory instead of malloc'd memory.
1696 // This eliminates dynamic allocation, avoids an indirection accessing the
1697 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001698 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001699 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng86cd4452010-04-14 20:52:55 +00001700 if (!NElems)
1701 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001702
Evan Cheng86cd4452010-04-14 20:52:55 +00001703 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1704 // Restrict this transformation to only working on small allocations
1705 // (2048 bytes currently), as we don't want to introduce a 16M global or
1706 // something.
1707 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001708 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001709 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001710 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001711
Evan Cheng86cd4452010-04-14 20:52:55 +00001712 // If the allocation is an array of structures, consider transforming this
1713 // into multiple malloc'd arrays, one for each field. This is basically
1714 // SRoA for malloc'd memory.
1715
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001716 if (Ordering != NotAtomic)
1717 return false;
1718
Evan Cheng86cd4452010-04-14 20:52:55 +00001719 // If this is an allocation of a fixed size array of structs, analyze as a
1720 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001721 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001722 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001723 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001724
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001725 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001726 if (!AllocSTy)
1727 return false;
1728
1729 // This the structure has an unreasonable number of fields, leave it
1730 // alone.
1731 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1732 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1733
1734 // If this is a fixed size array, transform the Malloc to be an alloc of
1735 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001736 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001737 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001738 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1739 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1740 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1741 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1742 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001743 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001744 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1745 CI->replaceAllUsesWith(Cast);
1746 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001747 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1748 CI = cast<CallInst>(BCI->getOperand(0));
1749 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001750 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001751 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001752
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001753 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1754 TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001755 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001756 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001757
Victor Hernandez83d63912009-09-18 22:35:49 +00001758 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001759}
Victor Hernandez83d63912009-09-18 22:35:49 +00001760
Chris Lattner9b34a612004-10-09 21:48:45 +00001761// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1762// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001763static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001764 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001765 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001766 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001767 // Ignore no-op GEPs and bitcasts.
1768 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001769
Chris Lattner708148e2004-10-10 23:14:11 +00001770 // If we are dealing with a pointer global that is initialized to null and
1771 // only has one (non-null) value stored into it, then we can optimize any
1772 // users of the loaded value (often calls and loads) that would trap if the
1773 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001774 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001775 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001776 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1777 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001778 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001779
Chris Lattner708148e2004-10-10 23:14:11 +00001780 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001781 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001782 return true;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001783 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1784 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001785 if (MallocType &&
1786 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1787 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001788 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001789 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001790 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001791
Chris Lattner9b34a612004-10-09 21:48:45 +00001792 return false;
1793}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001794
Chris Lattner58e44f42008-01-14 01:17:44 +00001795/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1796/// two values ever stored into GV are its initializer and OtherVal. See if we
1797/// can shrink the global into a boolean and select between the two values
1798/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001799static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001800 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001801
Chris Lattner58e44f42008-01-14 01:17:44 +00001802 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001803 // an FP value, pointer or vector, don't do this optimization because a select
1804 // between them is very expensive and unlikely to lead to later
1805 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1806 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001807 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001808 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001809 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001810 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001811
Chris Lattner58e44f42008-01-14 01:17:44 +00001812 // Walk the use list of the global seeing if all the uses are load or store.
1813 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001814 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1815 User *U = *I;
1816 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001817 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001818 }
1819
David Greene3215b0e2010-01-05 01:28:05 +00001820 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001821
Chris Lattner96a86b22004-12-12 05:53:50 +00001822 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001823 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1824 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001825 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001826 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001827 GV->getName()+".b",
Hans Wennborgce718ff2012-06-23 11:37:03 +00001828 GV->getThreadLocalMode());
Chris Lattner96a86b22004-12-12 05:53:50 +00001829 GV->getParent()->getGlobalList().insert(GV, NewGV);
1830
1831 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001832 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001833 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001834
1835 // If initialized to zero and storing one into the global, we can use a cast
1836 // instead of a select to synthesize the desired value.
1837 bool IsOneZero = false;
1838 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001839 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001840
1841 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001842 Instruction *UI = cast<Instruction>(GV->use_back());
1843 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001844 // Change the store into a boolean store.
1845 bool StoringOther = SI->getOperand(0) == OtherVal;
1846 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001847 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001848 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001849 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1850 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001851 else {
1852 // Otherwise, we are storing a previously loaded copy. To do this,
1853 // change the copy from copying the original value to just copying the
1854 // bool.
1855 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1856
Gabor Greif9e4f2432010-06-24 14:42:01 +00001857 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001858 // select instruction. If not, it will be a load of the original
1859 // global.
1860 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1861 assert(LI->getOperand(0) == GV && "Not a copy!");
1862 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001863 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1864 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001865 } else {
1866 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1867 "This is not a form that we understand!");
1868 StoreVal = StoredVal->getOperand(0);
1869 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1870 }
1871 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001872 new StoreInst(StoreVal, NewGV, false, 0,
1873 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001874 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001875 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001876 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001877 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1878 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001879 Value *NSI;
1880 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001881 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001882 else
Gabor Greif051a9502008-04-06 20:25:17 +00001883 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001884 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001885 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001886 }
1887 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001888 }
1889
1890 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001891 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001892}
1893
1894
Nick Lewyckydb292a62012-02-12 00:52:26 +00001895/// ProcessGlobal - Analyze the specified global variable and optimize it if
1896/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001897bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1898 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001899 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001900 return false;
1901
1902 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001903 GV->removeDeadConstantUsers();
1904
1905 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001906 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001907 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001908 ++NumDeleted;
1909 return true;
1910 }
1911
Rafael Espindola2f135d42012-06-15 18:00:24 +00001912 if (!GV->hasLocalLinkage())
1913 return false;
1914
Rafael Espindolac4440e32011-01-19 16:32:21 +00001915 SmallPtrSet<const PHINode*, 16> PHIUsers;
1916 GlobalStatus GS;
1917
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001918 if (AnalyzeGlobal(GV, GS, PHIUsers))
1919 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001920
Rafael Espindolac4440e32011-01-19 16:32:21 +00001921 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1922 GV->setUnnamedAddr(true);
1923 NumUnnamed++;
1924 }
1925
1926 if (GV->isConstant() || !GV->hasInitializer())
1927 return false;
1928
1929 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1930}
1931
1932/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1933/// it if possible. If we make a change, return true.
1934bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1935 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001936 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001937 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001938 // If this is a first class global and has only one accessing function
1939 // and this function is main (which we know is not recursive we can make
1940 // this global a local variable) we replace the global with a local alloca
1941 // in this function.
1942 //
1943 // NOTE: It doesn't make sense to promote non single-value types since we
1944 // are just replacing static memory to stack memory.
1945 //
1946 // If the global is in different address space, don't bring it to stack.
1947 if (!GS.HasMultipleAccessingFunctions &&
1948 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1949 GV->getType()->getElementType()->isSingleValueType() &&
1950 GS.AccessingFunction->getName() == "main" &&
1951 GS.AccessingFunction->hasExternalLinkage() &&
1952 GV->getType()->getAddressSpace() == 0) {
1953 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001954 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001955 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001956 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001957 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001958 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001959 if (!isa<UndefValue>(GV->getInitializer()))
1960 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001961
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001962 GV->replaceAllUsesWith(Alloca);
1963 GV->eraseFromParent();
1964 ++NumLocalized;
1965 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001966 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001967
1968 // If the global is never loaded (but may be stored to), it is dead.
1969 // Delete it now.
1970 if (!GS.isLoaded) {
1971 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1972
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001973 bool Changed;
1974 if (isLeakCheckerRoot(GV)) {
1975 // Delete any constant stores to the global.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001976 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001977 } else {
1978 // Delete any stores we can find to the global. We may not be able to
1979 // make it completely dead though.
1980 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1981 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001982
1983 // If the global is dead now, delete it.
1984 if (GV->use_empty()) {
1985 GV->eraseFromParent();
1986 ++NumDeleted;
1987 Changed = true;
1988 }
1989 return Changed;
1990
1991 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1992 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1993 GV->setConstant(true);
1994
1995 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001996 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001997
1998 // If the global is dead now, just nuke it.
1999 if (GV->use_empty()) {
2000 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
2001 << "all users and delete global!\n");
2002 GV->eraseFromParent();
2003 ++NumDeleted;
2004 }
2005
2006 ++NumMarked;
2007 return true;
2008 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmow3574eca2012-10-08 16:38:25 +00002009 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002010 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
2011 GVI = FirstNewGV; // Don't skip the newly produced globals!
2012 return true;
2013 }
2014 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
2015 // If the initial value for the global was an undef value, and if only
2016 // one other value was stored into it, we can just change the
2017 // initializer to be the stored value, then delete all stores to the
2018 // global. This allows us to mark it constant.
2019 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2020 if (isa<UndefValue>(GV->getInitializer())) {
2021 // Change the initial value here.
2022 GV->setInitializer(SOVConstant);
2023
2024 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002025 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002026
2027 if (GV->use_empty()) {
2028 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00002029 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002030 GV->eraseFromParent();
2031 ++NumDeleted;
2032 } else {
2033 GVI = GV;
2034 }
2035 ++NumSubstitute;
2036 return true;
2037 }
2038
2039 // Try to optimize globals based on the knowledge that only one value
2040 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00002041 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00002042 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002043 return true;
2044
2045 // Otherwise, if the global was not a boolean, we can shrink it to be a
2046 // boolean.
2047 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2048 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
2049 ++NumShrunkToBool;
2050 return true;
2051 }
2052 }
2053
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002054 return false;
2055}
2056
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002057/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2058/// function, changing them to FastCC.
2059static void ChangeCalleesToFastCall(Function *F) {
2060 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002061 if (isa<BlockAddress>(*UI))
2062 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002063 CallSite User(cast<Instruction>(*UI));
2064 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002065 }
2066}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002067
Bill Wendling99faa3b2012-12-07 23:16:57 +00002068static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00002069 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling67658342012-10-09 07:45:08 +00002070 if (!Attrs.getSlot(i).Attrs.hasAttribute(Attributes::Nest))
Duncan Sands548448a2008-02-18 17:32:13 +00002071 continue;
2072
Duncan Sands548448a2008-02-18 17:32:13 +00002073 // There can be only one.
Bill Wendling46d5dd92012-10-16 05:23:31 +00002074 return Attrs.removeAttr(C, Attrs.getSlot(i).Index,
2075 Attributes::get(C, Attributes::Nest));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002076 }
2077
2078 return Attrs;
2079}
2080
2081static void RemoveNestAttribute(Function *F) {
Bill Wendling5886b7b2012-10-14 06:39:53 +00002082 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002083 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002084 if (isa<BlockAddress>(*UI))
2085 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002086 CallSite User(cast<Instruction>(*UI));
Bill Wendling5886b7b2012-10-14 06:39:53 +00002087 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002088 }
2089}
2090
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002091bool GlobalOpt::OptimizeFunctions(Module &M) {
2092 bool Changed = false;
2093 // Optimize functions.
2094 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2095 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002096 // Functions without names cannot be referenced outside this module.
2097 if (!F->hasName() && !F->isDeclaration())
2098 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002099 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00002100 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00002101 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002102 Changed = true;
2103 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002104 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002105 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002106 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002107 // If this function has C calling conventions, is not a varargs
2108 // function, and is only called directly, promote it to use the Fast
2109 // calling convention.
2110 F->setCallingConv(CallingConv::Fast);
2111 ChangeCalleesToFastCall(F);
2112 ++NumFastCallFns;
2113 Changed = true;
2114 }
2115
Bill Wendling7d2f2492012-10-10 07:36:45 +00002116 if (F->getAttributes().hasAttrSomewhere(Attributes::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002117 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002118 // The function is not used by a trampoline intrinsic, so it is safe
2119 // to remove the 'nest' attribute.
2120 RemoveNestAttribute(F);
2121 ++NumNestRemoved;
2122 Changed = true;
2123 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002124 }
2125 }
2126 return Changed;
2127}
2128
2129bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2130 bool Changed = false;
2131 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2132 GVI != E; ) {
2133 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002134 // Global variables without names cannot be referenced outside this module.
2135 if (!GV->hasName() && !GV->isDeclaration())
2136 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002137 // Simplify the initializer.
2138 if (GV->hasInitializer())
2139 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00002140 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002141 if (New && New != CE)
2142 GV->setInitializer(New);
2143 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00002144
2145 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002146 }
2147 return Changed;
2148}
2149
Nick Lewycky2c44a802011-04-08 07:30:21 +00002150/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002151/// initializers have an init priority of 65535.
2152GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002153 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2154 if (GV == 0) return 0;
Jakub Staszak582088c2012-12-06 21:57:16 +00002155
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002156 // Verify that the initializer is simple enough for us to handle. We are
2157 // only allowed to optimize the initializer if it is unique.
2158 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002159
2160 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2161 return GV;
2162 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00002163
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002164 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002165 if (isa<ConstantAggregateZero>(*i))
2166 continue;
2167 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002168 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2169 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002170
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002171 // Must have a function or null ptr.
2172 if (!isa<Function>(CS->getOperand(1)))
2173 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002174
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002175 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00002176 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2177 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002178 return 0;
2179 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002180
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002181 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002182}
2183
Chris Lattnerdb973e62005-09-26 02:31:18 +00002184/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2185/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002186static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002187 if (GV->getInitializer()->isNullValue())
2188 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002189 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2190 std::vector<Function*> Result;
2191 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002192 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2193 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002194 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2195 }
2196 return Result;
2197}
2198
Chris Lattnerdb973e62005-09-26 02:31:18 +00002199/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2200/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002201static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002202 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002203 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002204 Constant *CSVals[2];
2205 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2206 CSVals[1] = 0;
2207
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002208 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002209 cast <StructType>(
2210 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002211
Chris Lattnerdb973e62005-09-26 02:31:18 +00002212 // Create the new init list.
2213 std::vector<Constant*> CAList;
2214 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002215 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002216 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002217 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002218 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002219 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002220 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002221 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002222 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002223 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002224 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002225 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002226 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002227
Chris Lattnerdb973e62005-09-26 02:31:18 +00002228 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002229 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002230 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002231
Chris Lattnerdb973e62005-09-26 02:31:18 +00002232 // If we didn't change the number of elements, don't create a new GV.
2233 if (CA->getType() == GCL->getInitializer()->getType()) {
2234 GCL->setInitializer(CA);
2235 return GCL;
2236 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002237
Chris Lattnerdb973e62005-09-26 02:31:18 +00002238 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002239 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002240 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002241 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002242 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002243 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002244
Chris Lattnerdb973e62005-09-26 02:31:18 +00002245 // Nuke the old list, replacing any uses with the new one.
2246 if (!GCL->use_empty()) {
2247 Constant *V = NGV;
2248 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002249 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002250 GCL->replaceAllUsesWith(V);
2251 }
2252 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002253
Chris Lattnerdb973e62005-09-26 02:31:18 +00002254 if (Ctors.size())
2255 return NGV;
2256 else
2257 return 0;
2258}
Chris Lattner79c11012005-09-26 04:44:35 +00002259
2260
Jakub Staszak582088c2012-12-06 21:57:16 +00002261static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002262isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002263 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002264 const DataLayout *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002265
2266
2267/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2268/// handled by the code generator. We don't want to generate something like:
2269/// void *X = &X/42;
2270/// because the code generator doesn't have a relocation that can handle that.
2271///
2272/// This function should be called if C was not found (but just got inserted)
2273/// in SimpleConstants to avoid having to rescan the same constants all the
2274/// time.
2275static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002276 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002277 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002278 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2279 // all supported.
2280 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2281 isa<GlobalValue>(C))
2282 return true;
Jakub Staszak582088c2012-12-06 21:57:16 +00002283
Chris Lattner1945d582010-12-07 04:33:29 +00002284 // Aggregate values are safe if all their elements are.
2285 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2286 isa<ConstantVector>(C)) {
2287 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2288 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002289 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002290 return false;
2291 }
2292 return true;
2293 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002294
Chris Lattner1945d582010-12-07 04:33:29 +00002295 // We don't know exactly what relocations are allowed in constant expressions,
2296 // so we allow &global+constantoffset, which is safe and uniformly supported
2297 // across targets.
2298 ConstantExpr *CE = cast<ConstantExpr>(C);
2299 switch (CE->getOpcode()) {
2300 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002301 // Bitcast is fine if the casted value is fine.
2302 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2303
Chris Lattner1945d582010-12-07 04:33:29 +00002304 case Instruction::IntToPtr:
2305 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002306 // int <=> ptr is fine if the int type is the same size as the
2307 // pointer type.
2308 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2309 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2310 return false;
2311 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002312
Chris Lattner1945d582010-12-07 04:33:29 +00002313 // GEP is fine if it is simple + constant offset.
2314 case Instruction::GetElementPtr:
2315 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2316 if (!isa<ConstantInt>(CE->getOperand(i)))
2317 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002318 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002319
Chris Lattner1945d582010-12-07 04:33:29 +00002320 case Instruction::Add:
2321 // We allow simple+cst.
2322 if (!isa<ConstantInt>(CE->getOperand(1)))
2323 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002324 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002325 }
2326 return false;
2327}
2328
Jakub Staszak582088c2012-12-06 21:57:16 +00002329static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002330isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002331 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002332 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002333 // If we already checked this constant, we win.
2334 if (!SimpleConstants.insert(C)) return true;
2335 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002336 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002337}
2338
2339
Chris Lattner79c11012005-09-26 04:44:35 +00002340/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002341/// enough for us to understand. In particular, if it is a cast to anything
2342/// other than from one pointer type to another pointer type, we punt.
2343/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002344/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002345static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002346 // Conservatively, avoid aggregate types. This is because we don't
2347 // want to worry about them partially overlapping other stores.
2348 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2349 return false;
2350
Dan Gohmanfd54a892009-09-07 22:31:26 +00002351 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002352 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002353 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002354 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002355
Owen Andersone95a32c2011-01-14 22:31:13 +00002356 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002357 // Handle a constantexpr gep.
2358 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002359 isa<GlobalVariable>(CE->getOperand(0)) &&
2360 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002361 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002362 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002363 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002364 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002365 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002366
Dan Gohman80bdc962009-09-07 22:44:55 +00002367 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002368 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002369 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002370
2371 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002372 // notional bounds of the corresponding static array types.
2373 if (!CE->isGEPWithNoNotionalOverIndexing())
2374 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002375
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002376 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak582088c2012-12-06 21:57:16 +00002377
Owen Andersoncff6b372011-01-14 22:19:20 +00002378 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2379 // and we know how to evaluate it by moving the bitcast from the pointer
2380 // operand to the value operand.
2381 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002382 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002383 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2384 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002385 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002386 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002387 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002388
Chris Lattner79c11012005-09-26 04:44:35 +00002389 return false;
2390}
2391
Chris Lattner798b4d52005-09-26 06:52:44 +00002392/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2393/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2394/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2395static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Shengefcdb292012-12-01 10:54:28 +00002396 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002397 // Base case of the recursion.
2398 if (OpNo == Addr->getNumOperands()) {
2399 assert(Val->getType() == Init->getType() && "Type mismatch!");
2400 return Val;
2401 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002402
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002403 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002404 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002405 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002406 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2407 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002408
Chris Lattner798b4d52005-09-26 06:52:44 +00002409 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002410 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2411 unsigned Idx = CU->getZExtValue();
2412 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Shengefcdb292012-12-01 10:54:28 +00002413 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002414
Chris Lattner798b4d52005-09-26 06:52:44 +00002415 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002416 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002417 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002418
Chris Lattnerb065b062011-06-20 04:01:31 +00002419 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002420 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002421
2422 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002423 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002424 NumElts = ATy->getNumElements();
2425 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002426 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002427
2428 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002429 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2430 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002431
2432 assert(CI->getZExtValue() < NumElts);
2433 Elts[CI->getZExtValue()] =
Zhou Shengefcdb292012-12-01 10:54:28 +00002434 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnerb065b062011-06-20 04:01:31 +00002435
2436 if (Init->getType()->isArrayTy())
2437 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2438 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002439}
2440
Chris Lattner79c11012005-09-26 04:44:35 +00002441/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2442/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002443static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002444 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2445 assert(GV->hasInitializer());
2446 GV->setInitializer(Val);
2447 return;
2448 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002449
Chris Lattner798b4d52005-09-26 06:52:44 +00002450 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2451 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Shengefcdb292012-12-01 10:54:28 +00002452 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002453}
2454
Nick Lewycky7fa76772012-02-20 03:25:59 +00002455namespace {
2456
2457/// Evaluator - This class evaluates LLVM IR, producing the Constant
2458/// representing each SSA instruction. Changes to global variables are stored
2459/// in a mapping that can be iterated over after the evaluation is complete.
2460/// Once an evaluation call fails, the evaluation object should not be reused.
2461class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002462public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002463 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002464 : TD(TD), TLI(TLI) {
2465 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2466 }
2467
Nick Lewycky7fa76772012-02-20 03:25:59 +00002468 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002469 DeleteContainerPointers(ValueStack);
2470 while (!AllocaTmps.empty()) {
2471 GlobalVariable *Tmp = AllocaTmps.back();
2472 AllocaTmps.pop_back();
2473
2474 // If there are still users of the alloca, the program is doing something
2475 // silly, e.g. storing the address of the alloca somewhere and using it
2476 // later. Since this is undefined, we'll just make it be null.
2477 if (!Tmp->use_empty())
2478 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2479 delete Tmp;
2480 }
2481 }
2482
2483 /// EvaluateFunction - Evaluate a call to function F, returning true if
2484 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2485 /// arguments for the function.
2486 bool EvaluateFunction(Function *F, Constant *&RetVal,
2487 const SmallVectorImpl<Constant*> &ActualArgs);
2488
2489 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2490 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2491 /// control flows into, or null upon return.
2492 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2493
2494 Constant *getVal(Value *V) {
2495 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2496 Constant *R = ValueStack.back()->lookup(V);
2497 assert(R && "Reference to an uncomputed value!");
2498 return R;
2499 }
2500
2501 void setVal(Value *V, Constant *C) {
2502 ValueStack.back()->operator[](V) = C;
2503 }
2504
2505 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2506 return MutatedMemory;
2507 }
2508
2509 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2510 return Invariants;
2511 }
2512
2513private:
2514 Constant *ComputeLoadResult(Constant *P);
2515
2516 /// ValueStack - As we compute SSA register values, we store their contents
2517 /// here. The back of the vector contains the current function and the stack
2518 /// contains the values in the calling frames.
2519 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2520
2521 /// CallStack - This is used to detect recursion. In pathological situations
2522 /// we could hit exponential behavior, but at least there is nothing
2523 /// unbounded.
2524 SmallVector<Function*, 4> CallStack;
2525
2526 /// MutatedMemory - For each store we execute, we update this map. Loads
2527 /// check this to get the most up-to-date value. If evaluation is successful,
2528 /// this state is committed to the process.
2529 DenseMap<Constant*, Constant*> MutatedMemory;
2530
2531 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2532 /// to represent its body. This vector is needed so we can delete the
2533 /// temporary globals when we are done.
2534 SmallVector<GlobalVariable*, 32> AllocaTmps;
2535
2536 /// Invariants - These global variables have been marked invariant by the
2537 /// static constructor.
2538 SmallPtrSet<GlobalVariable*, 8> Invariants;
2539
2540 /// SimpleConstants - These are constants we have checked and know to be
2541 /// simple enough to live in a static initializer of a global.
2542 SmallPtrSet<Constant*, 8> SimpleConstants;
2543
Micah Villmow3574eca2012-10-08 16:38:25 +00002544 const DataLayout *TD;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002545 const TargetLibraryInfo *TLI;
2546};
2547
Nick Lewycky7fa76772012-02-20 03:25:59 +00002548} // anonymous namespace
2549
Chris Lattner562a0552005-09-26 05:16:34 +00002550/// ComputeLoadResult - Return the value that would be computed by a load from
2551/// P after the stores reflected by 'memory' have been performed. If we can't
2552/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002553Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002554 // If this memory location has been recently stored, use the stored value: it
2555 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002556 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2557 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002558
Chris Lattner04de1cf2005-09-26 05:15:37 +00002559 // Access it.
2560 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002561 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002562 return GV->getInitializer();
2563 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002564 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002565
Chris Lattner798b4d52005-09-26 06:52:44 +00002566 // Handle a constantexpr getelementptr.
2567 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2568 if (CE->getOpcode() == Instruction::GetElementPtr &&
2569 isa<GlobalVariable>(CE->getOperand(0))) {
2570 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002571 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002572 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002573 }
2574
2575 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002576}
2577
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002578/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2579/// successful, false if we can't evaluate it. NewBB returns the next BB that
2580/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002581bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2582 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002583 // This is the main evaluation loop.
2584 while (1) {
2585 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002586
Chris Lattner79c11012005-09-26 04:44:35 +00002587 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002588 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002589 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002590 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2591 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002592 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002593 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002594 return false;
Jakub Staszak582088c2012-12-06 21:57:16 +00002595
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002596 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002597
2598 // If this might be too difficult for the backend to handle (e.g. the addr
2599 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002600 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002601 return false;
Jakub Staszak582088c2012-12-06 21:57:16 +00002602
Owen Andersoncff6b372011-01-14 22:19:20 +00002603 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2604 if (CE->getOpcode() == Instruction::BitCast) {
2605 // If we're evaluating a store through a bitcast, then we need
2606 // to pull the bitcast off the pointer type and push it onto the
2607 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002608 Ptr = CE->getOperand(0);
Jakub Staszak582088c2012-12-06 21:57:16 +00002609
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002610 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak582088c2012-12-06 21:57:16 +00002611
Owen Anderson66f708f2011-01-16 04:33:33 +00002612 // In order to push the bitcast onto the stored value, a bitcast
2613 // from NewTy to Val's type must be legal. If it's not, we can try
2614 // introspecting NewTy to find a legal conversion.
2615 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2616 // If NewTy is a struct, we can convert the pointer to the struct
2617 // into a pointer to its first member.
2618 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002619 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002620 NewTy = STy->getTypeAtIndex(0U);
2621
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002622 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002623 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2624 Constant * const IdxList[] = {IdxZero, IdxZero};
2625
Jay Foadb4263a62011-07-22 08:52:50 +00002626 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002627 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2628 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2629
Owen Anderson66f708f2011-01-16 04:33:33 +00002630 // If we can't improve the situation by introspecting NewTy,
2631 // we have to give up.
2632 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002633 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002634 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002635 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002636
Owen Anderson66f708f2011-01-16 04:33:33 +00002637 // If we found compatible types, go ahead and push the bitcast
2638 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002639 Val = ConstantExpr::getBitCast(Val, NewTy);
2640 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002641
Chris Lattner79c11012005-09-26 04:44:35 +00002642 MutatedMemory[Ptr] = Val;
2643 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002644 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002645 getVal(BO->getOperand(0)),
2646 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002647 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002648 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002649 getVal(CI->getOperand(0)),
2650 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002651 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002652 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002653 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002654 CI->getType());
2655 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002656 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2657 getVal(SI->getOperand(1)),
2658 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002659 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002660 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002661 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002662 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2663 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002664 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002665 InstResult =
2666 ConstantExpr::getGetElementPtr(P, GEPOps,
2667 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002668 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002669 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002670 Constant *Ptr = getVal(LI->getOperand(0));
2671 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2672 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2673 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002674 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002675 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002676 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002677 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002678 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002679 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002680 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002681 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002682 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002683 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2684 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002685
2686 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002687 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002688 ++CurInst;
2689 continue;
2690 }
2691
Chris Lattner7cd580f2006-07-07 21:37:01 +00002692 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002693 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002694
Nick Lewycky81266c52012-02-17 06:59:21 +00002695 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2696 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2697 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002698 Constant *Ptr = getVal(MSI->getDest());
2699 Constant *Val = getVal(MSI->getValue());
2700 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002701 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2702 // This memset is a no-op.
2703 ++CurInst;
2704 continue;
2705 }
2706 }
2707
2708 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2709 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2710 ++CurInst;
2711 continue;
2712 }
2713
2714 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2715 // We don't insert an entry into Values, as it doesn't have a
2716 // meaningful return value.
2717 if (!II->use_empty())
2718 return false;
2719 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002720 Value *PtrArg = getVal(II->getArgOperand(1));
2721 Value *Ptr = PtrArg->stripPointerCasts();
2722 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2723 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2724 if (!Size->isAllOnesValue() &&
2725 Size->getValue().getLimitedValue() >=
2726 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002727 Invariants.insert(GV);
2728 }
2729 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002730 ++CurInst;
2731 continue;
2732 }
2733 return false;
2734 }
2735
Chris Lattnercd271422005-09-27 04:45:34 +00002736 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002737 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002738 if (!Callee || Callee->mayBeOverridden())
2739 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002740
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002741 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002742 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002743 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002744
Reid Spencer5cbf9852007-01-30 20:08:39 +00002745 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002746 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002747 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002748 InstResult = C;
2749 } else {
2750 return false;
2751 }
2752 } else {
2753 if (Callee->getFunctionType()->isVarArg())
2754 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002755
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002756 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002757 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002758 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2759 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002760 return false;
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002761 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002762 InstResult = RetVal;
2763 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002764 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002765 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2766 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002767 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002768 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002769 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002770 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002771 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002772
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002773 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002774 }
2775 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2776 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002777 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002778 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002779 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002780 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002781 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002782 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002783 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002784 else
2785 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002786 } else if (isa<ReturnInst>(CurInst)) {
2787 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002788 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002789 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002790 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002791 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002792
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002793 // We succeeded at evaluating this block!
2794 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002795 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002796 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002797 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002798 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002799
Chris Lattner1945d582010-12-07 04:33:29 +00002800 if (!CurInst->use_empty()) {
2801 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002802 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Jakub Staszak582088c2012-12-06 21:57:16 +00002803
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002804 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002805 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002806
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002807 // If we just processed an invoke, we finished evaluating the block.
2808 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2809 NextBB = II->getNormalDest();
2810 return true;
2811 }
2812
Chris Lattner79c11012005-09-26 04:44:35 +00002813 // Advance program counter.
2814 ++CurInst;
2815 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002816}
2817
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002818/// EvaluateFunction - Evaluate a call to function F, returning true if
2819/// successful, false if we can't evaluate it. ActualArgs contains the formal
2820/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002821bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2822 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002823 // Check to see if this function is already executing (recursion). If so,
2824 // bail out. TODO: we might want to accept limited recursion.
2825 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2826 return false;
2827
2828 CallStack.push_back(F);
2829
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002830 // Initialize arguments to the incoming values specified.
2831 unsigned ArgNo = 0;
2832 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2833 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002834 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002835
2836 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2837 // we can only evaluate any one basic block at most once. This set keeps
2838 // track of what we have executed so we can detect recursive cases etc.
2839 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2840
2841 // CurBB - The current basic block we're evaluating.
2842 BasicBlock *CurBB = F->begin();
2843
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002844 BasicBlock::iterator CurInst = CurBB->begin();
2845
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002846 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002847 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002848 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002849 return false;
2850
2851 if (NextBB == 0) {
2852 // Successfully running until there's no next block means that we found
2853 // the return. Fill it the return value and pop the call stack.
2854 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2855 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002856 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002857 CallStack.pop_back();
2858 return true;
2859 }
2860
2861 // Okay, we succeeded in evaluating this control flow. See if we have
2862 // executed the new block before. If so, we have a looping function,
2863 // which we cannot evaluate in reasonable time.
2864 if (!ExecutedBlocks.insert(NextBB))
2865 return false; // looped!
2866
2867 // Okay, we have never been in this block before. Check to see if there
2868 // are any PHI nodes. If so, evaluate them with information about where
2869 // we came from.
2870 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002871 for (CurInst = NextBB->begin();
2872 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002873 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002874
2875 // Advance to the next block.
2876 CurBB = NextBB;
2877 }
2878}
2879
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002880/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2881/// we can. Return true if we can, false otherwise.
Micah Villmow3574eca2012-10-08 16:38:25 +00002882static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosier00737bd2011-12-01 21:29:16 +00002883 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002884 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002885 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002886 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002887 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2888 SmallVector<Constant*, 0>());
Jakub Staszak582088c2012-12-06 21:57:16 +00002889
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002890 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002891 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002892 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002893 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002894 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002895 for (DenseMap<Constant*, Constant*>::const_iterator I =
2896 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002897 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002898 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002899 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2900 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2901 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002902 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002903 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002904
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002905 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002906}
2907
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002908/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2909/// Return true if anything changed.
2910bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2911 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2912 bool MadeChange = false;
2913 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002914
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002915 // Loop over global ctors, optimizing them when we can.
2916 for (unsigned i = 0; i != Ctors.size(); ++i) {
2917 Function *F = Ctors[i];
2918 // Found a null terminator in the middle of the list, prune off the rest of
2919 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002920 if (F == 0) {
2921 if (i != Ctors.size()-1) {
2922 Ctors.resize(i+1);
2923 MadeChange = true;
2924 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002925 break;
2926 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002927
Chris Lattner79c11012005-09-26 04:44:35 +00002928 // We cannot simplify external ctor functions.
2929 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002930
Chris Lattner79c11012005-09-26 04:44:35 +00002931 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002932 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002933 Ctors.erase(Ctors.begin()+i);
2934 MadeChange = true;
2935 --i;
2936 ++NumCtorsEvaluated;
2937 continue;
2938 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002939 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002940
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002941 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002942
Chris Lattner7b550cc2009-11-06 04:27:31 +00002943 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002944 return true;
2945}
2946
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002947bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002948 bool Changed = false;
2949
Duncan Sands177d84e2009-01-07 20:01:06 +00002950 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002951 I != E;) {
2952 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002953 // Aliases without names cannot be referenced outside this module.
2954 if (!J->hasName() && !J->isDeclaration())
2955 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002956 // If the aliasee may change at link time, nothing can be done - bail out.
2957 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002958 continue;
2959
Duncan Sands4782b302009-02-15 09:56:08 +00002960 Constant *Aliasee = J->getAliasee();
2961 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002962 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002963 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2964
2965 // Make all users of the alias use the aliasee instead.
2966 if (!J->use_empty()) {
2967 J->replaceAllUsesWith(Aliasee);
2968 ++NumAliasesResolved;
2969 Changed = true;
2970 }
2971
Duncan Sands7a154cf2009-12-08 10:10:20 +00002972 // If the alias is externally visible, we may still be able to simplify it.
2973 if (!J->hasLocalLinkage()) {
2974 // If the aliasee has internal linkage, give it the name and linkage
2975 // of the alias, and delete the alias. This turns:
2976 // define internal ... @f(...)
2977 // @a = alias ... @f
2978 // into:
2979 // define ... @a(...)
2980 if (!Target->hasLocalLinkage())
2981 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002982
Duncan Sands7a154cf2009-12-08 10:10:20 +00002983 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002984 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002985 // and other attributes of the aliasee with those of the alias.
2986 if (!hasOneUse)
2987 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002988
Duncan Sands7a154cf2009-12-08 10:10:20 +00002989 // Give the aliasee the name, linkage and other attributes of the alias.
2990 Target->takeName(J);
2991 Target->setLinkage(J->getLinkage());
2992 Target->GlobalValue::copyAttributesFrom(J);
2993 }
Duncan Sands4782b302009-02-15 09:56:08 +00002994
2995 // Delete the alias.
2996 M.getAliasList().erase(J);
2997 ++NumAliasesRemoved;
2998 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002999 }
3000
3001 return Changed;
3002}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003003
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003004static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3005 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00003006 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003007
3008 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak582088c2012-12-06 21:57:16 +00003009
Anders Carlssona201c4c2011-03-20 17:59:11 +00003010 if (!Fn)
3011 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003012
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003013 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak582088c2012-12-06 21:57:16 +00003014
3015 // Checking that the function has the right return type, the right number of
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003016 // parameters and that they all have pointer types should be enough.
3017 if (!FTy->getReturnType()->isIntegerTy() ||
3018 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003019 !FTy->getParamType(0)->isPointerTy() ||
3020 !FTy->getParamType(1)->isPointerTy() ||
3021 !FTy->getParamType(2)->isPointerTy())
3022 return 0;
3023
3024 return Fn;
3025}
3026
3027/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3028/// destructor and can therefore be eliminated.
3029/// Note that we assume that other optimization passes have already simplified
3030/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003031/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3032/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003033static bool cxxDtorIsEmpty(const Function &Fn,
3034 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003035 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003036 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003037 if (Fn.isDeclaration())
3038 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003039
3040 if (++Fn.begin() != Fn.end())
3041 return false;
3042
3043 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3044 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3045 I != E; ++I) {
3046 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003047 // Ignore debug intrinsics.
3048 if (isa<DbgInfoIntrinsic>(CI))
3049 continue;
3050
Anders Carlssona201c4c2011-03-20 17:59:11 +00003051 const Function *CalledFn = CI->getCalledFunction();
3052
3053 if (!CalledFn)
3054 return false;
3055
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003056 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3057
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003058 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003059 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003060 return false;
3061
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003062 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003063 return false;
3064 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003065 return true; // We're done.
3066 else if (I->mayHaveSideEffects())
3067 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003068 }
3069
3070 return false;
3071}
3072
3073bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3074 /// Itanium C++ ABI p3.3.5:
3075 ///
3076 /// After constructing a global (or local static) object, that will require
3077 /// destruction on exit, a termination function is registered as follows:
3078 ///
3079 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3080 ///
3081 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3082 /// call f(p) when DSO d is unloaded, before all such termination calls
3083 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003084 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003085
3086 // This pass will look for calls to __cxa_atexit where the function is trivial
3087 // and remove them.
3088 bool Changed = false;
3089
Jakub Staszak582088c2012-12-06 21:57:16 +00003090 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
Anders Carlssona201c4c2011-03-20 17:59:11 +00003091 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003092 // We're only interested in calls. Theoretically, we could handle invoke
3093 // instructions as well, but neither llvm-gcc nor clang generate invokes
3094 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003095 CallInst *CI = dyn_cast<CallInst>(*I++);
3096 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003097 continue;
3098
Jakub Staszak582088c2012-12-06 21:57:16 +00003099 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003100 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003101 if (!DtorFn)
3102 continue;
3103
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003104 SmallPtrSet<const Function *, 8> CalledFunctions;
3105 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003106 continue;
3107
3108 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003109 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3110 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003111
Anders Carlssona201c4c2011-03-20 17:59:11 +00003112 ++NumCXXDtorsRemoved;
3113
3114 Changed |= true;
3115 }
3116
3117 return Changed;
3118}
3119
Chris Lattner7a90b682004-10-07 04:16:33 +00003120bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003121 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003122
Micah Villmow3574eca2012-10-08 16:38:25 +00003123 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003124 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003125
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003126 // Try to find the llvm.globalctors list.
3127 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003128
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003129 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003130
Chris Lattner7a90b682004-10-07 04:16:33 +00003131 bool LocalChange = true;
3132 while (LocalChange) {
3133 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003134
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003135 // Delete functions that are trivially dead, ccc -> fastcc
3136 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003137
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003138 // Optimize global_ctors list.
3139 if (GlobalCtors)
3140 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003141
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003142 // Optimize non-address-taken globals.
3143 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003144
3145 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003146 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003147
3148 // Try to remove trivial global destructors.
3149 if (CXAAtExitFn)
3150 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3151
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003152 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003153 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003154
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003155 // TODO: Move all global ctors functions to the end of the module for code
3156 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003157
Chris Lattner079236d2004-02-25 21:34:36 +00003158 return Changed;
3159}