blob: 72623a36e509b51600a91dbc0a226204250131f6 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
Jay Foad562b84b2011-04-11 09:35:34 +000024#include "llvm/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000025#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000027#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000028#include "llvm/Target/TargetData.h"
Chad Rosier00737bd2011-12-01 21:29:16 +000029#include "llvm/Target/TargetLibraryInfo.h"
Duncan Sands548448a2008-02-18 17:32:13 +000030#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000034#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000040#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000041#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000042using namespace llvm;
43
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000045STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000046STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49STATISTIC(NumDeleted , "Number of globals deleted");
50STATISTIC(NumFnDeleted , "Number of functions deleted");
51STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52STATISTIC(NumLocalized , "Number of globals localized");
53STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000056STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000057STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000059STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000060
Chris Lattner86453c52006-12-19 22:09:18 +000061namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000062 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000065 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000066 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000068 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
70 }
Misha Brukmanfd939082005-04-21 23:48:37 +000071
Chris Lattnerb12914b2004-09-20 04:48:05 +000072 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000073
74 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000075 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000078 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000079 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000080 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewycky6a577f82012-02-12 01:13:18 +000085
86 TargetData *TD;
87 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
Chris Lattner25de4e52006-11-01 18:03:33 +0000151 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
152 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000153
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000154 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
155 AtomicOrdering Ordering;
156
Rafael Espindolac4440e32011-01-19 16:32:21 +0000157 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
158 StoredOnceValue(0), AccessingFunction(0),
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000159 HasMultipleAccessingFunctions(false),
160 HasNonInstructionUser(false), HasPHIUser(false),
161 Ordering(NotAtomic) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000162};
Chris Lattnere47ba742004-10-06 20:57:02 +0000163
Dan Gohman844731a2008-05-13 00:00:25 +0000164}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000165
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000166/// StrongerOrdering - Return the stronger of the two ordering. If the two
167/// orderings are acquire and release, then return AcquireRelease.
168///
169static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
170 if (X == Acquire && Y == Release) return AcquireRelease;
171 if (Y == Acquire && X == Release) return AcquireRelease;
172 return (AtomicOrdering)std::max(X, Y);
173}
174
Nick Lewyckybc384a12012-02-05 19:48:37 +0000175/// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
176/// by constants itself. Note that constants cannot be cyclic, so this test is
177/// pretty easy to implement recursively.
178///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000179static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000180 if (isa<GlobalValue>(C)) return false;
181
Gabor Greif27236912010-04-07 18:59:26 +0000182 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
183 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000184 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000185 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000186 } else
187 return false;
188 return true;
189}
190
191
Chris Lattner7a90b682004-10-07 04:16:33 +0000192/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
193/// structure. If the global has its address taken, return true to indicate we
194/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000195///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000196static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
197 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000198 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000199 ++UI) {
200 const User *U = *UI;
201 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000202 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000203
204 // If the result of the constantexpr isn't pointer type, then we won't
205 // know to expect it in various places. Just reject early.
206 if (!isa<PointerType>(CE->getType())) return true;
207
Chris Lattner7a90b682004-10-07 04:16:33 +0000208 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000209 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000210 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000211 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000212 if (GS.AccessingFunction == 0)
213 GS.AccessingFunction = F;
214 else if (GS.AccessingFunction != F)
215 GS.HasMultipleAccessingFunctions = true;
216 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000217 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000218 GS.isLoaded = true;
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000219 // Don't hack on volatile loads.
220 if (LI->isVolatile()) return true;
221 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000222 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000223 // Don't allow a store OF the address, only stores TO the address.
224 if (SI->getOperand(0) == V) return true;
225
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000226 // Don't hack on volatile stores.
227 if (SI->isVolatile()) return true;
228 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000229
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000230 // If this is a direct store to the global (i.e., the global is a scalar
231 // value, not an aggregate), keep more specific information about
232 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000233 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000234 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
235 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000236 Value *StoredVal = SI->getOperand(0);
237 if (StoredVal == GV->getInitializer()) {
238 if (GS.StoredType < GlobalStatus::isInitializerStored)
239 GS.StoredType = GlobalStatus::isInitializerStored;
240 } else if (isa<LoadInst>(StoredVal) &&
241 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000242 if (GS.StoredType < GlobalStatus::isInitializerStored)
243 GS.StoredType = GlobalStatus::isInitializerStored;
244 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
245 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000246 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000247 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000248 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000249 // noop.
250 } else {
251 GS.StoredType = GlobalStatus::isStored;
252 }
253 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000254 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000255 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000256 }
Duncan Sandsb2fe7f12012-07-02 18:55:39 +0000257 } else if (isa<BitCastInst>(I)) {
258 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000259 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000260 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000261 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000262 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000263 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000264 // PHI nodes we can check just like select or GEP instructions, but we
265 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000266 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000267 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000268 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000269 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000270 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000271 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
272 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000273 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000274 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000275 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000276 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000277 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
278 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
279 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000280 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000281 } else {
282 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000283 }
Gabor Greife6642672010-07-09 16:51:20 +0000284 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000285 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000286 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000287 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000288 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000289 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000290 GS.HasNonInstructionUser = true;
291 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000292 return true;
293 }
Gabor Greife6642672010-07-09 16:51:20 +0000294 }
Chris Lattner079236d2004-02-25 21:34:36 +0000295
296 return false;
297}
298
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000299/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
300/// as a root? If so, we might not really want to eliminate the stores to it.
301static bool isLeakCheckerRoot(GlobalVariable *GV) {
302 // A global variable is a root if it is a pointer, or could plausibly contain
303 // a pointer. There are two challenges; one is that we could have a struct
304 // the has an inner member which is a pointer. We recurse through the type to
305 // detect these (up to a point). The other is that we may actually be a union
306 // of a pointer and another type, and so our LLVM type is an integer which
307 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
308 // potentially contained here.
309
310 if (GV->hasPrivateLinkage())
311 return false;
312
313 SmallVector<Type *, 4> Types;
314 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
315
316 unsigned Limit = 20;
317 do {
318 Type *Ty = Types.pop_back_val();
319 switch (Ty->getTypeID()) {
320 default: break;
321 case Type::PointerTyID: return true;
322 case Type::ArrayTyID:
323 case Type::VectorTyID: {
324 SequentialType *STy = cast<SequentialType>(Ty);
325 Types.push_back(STy->getElementType());
326 break;
327 }
328 case Type::StructTyID: {
329 StructType *STy = cast<StructType>(Ty);
330 if (STy->isOpaque()) return true;
331 for (StructType::element_iterator I = STy->element_begin(),
332 E = STy->element_end(); I != E; ++I) {
333 Type *InnerTy = *I;
334 if (isa<PointerType>(InnerTy)) return true;
335 if (isa<CompositeType>(InnerTy))
336 Types.push_back(InnerTy);
337 }
338 break;
339 }
340 }
341 if (--Limit == 0) return true;
342 } while (!Types.empty());
343 return false;
344}
345
346/// Given a value that is stored to a global but never read, determine whether
347/// it's safe to remove the store and the chain of computation that feeds the
348/// store.
349static bool IsSafeComputationToRemove(Value *V) {
350 do {
351 if (isa<Constant>(V))
352 return true;
353 if (!V->hasOneUse())
354 return false;
355 if (isa<LoadInst>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
356 return false;
357 if (isAllocationFn(V))
358 return true;
359
360 Instruction *I = cast<Instruction>(V);
361 if (I->mayHaveSideEffects())
362 return false;
363 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
364 if (!GEP->hasAllConstantIndices())
365 return false;
366 } else if (I->getNumOperands() != 1) {
367 return false;
368 }
369
370 V = I->getOperand(0);
371 } while (1);
372}
373
374/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
375/// of the global and clean up any that obviously don't assign the global a
376/// value that isn't dynamically allocated.
377///
378static bool CleanupPointerRootUsers(GlobalVariable *GV) {
379 // A brief explanation of leak checkers. The goal is to find bugs where
380 // pointers are forgotten, causing an accumulating growth in memory
381 // usage over time. The common strategy for leak checkers is to whitelist the
382 // memory pointed to by globals at exit. This is popular because it also
383 // solves another problem where the main thread of a C++ program may shut down
384 // before other threads that are still expecting to use those globals. To
385 // handle that case, we expect the program may create a singleton and never
386 // destroy it.
387
388 bool Changed = false;
389
390 // If Dead[n].first is the only use of a malloc result, we can delete its
391 // chain of computation and the store to the global in Dead[n].second.
392 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
393
394 // Constants can't be pointers to dynamically allocated memory.
395 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
396 UI != E;) {
397 User *U = *UI++;
398 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
399 Value *V = SI->getValueOperand();
400 if (isa<Constant>(V)) {
401 Changed = true;
402 SI->eraseFromParent();
403 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
404 if (I->hasOneUse())
405 Dead.push_back(std::make_pair(I, SI));
406 }
407 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
408 if (isa<Constant>(MSI->getValue())) {
409 Changed = true;
410 MSI->eraseFromParent();
411 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
412 if (I->hasOneUse())
413 Dead.push_back(std::make_pair(I, MSI));
414 }
415 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
416 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
417 if (MemSrc && MemSrc->isConstant()) {
418 Changed = true;
419 MTI->eraseFromParent();
420 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
421 if (I->hasOneUse())
422 Dead.push_back(std::make_pair(I, MTI));
423 }
424 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
425 if (CE->use_empty()) {
426 CE->destroyConstant();
427 Changed = true;
428 }
429 } else if (Constant *C = dyn_cast<Constant>(U)) {
430 if (SafeToDestroyConstant(C)) {
431 C->destroyConstant();
432 // This could have invalidated UI, start over from scratch.
433 Dead.clear();
434 CleanupPointerRootUsers(GV);
435 return true;
436 }
437 }
438 }
439
440 for (int i = 0, e = Dead.size(); i != e; ++i) {
441 if (IsSafeComputationToRemove(Dead[i].first)) {
442 Dead[i].second->eraseFromParent();
443 Instruction *I = Dead[i].first;
444 do {
Nick Lewycky952f5d52012-07-24 21:33:00 +0000445 if (isAllocationFn(I))
446 break;
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000447 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
448 if (!J)
449 break;
450 I->eraseFromParent();
451 I = J;
Nick Lewycky952f5d52012-07-24 21:33:00 +0000452 } while (1);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000453 I->eraseFromParent();
454 }
455 }
456
457 return Changed;
458}
459
Chris Lattnere47ba742004-10-06 20:57:02 +0000460/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
461/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000462/// quick scan over the use list to clean up the easy and obvious cruft. This
463/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000464static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
465 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000466 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000467 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
468 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000469
Chris Lattner7a90b682004-10-07 04:16:33 +0000470 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000471 if (Init) {
472 // Replace the load with the initializer.
473 LI->replaceAllUsesWith(Init);
474 LI->eraseFromParent();
475 Changed = true;
476 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000477 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000478 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000479 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000480 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000481 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
482 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000483 Constant *SubInit = 0;
484 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000485 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000486 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000487 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000488 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000489 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000490 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000491 }
492
493 if (CE->use_empty()) {
494 CE->destroyConstant();
495 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000496 }
497 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000498 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
499 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
500 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000501 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000502 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000503 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000504 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000505 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000506 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000507
508 // If the initializer is an all-null value and we have an inbounds GEP,
509 // we already know what the result of any load from that GEP is.
510 // TODO: Handle splats.
511 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
512 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000513 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000514 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000515
Chris Lattner031955d2004-10-10 16:43:46 +0000516 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000517 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000518 Changed = true;
519 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000520 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
521 if (MI->getRawDest() == V) {
522 MI->eraseFromParent();
523 Changed = true;
524 }
525
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000526 } else if (Constant *C = dyn_cast<Constant>(U)) {
527 // If we have a chain of dead constantexprs or other things dangling from
528 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000529 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000530 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000531 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000532 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000533 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000534 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000535 }
536 }
Chris Lattner031955d2004-10-10 16:43:46 +0000537 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000538}
539
Chris Lattner941db492008-01-14 02:09:12 +0000540/// isSafeSROAElementUse - Return true if the specified instruction is a safe
541/// user of a derived expression from a global that we want to SROA.
542static bool isSafeSROAElementUse(Value *V) {
543 // We might have a dead and dangling constant hanging off of here.
544 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000545 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000546
Chris Lattner941db492008-01-14 02:09:12 +0000547 Instruction *I = dyn_cast<Instruction>(V);
548 if (!I) return false;
549
550 // Loads are ok.
551 if (isa<LoadInst>(I)) return true;
552
553 // Stores *to* the pointer are ok.
554 if (StoreInst *SI = dyn_cast<StoreInst>(I))
555 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000556
Chris Lattner941db492008-01-14 02:09:12 +0000557 // Otherwise, it must be a GEP.
558 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
559 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000560
Chris Lattner941db492008-01-14 02:09:12 +0000561 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
562 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
563 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000564
Chris Lattner941db492008-01-14 02:09:12 +0000565 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
566 I != E; ++I)
567 if (!isSafeSROAElementUse(*I))
568 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000569 return true;
570}
571
Chris Lattner941db492008-01-14 02:09:12 +0000572
573/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
574/// Look at it and its uses and decide whether it is safe to SROA this global.
575///
576static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
577 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000578 if (!isa<GetElementPtrInst>(U) &&
579 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000580 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
581 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000582
Chris Lattner941db492008-01-14 02:09:12 +0000583 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
584 // don't like < 3 operand CE's, and we don't like non-constant integer
585 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
586 // value of C.
587 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
588 !cast<Constant>(U->getOperand(1))->isNullValue() ||
589 !isa<ConstantInt>(U->getOperand(2)))
590 return false;
591
592 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
593 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000594
Chris Lattner941db492008-01-14 02:09:12 +0000595 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000596 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000597 uint64_t NumElements = AT->getNumElements();
598 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000599
Chris Lattner941db492008-01-14 02:09:12 +0000600 // Check to make sure that index falls within the array. If not,
601 // something funny is going on, so we won't do the optimization.
602 //
603 if (Idx->getZExtValue() >= NumElements)
604 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000605
Chris Lattner941db492008-01-14 02:09:12 +0000606 // We cannot scalar repl this level of the array unless any array
607 // sub-indices are in-range constants. In particular, consider:
608 // A[0][i]. We cannot know that the user isn't doing invalid things like
609 // allowing i to index an out-of-range subscript that accesses A[1].
610 //
611 // Scalar replacing *just* the outer index of the array is probably not
612 // going to be a win anyway, so just give up.
613 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000614 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000615 ++GEPI) {
616 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000617 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000618 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000619 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000620 NumElements = SubVectorTy->getNumElements();
621 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000622 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000623 "Indexed GEP type is not array, vector, or struct!");
624 continue;
625 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000626
Chris Lattner941db492008-01-14 02:09:12 +0000627 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
628 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
629 return false;
630 }
631 }
632
633 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
634 if (!isSafeSROAElementUse(*I))
635 return false;
636 return true;
637}
638
639/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
640/// is safe for us to perform this transformation.
641///
642static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
643 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
644 UI != E; ++UI) {
645 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
646 return false;
647 }
648 return true;
649}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000650
Chris Lattner941db492008-01-14 02:09:12 +0000651
Chris Lattner670c8892004-10-08 17:32:09 +0000652/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
653/// variable. This opens the door for other optimizations by exposing the
654/// behavior of the program in a more fine-grained way. We have determined that
655/// this transformation is safe already. We return the first global variable we
656/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000657static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000658 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000659 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000660 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000661
Rafael Espindolabb46f522009-01-15 20:18:42 +0000662 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000663 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000664 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000665
Chris Lattner670c8892004-10-08 17:32:09 +0000666 std::vector<GlobalVariable*> NewGlobals;
667 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
668
Chris Lattner998182b2008-04-26 07:40:11 +0000669 // Get the alignment of the global, either explicit or target-specific.
670 unsigned StartAlignment = GV->getAlignment();
671 if (StartAlignment == 0)
672 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000673
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000674 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000675 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000676 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000677 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000678 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000679 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000680 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000681 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000682 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000683 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000684 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000685 Globals.insert(GV, NGV);
686 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000687
Chris Lattner998182b2008-04-26 07:40:11 +0000688 // Calculate the known alignment of the field. If the original aggregate
689 // had 256 byte alignment for example, something might depend on that:
690 // propagate info to each field.
691 uint64_t FieldOffset = Layout.getElementOffset(i);
692 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
693 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
694 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000695 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000696 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000697 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000698 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000699 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000700 else
Chris Lattner998182b2008-04-26 07:40:11 +0000701 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000702
Chris Lattner1f21ef12005-02-23 16:53:04 +0000703 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000704 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000705 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000706
Duncan Sands777d2302009-05-09 07:06:46 +0000707 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000708 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000709 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000710 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000711 assert(In && "Couldn't get element of initializer?");
712
Chris Lattner7b550cc2009-11-06 04:27:31 +0000713 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000714 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000715 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000716 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000717 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000718 Globals.insert(GV, NGV);
719 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000720
Chris Lattner998182b2008-04-26 07:40:11 +0000721 // Calculate the known alignment of the field. If the original aggregate
722 // had 256 byte alignment for example, something might depend on that:
723 // propagate info to each field.
724 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
725 if (NewAlign > EltAlign)
726 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000727 }
728 }
729
730 if (NewGlobals.empty())
731 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000732
David Greene3215b0e2010-01-05 01:28:05 +0000733 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000734
Chris Lattner7b550cc2009-11-06 04:27:31 +0000735 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000736
737 // Loop over all of the uses of the global, replacing the constantexpr geps,
738 // with smaller constantexpr geps or direct references.
739 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000740 User *GEP = GV->use_back();
741 assert(((isa<ConstantExpr>(GEP) &&
742 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
743 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000744
Chris Lattner670c8892004-10-08 17:32:09 +0000745 // Ignore the 1th operand, which has to be zero or else the program is quite
746 // broken (undefined). Get the 2nd operand, which is the structure or array
747 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000748 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000749 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
750
Chris Lattner30ba5692004-10-11 05:54:41 +0000751 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000752
753 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000754 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000755 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000756 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000757 Idxs.push_back(NullInt);
758 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
759 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000760 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000761 } else {
762 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000763 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000764 Idxs.push_back(NullInt);
765 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
766 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000767 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000768 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000769 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000770 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000771 GEP->replaceAllUsesWith(NewPtr);
772
773 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000774 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000775 else
776 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000777 }
778
Chris Lattnere40e2d12004-10-08 20:25:55 +0000779 // Delete the old global, now that it is dead.
780 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000781 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000782
783 // Loop over the new globals array deleting any globals that are obviously
784 // dead. This can arise due to scalarization of a structure or an array that
785 // has elements that are dead.
786 unsigned FirstGlobal = 0;
787 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
788 if (NewGlobals[i]->use_empty()) {
789 Globals.erase(NewGlobals[i]);
790 if (FirstGlobal == i) ++FirstGlobal;
791 }
792
793 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000794}
795
Chris Lattner9b34a612004-10-09 21:48:45 +0000796/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000797/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000798/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000799static bool AllUsesOfValueWillTrapIfNull(const Value *V,
800 SmallPtrSet<const PHINode*, 8> &PHIs) {
801 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000802 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000803 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000804
805 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000806 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000807 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000808 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000809 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000810 return false; // Storing the value.
811 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000812 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000813 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000814 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000815 return false; // Not calling the ptr
816 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000817 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000818 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000819 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000820 return false; // Not calling the ptr
821 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000822 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000823 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000824 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000825 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000826 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000827 // If we've already seen this phi node, ignore it, it has already been
828 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000829 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
830 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000831 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000832 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000833 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000834 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000835 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000836 return false;
837 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000838 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000839 return true;
840}
841
842/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000843/// from GV will trap if the loaded value is null. Note that this also permits
844/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000845static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
846 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000847 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000848 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000849
Gabor Greif6ce02b52010-04-06 19:24:18 +0000850 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
851 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000852 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000853 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000854 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000855 // Ignore stores to the global.
856 } else {
857 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000858 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000859 return false;
860 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000861 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000862 return true;
863}
864
Chris Lattner7b550cc2009-11-06 04:27:31 +0000865static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000866 bool Changed = false;
867 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
868 Instruction *I = cast<Instruction>(*UI++);
869 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
870 LI->setOperand(0, NewV);
871 Changed = true;
872 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
873 if (SI->getOperand(1) == V) {
874 SI->setOperand(1, NewV);
875 Changed = true;
876 }
877 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000878 CallSite CS(I);
879 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000880 // Calling through the pointer! Turn into a direct call, but be careful
881 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000882 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000883 Changed = true;
884 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000885 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
886 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000887 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000888 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000889 }
890
891 if (PassedAsArg) {
892 // Being passed as an argument also. Be careful to not invalidate UI!
893 UI = V->use_begin();
894 }
895 }
896 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
897 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000898 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000899 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000900 if (CI->use_empty()) {
901 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000902 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000903 }
904 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
905 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000906 SmallVector<Constant*, 8> Idxs;
907 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000908 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
909 i != e; ++i)
910 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000911 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000912 else
913 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000914 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000915 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000916 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000917 if (GEPI->use_empty()) {
918 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000919 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000920 }
921 }
922 }
923
924 return Changed;
925}
926
927
928/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
929/// value stored into it. If there are uses of the loaded value that would trap
930/// if the loaded value is dynamically null, then we know that they cannot be
931/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000932static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
933 TargetData *TD,
934 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000935 bool Changed = false;
936
Chris Lattner92c6bd22009-01-14 00:12:58 +0000937 // Keep track of whether we are able to remove all the uses of the global
938 // other than the store that defines it.
939 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000940
Chris Lattner708148e2004-10-10 23:14:11 +0000941 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000942 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
943 User *GlobalUser = *GUI++;
944 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000945 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000946 // If we were able to delete all uses of the loads
947 if (LI->use_empty()) {
948 LI->eraseFromParent();
949 Changed = true;
950 } else {
951 AllNonStoreUsesGone = false;
952 }
953 } else if (isa<StoreInst>(GlobalUser)) {
954 // Ignore the store that stores "LV" to the global.
955 assert(GlobalUser->getOperand(1) == GV &&
956 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000957 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000958 AllNonStoreUsesGone = false;
959
960 // If we get here we could have other crazy uses that are transitively
961 // loaded.
962 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000963 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
964 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000965 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000966 }
Chris Lattner708148e2004-10-10 23:14:11 +0000967
968 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000969 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000970 ++NumGlobUses;
971 }
972
Chris Lattner708148e2004-10-10 23:14:11 +0000973 // If we nuked all of the loads, then none of the stores are needed either,
974 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000975 if (AllNonStoreUsesGone) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000976 if (isLeakCheckerRoot(GV)) {
977 Changed |= CleanupPointerRootUsers(GV);
978 } else {
979 Changed = true;
980 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
981 }
Chris Lattner708148e2004-10-10 23:14:11 +0000982 if (GV->use_empty()) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000983 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
984 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000985 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000986 ++NumDeleted;
987 }
Chris Lattner708148e2004-10-10 23:14:11 +0000988 }
989 return Changed;
990}
991
Chris Lattner30ba5692004-10-11 05:54:41 +0000992/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
993/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000994static void ConstantPropUsersOf(Value *V,
995 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000996 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
997 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +0000998 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000999 I->replaceAllUsesWith(NewC);
1000
Chris Lattnerd514d822005-02-01 01:23:31 +00001001 // Advance UI to the next non-I use to avoid invalidating it!
1002 // Instructions could multiply use V.
1003 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +00001004 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +00001005 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +00001006 }
1007}
1008
1009/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
1010/// variable, and transforms the program as if it always contained the result of
1011/// the specified malloc. Because it is always the result of the specified
1012/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001013/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001014static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001015 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001016 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +00001017 ConstantInt *NElements,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001018 TargetData *TD,
1019 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +00001020 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001021
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001022 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +00001023 if (NElements->getZExtValue() == 1)
1024 GlobalType = AllocTy;
1025 else
1026 // If we have an array allocation, the global variable is of an array.
1027 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +00001028
1029 // Create the new global variable. The contents of the malloc'd memory is
1030 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001031 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +00001032 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +00001033 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +00001034 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +00001035 GV->getName()+".body",
1036 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001037 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001038
Chris Lattnera6874652010-02-25 22:33:52 +00001039 // If there are bitcast users of the malloc (which is typical, usually we have
1040 // a malloc + bitcast) then replace them with uses of the new global. Update
1041 // other users to use the global as well.
1042 BitCastInst *TheBC = 0;
1043 while (!CI->use_empty()) {
1044 Instruction *User = cast<Instruction>(CI->use_back());
1045 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1046 if (BCI->getType() == NewGV->getType()) {
1047 BCI->replaceAllUsesWith(NewGV);
1048 BCI->eraseFromParent();
1049 } else {
1050 BCI->setOperand(0, NewGV);
1051 }
1052 } else {
1053 if (TheBC == 0)
1054 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1055 User->replaceUsesOfWith(CI, TheBC);
1056 }
1057 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001058
Victor Hernandez83d63912009-09-18 22:35:49 +00001059 Constant *RepValue = NewGV;
1060 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001061 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +00001062 GV->getType()->getElementType());
1063
1064 // If there is a comparison against null, we will insert a global bool to
1065 // keep track of whether the global was initialized yet or not.
1066 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001067 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +00001068 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001069 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +00001070 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001071 bool InitBoolUsed = false;
1072
1073 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +00001074 while (!GV->use_empty()) {
1075 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001076 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001077 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1078 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001079 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +00001080 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +00001081 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001082
Chris Lattnera6874652010-02-25 22:33:52 +00001083 LoadInst *LI = cast<LoadInst>(GV->use_back());
1084 while (!LI->use_empty()) {
1085 Use &LoadUse = LI->use_begin().getUse();
1086 if (!isa<ICmpInst>(LoadUse.getUser())) {
1087 LoadUse = RepValue;
1088 continue;
1089 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001090
Chris Lattnera6874652010-02-25 22:33:52 +00001091 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1092 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001093 // Sink the load to where the compare was, if atomic rules allow us to.
1094 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1095 LI->getOrdering(), LI->getSynchScope(),
1096 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +00001097 InitBoolUsed = true;
1098 switch (ICI->getPredicate()) {
1099 default: llvm_unreachable("Unknown ICmp Predicate!");
1100 case ICmpInst::ICMP_ULT:
1101 case ICmpInst::ICMP_SLT: // X < null -> always false
1102 LV = ConstantInt::getFalse(GV->getContext());
1103 break;
1104 case ICmpInst::ICMP_ULE:
1105 case ICmpInst::ICMP_SLE:
1106 case ICmpInst::ICMP_EQ:
1107 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1108 break;
1109 case ICmpInst::ICMP_NE:
1110 case ICmpInst::ICMP_UGE:
1111 case ICmpInst::ICMP_SGE:
1112 case ICmpInst::ICMP_UGT:
1113 case ICmpInst::ICMP_SGT:
1114 break; // no change.
1115 }
1116 ICI->replaceAllUsesWith(LV);
1117 ICI->eraseFromParent();
1118 }
1119 LI->eraseFromParent();
1120 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001121
1122 // If the initialization boolean was used, insert it, otherwise delete it.
1123 if (!InitBoolUsed) {
1124 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +00001125 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001126 delete InitBool;
1127 } else
1128 GV->getParent()->getGlobalList().insert(GV, InitBool);
1129
Chris Lattnera6874652010-02-25 22:33:52 +00001130 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +00001131 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001132 CI->eraseFromParent();
1133
1134 // To further other optimizations, loop over all users of NewGV and try to
1135 // constant prop them. This will promote GEP instructions with constant
1136 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001137 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001138 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +00001139 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001140
1141 return NewGV;
1142}
1143
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001144/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1145/// to make sure that there are no complex uses of V. We permit simple things
1146/// like dereferencing the pointer, but not storing through the address, unless
1147/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +00001148static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1149 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +00001150 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001151 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +00001152 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001153 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +00001154
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001155 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1156 continue; // Fine, ignore.
1157 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001158
Gabor Greif0b520db2010-04-06 18:58:22 +00001159 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001160 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1161 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001162 continue; // Otherwise, storing through it, or storing into GV... fine.
1163 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001164
Chris Lattnera2fb2342010-04-10 18:19:22 +00001165 // Must index into the array and into the struct.
1166 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001167 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001168 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001169 continue;
1170 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001171
Gabor Greif0b520db2010-04-06 18:58:22 +00001172 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001173 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1174 // cycles.
1175 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001176 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1177 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001178 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001179 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001180
Gabor Greif0b520db2010-04-06 18:58:22 +00001181 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001182 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1183 return false;
1184 continue;
1185 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001186
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001187 return false;
1188 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001189 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001190}
1191
Chris Lattner86395032006-09-30 23:32:09 +00001192/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1193/// somewhere. Transform all uses of the allocation into loads from the
1194/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001195/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001196/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001197static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001198 GlobalVariable *GV) {
1199 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001200 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1201 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001202 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1203 // If this is the store of the allocation into the global, remove it.
1204 if (SI->getOperand(1) == GV) {
1205 SI->eraseFromParent();
1206 continue;
1207 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001208 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1209 // Insert the load in the corresponding predecessor, not right before the
1210 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001211 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001212 } else if (isa<BitCastInst>(U)) {
1213 // Must be bitcast between the malloc and store to initialize the global.
1214 ReplaceUsesOfMallocWithGlobal(U, GV);
1215 U->eraseFromParent();
1216 continue;
1217 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1218 // If this is a "GEP bitcast" and the user is a store to the global, then
1219 // just process it as a bitcast.
1220 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1221 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1222 if (SI->getOperand(1) == GV) {
1223 // Must be bitcast GEP between the malloc and store to initialize
1224 // the global.
1225 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1226 GEPI->eraseFromParent();
1227 continue;
1228 }
Chris Lattner86395032006-09-30 23:32:09 +00001229 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001230
Chris Lattner86395032006-09-30 23:32:09 +00001231 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001232 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001233 U->replaceUsesOfWith(Alloc, NL);
1234 }
1235}
1236
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001237/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1238/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1239/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001240static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001241 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1242 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001243 // We permit two users of the load: setcc comparing against the null
1244 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001245 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1246 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001247 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001248
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001249 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001250 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001251 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1252 return false;
1253 continue;
1254 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001255
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001256 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001257 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001258 // Must index into the array and into the struct.
1259 if (GEPI->getNumOperands() < 3)
1260 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001261
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001262 // Otherwise the GEP is ok.
1263 continue;
1264 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001265
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001266 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001267 if (!LoadUsingPHIsPerLoad.insert(PN))
1268 // This means some phi nodes are dependent on each other.
1269 // Avoid infinite looping!
1270 return false;
1271 if (!LoadUsingPHIs.insert(PN))
1272 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001273 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001274
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001275 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001276 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1277 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001278 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001279
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001280 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001281 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001282
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001283 // Otherwise we don't know what this is, not ok.
1284 return false;
1285 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001286
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001287 return true;
1288}
1289
1290
1291/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1292/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001293static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001294 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001295 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1296 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001297 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1298 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001299 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001300 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1301 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001302 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001303 LoadUsingPHIsPerLoad.clear();
1304 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001305
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001306 // If we reach here, we know that all uses of the loads and transitive uses
1307 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001308 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001309 // Check to verify that all operands of the PHIs are either PHIS that can be
1310 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001311 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1312 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001313 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001314 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1315 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001316
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001317 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001318 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001319
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001320 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001321 // One of the PHIs in our set is (optimistically) ok.
1322 if (LoadUsingPHIs.count(InPN))
1323 continue;
1324 return false;
1325 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001326
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001327 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001328 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001329 if (LI->getOperand(0) == GV)
1330 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001331
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001332 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001333
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001334 // Anything else is rejected.
1335 return false;
1336 }
1337 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001338
Chris Lattner86395032006-09-30 23:32:09 +00001339 return true;
1340}
1341
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001342static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1343 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001344 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001345 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001346
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001347 if (FieldNo >= FieldVals.size())
1348 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001349
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001350 // If we already have this value, just reuse the previously scalarized
1351 // version.
1352 if (Value *FieldVal = FieldVals[FieldNo])
1353 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001354
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001355 // Depending on what instruction this is, we have several cases.
1356 Value *Result;
1357 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1358 // This is a scalarized version of the load from the global. Just create
1359 // a new Load of the scalarized global.
1360 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1361 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001362 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001363 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001364 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1365 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1366 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001367 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001368 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001369
Jay Foadd8b4fb42011-03-30 11:19:20 +00001370 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001371 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001372 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001373 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001374 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001375 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1376 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001377 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001378 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001379
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001380 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001381}
1382
Chris Lattner330245e2007-09-13 17:29:05 +00001383/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1384/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001385static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001386 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001387 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001388 // If this is a comparison against null, handle it.
1389 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1390 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1391 // If we have a setcc of the loaded pointer, we can use a setcc of any
1392 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001393 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001394 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001395
Owen Anderson333c4002009-07-09 23:48:35 +00001396 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001397 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001398 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001399 SCI->replaceAllUsesWith(New);
1400 SCI->eraseFromParent();
1401 return;
1402 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001403
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001404 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001405 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1406 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1407 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001408
Chris Lattnera637a8b2007-09-13 18:00:31 +00001409 // Load the pointer for this field.
1410 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001411 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001412 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001413
Chris Lattnera637a8b2007-09-13 18:00:31 +00001414 // Create the new GEP idx vector.
1415 SmallVector<Value*, 8> GEPIdx;
1416 GEPIdx.push_back(GEPI->getOperand(1));
1417 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001418
Jay Foada9203102011-07-25 09:48:08 +00001419 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001420 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001421 GEPI->replaceAllUsesWith(NGEPI);
1422 GEPI->eraseFromParent();
1423 return;
1424 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001425
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001426 // Recursively transform the users of PHI nodes. This will lazily create the
1427 // PHIs that are needed for individual elements. Keep track of what PHIs we
1428 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1429 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1430 // already been seen first by another load, so its uses have already been
1431 // processed.
1432 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001433 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1434 std::vector<Value*>())).second)
1435 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001436
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001437 // If this is the first time we've seen this PHI, recursively process all
1438 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001439 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1440 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001441 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001442 }
Chris Lattner330245e2007-09-13 17:29:05 +00001443}
1444
Chris Lattner86395032006-09-30 23:32:09 +00001445/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1446/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1447/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001448/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001449static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001450 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001451 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001452 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001453 UI != E; ) {
1454 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001455 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001456 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001457
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001458 if (Load->use_empty()) {
1459 Load->eraseFromParent();
1460 InsertedScalarizedValues.erase(Load);
1461 }
Chris Lattner86395032006-09-30 23:32:09 +00001462}
1463
Victor Hernandez83d63912009-09-18 22:35:49 +00001464/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1465/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001466static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Nick Lewyckybc384a12012-02-05 19:48:37 +00001467 Value *NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001468 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Nick Lewyckybc384a12012-02-05 19:48:37 +00001469 Type *MAT = getMallocAllocatedType(CI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001470 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001471
1472 // There is guaranteed to be at least one use of the malloc (storing
1473 // it into GV). If there are other uses, change them to be uses of
1474 // the global to simplify later code. This also deletes the store
1475 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001476 ReplaceUsesOfMallocWithGlobal(CI, GV);
1477
Victor Hernandez83d63912009-09-18 22:35:49 +00001478 // Okay, at this point, there are no users of the malloc. Insert N
1479 // new mallocs at the same place as CI, and N globals.
1480 std::vector<Value*> FieldGlobals;
1481 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001482
Victor Hernandez83d63912009-09-18 22:35:49 +00001483 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001484 Type *FieldTy = STy->getElementType(FieldNo);
1485 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001486
Victor Hernandez83d63912009-09-18 22:35:49 +00001487 GlobalVariable *NGV =
1488 new GlobalVariable(*GV->getParent(),
1489 PFieldTy, false, GlobalValue::InternalLinkage,
1490 Constant::getNullValue(PFieldTy),
1491 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001492 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001493 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001494
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001495 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001496 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001497 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001498 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001499 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1500 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001501 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001502 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001503 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001504 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001505 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001506
Victor Hernandez83d63912009-09-18 22:35:49 +00001507 // The tricky aspect of this transformation is handling the case when malloc
1508 // fails. In the original code, malloc failing would set the result pointer
1509 // of malloc to null. In this case, some mallocs could succeed and others
1510 // could fail. As such, we emit code that looks like this:
1511 // F0 = malloc(field0)
1512 // F1 = malloc(field1)
1513 // F2 = malloc(field2)
1514 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1515 // if (F0) { free(F0); F0 = 0; }
1516 // if (F1) { free(F1); F1 = 0; }
1517 // if (F2) { free(F2); F2 = 0; }
1518 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001519 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001520 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1521 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001522 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001523 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001524 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1525 Constant::getNullValue(FieldMallocs[i]->getType()),
1526 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001527 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001528 }
1529
1530 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001531 BasicBlock *OrigBB = CI->getParent();
1532 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001533
Victor Hernandez83d63912009-09-18 22:35:49 +00001534 // Create the block to check the first condition. Put all these blocks at the
1535 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001536 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1537 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001538 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001539
Victor Hernandez83d63912009-09-18 22:35:49 +00001540 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1541 // branch on RunningOr.
1542 OrigBB->getTerminator()->eraseFromParent();
1543 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001544
Victor Hernandez83d63912009-09-18 22:35:49 +00001545 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1546 // pointer, because some may be null while others are not.
1547 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1548 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001549 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001550 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001551 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001552 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001553 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001554 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001555 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1556 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001557
1558 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001559 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001560 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1561 FreeBlock);
1562 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001563
Victor Hernandez83d63912009-09-18 22:35:49 +00001564 NullPtrBlock = NextBlock;
1565 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001566
Victor Hernandez83d63912009-09-18 22:35:49 +00001567 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001568
1569 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001570 CI->eraseFromParent();
1571
1572 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1573 /// update all uses of the load, keep track of what scalarized loads are
1574 /// inserted for a given load.
1575 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1576 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001577
Victor Hernandez83d63912009-09-18 22:35:49 +00001578 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001579
Victor Hernandez83d63912009-09-18 22:35:49 +00001580 // Okay, the malloc site is completely handled. All of the uses of GV are now
1581 // loads, and all uses of those loads are simple. Rewrite them to use loads
1582 // of the per-field globals instead.
1583 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1584 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001585
Victor Hernandez83d63912009-09-18 22:35:49 +00001586 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001587 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001588 continue;
1589 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001590
Victor Hernandez83d63912009-09-18 22:35:49 +00001591 // Must be a store of null.
1592 StoreInst *SI = cast<StoreInst>(User);
1593 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1594 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001595
Victor Hernandez83d63912009-09-18 22:35:49 +00001596 // Insert a store of null into each global.
1597 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001598 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001599 Constant *Null = Constant::getNullValue(PT->getElementType());
1600 new StoreInst(Null, FieldGlobals[i], SI);
1601 }
1602 // Erase the original store.
1603 SI->eraseFromParent();
1604 }
1605
1606 // While we have PHIs that are interesting to rewrite, do it.
1607 while (!PHIsToRewrite.empty()) {
1608 PHINode *PN = PHIsToRewrite.back().first;
1609 unsigned FieldNo = PHIsToRewrite.back().second;
1610 PHIsToRewrite.pop_back();
1611 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1612 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1613
1614 // Add all the incoming values. This can materialize more phis.
1615 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1616 Value *InVal = PN->getIncomingValue(i);
1617 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001618 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001619 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1620 }
1621 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001622
Victor Hernandez83d63912009-09-18 22:35:49 +00001623 // Drop all inter-phi links and any loads that made it this far.
1624 for (DenseMap<Value*, std::vector<Value*> >::iterator
1625 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1626 I != E; ++I) {
1627 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1628 PN->dropAllReferences();
1629 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1630 LI->dropAllReferences();
1631 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001632
Victor Hernandez83d63912009-09-18 22:35:49 +00001633 // Delete all the phis and loads now that inter-references are dead.
1634 for (DenseMap<Value*, std::vector<Value*> >::iterator
1635 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1636 I != E; ++I) {
1637 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1638 PN->eraseFromParent();
1639 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1640 LI->eraseFromParent();
1641 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001642
Victor Hernandez83d63912009-09-18 22:35:49 +00001643 // The old global is now dead, remove it.
1644 GV->eraseFromParent();
1645
1646 ++NumHeapSRA;
1647 return cast<GlobalVariable>(FieldGlobals[0]);
1648}
1649
Chris Lattnere61d0a62008-12-15 21:02:25 +00001650/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1651/// pointer global variable with a single value stored it that is a malloc or
1652/// cast of malloc.
1653static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001654 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001655 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001656 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001657 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001658 TargetData *TD,
1659 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001660 if (!TD)
1661 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001662
Victor Hernandez83d63912009-09-18 22:35:49 +00001663 // If this is a malloc of an abstract type, don't touch it.
1664 if (!AllocTy->isSized())
1665 return false;
1666
1667 // We can't optimize this global unless all uses of it are *known* to be
1668 // of the malloc value, not of the null initializer value (consider a use
1669 // that compares the global's value against zero to see if the malloc has
1670 // been reached). To do this, we check to see if all uses of the global
1671 // would trap if the global were null: this proves that they must all
1672 // happen after the malloc.
1673 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1674 return false;
1675
1676 // We can't optimize this if the malloc itself is used in a complex way,
1677 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001678 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001679 // GEP'd. These are all things we could transform to using the global
1680 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001681 SmallPtrSet<const PHINode*, 8> PHIs;
1682 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1683 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001684
1685 // If we have a global that is only initialized with a fixed size malloc,
1686 // transform the program to use global memory instead of malloc'd memory.
1687 // This eliminates dynamic allocation, avoids an indirection accessing the
1688 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001689 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001690 Value *NElems = getMallocArraySize(CI, TD, true);
1691 if (!NElems)
1692 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001693
Evan Cheng86cd4452010-04-14 20:52:55 +00001694 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1695 // Restrict this transformation to only working on small allocations
1696 // (2048 bytes currently), as we don't want to introduce a 16M global or
1697 // something.
1698 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001699 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001700 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001701 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001702
Evan Cheng86cd4452010-04-14 20:52:55 +00001703 // If the allocation is an array of structures, consider transforming this
1704 // into multiple malloc'd arrays, one for each field. This is basically
1705 // SRoA for malloc'd memory.
1706
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001707 if (Ordering != NotAtomic)
1708 return false;
1709
Evan Cheng86cd4452010-04-14 20:52:55 +00001710 // If this is an allocation of a fixed size array of structs, analyze as a
1711 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001712 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001713 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001714 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001715
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001716 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001717 if (!AllocSTy)
1718 return false;
1719
1720 // This the structure has an unreasonable number of fields, leave it
1721 // alone.
1722 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1723 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1724
1725 // If this is a fixed size array, transform the Malloc to be an alloc of
1726 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001727 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1728 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001729 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1730 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1731 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1732 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1733 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001734 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001735 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1736 CI->replaceAllUsesWith(Cast);
1737 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001738 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1739 CI = cast<CallInst>(BCI->getOperand(0));
1740 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001741 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001742 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001743
Nick Lewyckybc384a12012-02-05 19:48:37 +00001744 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true), TD);
Evan Cheng86cd4452010-04-14 20:52:55 +00001745 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001746 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001747
Victor Hernandez83d63912009-09-18 22:35:49 +00001748 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001749}
Victor Hernandez83d63912009-09-18 22:35:49 +00001750
Chris Lattner9b34a612004-10-09 21:48:45 +00001751// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1752// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001753static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001754 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001755 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001756 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001757 // Ignore no-op GEPs and bitcasts.
1758 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001759
Chris Lattner708148e2004-10-10 23:14:11 +00001760 // If we are dealing with a pointer global that is initialized to null and
1761 // only has one (non-null) value stored into it, then we can optimize any
1762 // users of the loaded value (often calls and loads) that would trap if the
1763 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001764 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001765 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001766 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1767 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001768 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001769
Chris Lattner708148e2004-10-10 23:14:11 +00001770 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001771 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001772 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001773 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Nick Lewyckybc384a12012-02-05 19:48:37 +00001774 Type *MallocType = getMallocAllocatedType(CI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001775 if (MallocType &&
1776 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1777 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001778 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001779 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001780 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001781
Chris Lattner9b34a612004-10-09 21:48:45 +00001782 return false;
1783}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001784
Chris Lattner58e44f42008-01-14 01:17:44 +00001785/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1786/// two values ever stored into GV are its initializer and OtherVal. See if we
1787/// can shrink the global into a boolean and select between the two values
1788/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001789static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001790 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001791
Chris Lattner58e44f42008-01-14 01:17:44 +00001792 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001793 // an FP value, pointer or vector, don't do this optimization because a select
1794 // between them is very expensive and unlikely to lead to later
1795 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1796 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001797 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001798 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001799 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001800 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001801
Chris Lattner58e44f42008-01-14 01:17:44 +00001802 // Walk the use list of the global seeing if all the uses are load or store.
1803 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001804 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1805 User *U = *I;
1806 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001807 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001808 }
1809
David Greene3215b0e2010-01-05 01:28:05 +00001810 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001811
Chris Lattner96a86b22004-12-12 05:53:50 +00001812 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001813 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1814 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001815 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001816 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001817 GV->getName()+".b",
Hans Wennborgce718ff2012-06-23 11:37:03 +00001818 GV->getThreadLocalMode());
Chris Lattner96a86b22004-12-12 05:53:50 +00001819 GV->getParent()->getGlobalList().insert(GV, NewGV);
1820
1821 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001822 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001823 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001824
1825 // If initialized to zero and storing one into the global, we can use a cast
1826 // instead of a select to synthesize the desired value.
1827 bool IsOneZero = false;
1828 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001829 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001830
1831 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001832 Instruction *UI = cast<Instruction>(GV->use_back());
1833 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001834 // Change the store into a boolean store.
1835 bool StoringOther = SI->getOperand(0) == OtherVal;
1836 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001837 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001838 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001839 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1840 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001841 else {
1842 // Otherwise, we are storing a previously loaded copy. To do this,
1843 // change the copy from copying the original value to just copying the
1844 // bool.
1845 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1846
Gabor Greif9e4f2432010-06-24 14:42:01 +00001847 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001848 // select instruction. If not, it will be a load of the original
1849 // global.
1850 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1851 assert(LI->getOperand(0) == GV && "Not a copy!");
1852 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001853 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1854 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001855 } else {
1856 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1857 "This is not a form that we understand!");
1858 StoreVal = StoredVal->getOperand(0);
1859 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1860 }
1861 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001862 new StoreInst(StoreVal, NewGV, false, 0,
1863 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001864 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001865 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001866 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001867 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1868 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001869 Value *NSI;
1870 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001871 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001872 else
Gabor Greif051a9502008-04-06 20:25:17 +00001873 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001874 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001875 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001876 }
1877 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001878 }
1879
1880 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001881 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001882}
1883
1884
Nick Lewyckydb292a62012-02-12 00:52:26 +00001885/// ProcessGlobal - Analyze the specified global variable and optimize it if
1886/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001887bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1888 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001889 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001890 return false;
1891
1892 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001893 GV->removeDeadConstantUsers();
1894
1895 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001896 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001897 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001898 ++NumDeleted;
1899 return true;
1900 }
1901
Rafael Espindola2f135d42012-06-15 18:00:24 +00001902 if (!GV->hasLocalLinkage())
1903 return false;
1904
Rafael Espindolac4440e32011-01-19 16:32:21 +00001905 SmallPtrSet<const PHINode*, 16> PHIUsers;
1906 GlobalStatus GS;
1907
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001908 if (AnalyzeGlobal(GV, GS, PHIUsers))
1909 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001910
Rafael Espindolac4440e32011-01-19 16:32:21 +00001911 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1912 GV->setUnnamedAddr(true);
1913 NumUnnamed++;
1914 }
1915
1916 if (GV->isConstant() || !GV->hasInitializer())
1917 return false;
1918
1919 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1920}
1921
1922/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1923/// it if possible. If we make a change, return true.
1924bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1925 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001926 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001927 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001928 // If this is a first class global and has only one accessing function
1929 // and this function is main (which we know is not recursive we can make
1930 // this global a local variable) we replace the global with a local alloca
1931 // in this function.
1932 //
1933 // NOTE: It doesn't make sense to promote non single-value types since we
1934 // are just replacing static memory to stack memory.
1935 //
1936 // If the global is in different address space, don't bring it to stack.
1937 if (!GS.HasMultipleAccessingFunctions &&
1938 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1939 GV->getType()->getElementType()->isSingleValueType() &&
1940 GS.AccessingFunction->getName() == "main" &&
1941 GS.AccessingFunction->hasExternalLinkage() &&
1942 GV->getType()->getAddressSpace() == 0) {
1943 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001944 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001945 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001946 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001947 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001948 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001949 if (!isa<UndefValue>(GV->getInitializer()))
1950 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001951
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001952 GV->replaceAllUsesWith(Alloca);
1953 GV->eraseFromParent();
1954 ++NumLocalized;
1955 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001956 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001957
1958 // If the global is never loaded (but may be stored to), it is dead.
1959 // Delete it now.
1960 if (!GS.isLoaded) {
1961 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1962
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001963 bool Changed;
1964 if (isLeakCheckerRoot(GV)) {
1965 // Delete any constant stores to the global.
1966 Changed = CleanupPointerRootUsers(GV);
1967 } else {
1968 // Delete any stores we can find to the global. We may not be able to
1969 // make it completely dead though.
1970 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1971 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001972
1973 // If the global is dead now, delete it.
1974 if (GV->use_empty()) {
1975 GV->eraseFromParent();
1976 ++NumDeleted;
1977 Changed = true;
1978 }
1979 return Changed;
1980
1981 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1982 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1983 GV->setConstant(true);
1984
1985 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001986 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001987
1988 // If the global is dead now, just nuke it.
1989 if (GV->use_empty()) {
1990 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1991 << "all users and delete global!\n");
1992 GV->eraseFromParent();
1993 ++NumDeleted;
1994 }
1995
1996 ++NumMarked;
1997 return true;
1998 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1999 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
2000 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
2001 GVI = FirstNewGV; // Don't skip the newly produced globals!
2002 return true;
2003 }
2004 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
2005 // If the initial value for the global was an undef value, and if only
2006 // one other value was stored into it, we can just change the
2007 // initializer to be the stored value, then delete all stores to the
2008 // global. This allows us to mark it constant.
2009 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2010 if (isa<UndefValue>(GV->getInitializer())) {
2011 // Change the initial value here.
2012 GV->setInitializer(SOVConstant);
2013
2014 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002015 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002016
2017 if (GV->use_empty()) {
2018 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00002019 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002020 GV->eraseFromParent();
2021 ++NumDeleted;
2022 } else {
2023 GVI = GV;
2024 }
2025 ++NumSubstitute;
2026 return true;
2027 }
2028
2029 // Try to optimize globals based on the knowledge that only one value
2030 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00002031 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00002032 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002033 return true;
2034
2035 // Otherwise, if the global was not a boolean, we can shrink it to be a
2036 // boolean.
2037 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2038 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
2039 ++NumShrunkToBool;
2040 return true;
2041 }
2042 }
2043
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002044 return false;
2045}
2046
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002047/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2048/// function, changing them to FastCC.
2049static void ChangeCalleesToFastCall(Function *F) {
2050 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002051 if (isa<BlockAddress>(*UI))
2052 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002053 CallSite User(cast<Instruction>(*UI));
2054 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002055 }
2056}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002057
Devang Patel05988662008-09-25 21:00:45 +00002058static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00002059 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00002060 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00002061 continue;
2062
Duncan Sands548448a2008-02-18 17:32:13 +00002063 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00002064 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00002065 }
2066
2067 return Attrs;
2068}
2069
2070static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00002071 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002072 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002073 if (isa<BlockAddress>(*UI))
2074 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002075 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00002076 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002077 }
2078}
2079
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002080bool GlobalOpt::OptimizeFunctions(Module &M) {
2081 bool Changed = false;
2082 // Optimize functions.
2083 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2084 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002085 // Functions without names cannot be referenced outside this module.
2086 if (!F->hasName() && !F->isDeclaration())
2087 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002088 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00002089 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00002090 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002091 Changed = true;
2092 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002093 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002094 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002095 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002096 // If this function has C calling conventions, is not a varargs
2097 // function, and is only called directly, promote it to use the Fast
2098 // calling convention.
2099 F->setCallingConv(CallingConv::Fast);
2100 ChangeCalleesToFastCall(F);
2101 ++NumFastCallFns;
2102 Changed = true;
2103 }
2104
Devang Patel05988662008-09-25 21:00:45 +00002105 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002106 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002107 // The function is not used by a trampoline intrinsic, so it is safe
2108 // to remove the 'nest' attribute.
2109 RemoveNestAttribute(F);
2110 ++NumNestRemoved;
2111 Changed = true;
2112 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002113 }
2114 }
2115 return Changed;
2116}
2117
2118bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2119 bool Changed = false;
2120 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2121 GVI != E; ) {
2122 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002123 // Global variables without names cannot be referenced outside this module.
2124 if (!GV->hasName() && !GV->isDeclaration())
2125 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002126 // Simplify the initializer.
2127 if (GV->hasInitializer())
2128 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00002129 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002130 if (New && New != CE)
2131 GV->setInitializer(New);
2132 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00002133
2134 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002135 }
2136 return Changed;
2137}
2138
Nick Lewycky2c44a802011-04-08 07:30:21 +00002139/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002140/// initializers have an init priority of 65535.
2141GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002142 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2143 if (GV == 0) return 0;
2144
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002145 // Verify that the initializer is simple enough for us to handle. We are
2146 // only allowed to optimize the initializer if it is unique.
2147 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002148
2149 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2150 return GV;
2151 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00002152
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002153 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002154 if (isa<ConstantAggregateZero>(*i))
2155 continue;
2156 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002157 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2158 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002159
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002160 // Must have a function or null ptr.
2161 if (!isa<Function>(CS->getOperand(1)))
2162 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002163
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002164 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00002165 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2166 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002167 return 0;
2168 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002169
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002170 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002171}
2172
Chris Lattnerdb973e62005-09-26 02:31:18 +00002173/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2174/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002175static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002176 if (GV->getInitializer()->isNullValue())
2177 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002178 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2179 std::vector<Function*> Result;
2180 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002181 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2182 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002183 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2184 }
2185 return Result;
2186}
2187
Chris Lattnerdb973e62005-09-26 02:31:18 +00002188/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2189/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002190static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002191 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002192 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002193 Constant *CSVals[2];
2194 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2195 CSVals[1] = 0;
2196
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002197 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002198 cast <StructType>(
2199 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002200
Chris Lattnerdb973e62005-09-26 02:31:18 +00002201 // Create the new init list.
2202 std::vector<Constant*> CAList;
2203 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002204 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002205 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002206 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002207 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002208 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002209 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002210 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002211 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002212 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002213 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002214 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002215 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002216
Chris Lattnerdb973e62005-09-26 02:31:18 +00002217 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002218 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002219 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002220
Chris Lattnerdb973e62005-09-26 02:31:18 +00002221 // If we didn't change the number of elements, don't create a new GV.
2222 if (CA->getType() == GCL->getInitializer()->getType()) {
2223 GCL->setInitializer(CA);
2224 return GCL;
2225 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002226
Chris Lattnerdb973e62005-09-26 02:31:18 +00002227 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002228 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002229 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002230 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002231 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002232 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002233
Chris Lattnerdb973e62005-09-26 02:31:18 +00002234 // Nuke the old list, replacing any uses with the new one.
2235 if (!GCL->use_empty()) {
2236 Constant *V = NGV;
2237 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002238 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002239 GCL->replaceAllUsesWith(V);
2240 }
2241 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002242
Chris Lattnerdb973e62005-09-26 02:31:18 +00002243 if (Ctors.size())
2244 return NGV;
2245 else
2246 return 0;
2247}
Chris Lattner79c11012005-09-26 04:44:35 +00002248
2249
Chris Lattner1945d582010-12-07 04:33:29 +00002250static inline bool
2251isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002252 SmallPtrSet<Constant*, 8> &SimpleConstants,
2253 const TargetData *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002254
2255
2256/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2257/// handled by the code generator. We don't want to generate something like:
2258/// void *X = &X/42;
2259/// because the code generator doesn't have a relocation that can handle that.
2260///
2261/// This function should be called if C was not found (but just got inserted)
2262/// in SimpleConstants to avoid having to rescan the same constants all the
2263/// time.
2264static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002265 SmallPtrSet<Constant*, 8> &SimpleConstants,
2266 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002267 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2268 // all supported.
2269 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2270 isa<GlobalValue>(C))
2271 return true;
2272
2273 // Aggregate values are safe if all their elements are.
2274 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2275 isa<ConstantVector>(C)) {
2276 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2277 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002278 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002279 return false;
2280 }
2281 return true;
2282 }
2283
2284 // We don't know exactly what relocations are allowed in constant expressions,
2285 // so we allow &global+constantoffset, which is safe and uniformly supported
2286 // across targets.
2287 ConstantExpr *CE = cast<ConstantExpr>(C);
2288 switch (CE->getOpcode()) {
2289 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002290 // Bitcast is fine if the casted value is fine.
2291 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2292
Chris Lattner1945d582010-12-07 04:33:29 +00002293 case Instruction::IntToPtr:
2294 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002295 // int <=> ptr is fine if the int type is the same size as the
2296 // pointer type.
2297 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2298 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2299 return false;
2300 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002301
2302 // GEP is fine if it is simple + constant offset.
2303 case Instruction::GetElementPtr:
2304 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2305 if (!isa<ConstantInt>(CE->getOperand(i)))
2306 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002307 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002308
2309 case Instruction::Add:
2310 // We allow simple+cst.
2311 if (!isa<ConstantInt>(CE->getOperand(1)))
2312 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002313 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002314 }
2315 return false;
2316}
2317
2318static inline bool
2319isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002320 SmallPtrSet<Constant*, 8> &SimpleConstants,
2321 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002322 // If we already checked this constant, we win.
2323 if (!SimpleConstants.insert(C)) return true;
2324 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002325 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002326}
2327
2328
Chris Lattner79c11012005-09-26 04:44:35 +00002329/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002330/// enough for us to understand. In particular, if it is a cast to anything
2331/// other than from one pointer type to another pointer type, we punt.
2332/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002333/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002334static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002335 // Conservatively, avoid aggregate types. This is because we don't
2336 // want to worry about them partially overlapping other stores.
2337 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2338 return false;
2339
Dan Gohmanfd54a892009-09-07 22:31:26 +00002340 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002341 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002342 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002343 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002344
Owen Andersone95a32c2011-01-14 22:31:13 +00002345 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002346 // Handle a constantexpr gep.
2347 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002348 isa<GlobalVariable>(CE->getOperand(0)) &&
2349 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002350 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002351 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002352 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002353 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002354 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002355
Dan Gohman80bdc962009-09-07 22:44:55 +00002356 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002357 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002358 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002359
2360 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002361 // notional bounds of the corresponding static array types.
2362 if (!CE->isGEPWithNoNotionalOverIndexing())
2363 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002364
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002365 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002366
2367 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2368 // and we know how to evaluate it by moving the bitcast from the pointer
2369 // operand to the value operand.
2370 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002371 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002372 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2373 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002374 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002375 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002376 }
2377
Chris Lattner79c11012005-09-26 04:44:35 +00002378 return false;
2379}
2380
Chris Lattner798b4d52005-09-26 06:52:44 +00002381/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2382/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2383/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2384static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002385 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002386 // Base case of the recursion.
2387 if (OpNo == Addr->getNumOperands()) {
2388 assert(Val->getType() == Init->getType() && "Type mismatch!");
2389 return Val;
2390 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002391
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002392 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002393 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002394 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002395 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2396 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002397
Chris Lattner798b4d52005-09-26 06:52:44 +00002398 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002399 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2400 unsigned Idx = CU->getZExtValue();
2401 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002402 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002403
Chris Lattner798b4d52005-09-26 06:52:44 +00002404 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002405 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002406 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002407
2408 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002409 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002410
2411 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002412 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002413 NumElts = ATy->getNumElements();
2414 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002415 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002416
2417 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002418 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2419 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002420
2421 assert(CI->getZExtValue() < NumElts);
2422 Elts[CI->getZExtValue()] =
2423 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2424
2425 if (Init->getType()->isArrayTy())
2426 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2427 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002428}
2429
Chris Lattner79c11012005-09-26 04:44:35 +00002430/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2431/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002432static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002433 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2434 assert(GV->hasInitializer());
2435 GV->setInitializer(Val);
2436 return;
2437 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002438
Chris Lattner798b4d52005-09-26 06:52:44 +00002439 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2440 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002441 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002442}
2443
Nick Lewycky7fa76772012-02-20 03:25:59 +00002444namespace {
2445
2446/// Evaluator - This class evaluates LLVM IR, producing the Constant
2447/// representing each SSA instruction. Changes to global variables are stored
2448/// in a mapping that can be iterated over after the evaluation is complete.
2449/// Once an evaluation call fails, the evaluation object should not be reused.
2450class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002451public:
Nick Lewycky7fa76772012-02-20 03:25:59 +00002452 Evaluator(const TargetData *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002453 : TD(TD), TLI(TLI) {
2454 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2455 }
2456
Nick Lewycky7fa76772012-02-20 03:25:59 +00002457 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002458 DeleteContainerPointers(ValueStack);
2459 while (!AllocaTmps.empty()) {
2460 GlobalVariable *Tmp = AllocaTmps.back();
2461 AllocaTmps.pop_back();
2462
2463 // If there are still users of the alloca, the program is doing something
2464 // silly, e.g. storing the address of the alloca somewhere and using it
2465 // later. Since this is undefined, we'll just make it be null.
2466 if (!Tmp->use_empty())
2467 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2468 delete Tmp;
2469 }
2470 }
2471
2472 /// EvaluateFunction - Evaluate a call to function F, returning true if
2473 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2474 /// arguments for the function.
2475 bool EvaluateFunction(Function *F, Constant *&RetVal,
2476 const SmallVectorImpl<Constant*> &ActualArgs);
2477
2478 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2479 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2480 /// control flows into, or null upon return.
2481 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2482
2483 Constant *getVal(Value *V) {
2484 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2485 Constant *R = ValueStack.back()->lookup(V);
2486 assert(R && "Reference to an uncomputed value!");
2487 return R;
2488 }
2489
2490 void setVal(Value *V, Constant *C) {
2491 ValueStack.back()->operator[](V) = C;
2492 }
2493
2494 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2495 return MutatedMemory;
2496 }
2497
2498 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2499 return Invariants;
2500 }
2501
2502private:
2503 Constant *ComputeLoadResult(Constant *P);
2504
2505 /// ValueStack - As we compute SSA register values, we store their contents
2506 /// here. The back of the vector contains the current function and the stack
2507 /// contains the values in the calling frames.
2508 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2509
2510 /// CallStack - This is used to detect recursion. In pathological situations
2511 /// we could hit exponential behavior, but at least there is nothing
2512 /// unbounded.
2513 SmallVector<Function*, 4> CallStack;
2514
2515 /// MutatedMemory - For each store we execute, we update this map. Loads
2516 /// check this to get the most up-to-date value. If evaluation is successful,
2517 /// this state is committed to the process.
2518 DenseMap<Constant*, Constant*> MutatedMemory;
2519
2520 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2521 /// to represent its body. This vector is needed so we can delete the
2522 /// temporary globals when we are done.
2523 SmallVector<GlobalVariable*, 32> AllocaTmps;
2524
2525 /// Invariants - These global variables have been marked invariant by the
2526 /// static constructor.
2527 SmallPtrSet<GlobalVariable*, 8> Invariants;
2528
2529 /// SimpleConstants - These are constants we have checked and know to be
2530 /// simple enough to live in a static initializer of a global.
2531 SmallPtrSet<Constant*, 8> SimpleConstants;
2532
2533 const TargetData *TD;
2534 const TargetLibraryInfo *TLI;
2535};
2536
Nick Lewycky7fa76772012-02-20 03:25:59 +00002537} // anonymous namespace
2538
Chris Lattner562a0552005-09-26 05:16:34 +00002539/// ComputeLoadResult - Return the value that would be computed by a load from
2540/// P after the stores reflected by 'memory' have been performed. If we can't
2541/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002542Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002543 // If this memory location has been recently stored, use the stored value: it
2544 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002545 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2546 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002547
Chris Lattner04de1cf2005-09-26 05:15:37 +00002548 // Access it.
2549 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002550 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002551 return GV->getInitializer();
2552 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002553 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002554
Chris Lattner798b4d52005-09-26 06:52:44 +00002555 // Handle a constantexpr getelementptr.
2556 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2557 if (CE->getOpcode() == Instruction::GetElementPtr &&
2558 isa<GlobalVariable>(CE->getOperand(0))) {
2559 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002560 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002561 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002562 }
2563
2564 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002565}
2566
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002567/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2568/// successful, false if we can't evaluate it. NewBB returns the next BB that
2569/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002570bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2571 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002572 // This is the main evaluation loop.
2573 while (1) {
2574 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002575
Chris Lattner79c11012005-09-26 04:44:35 +00002576 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002577 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002578 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002579 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2580 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002581 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002582 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002583 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002584
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002585 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002586
2587 // If this might be too difficult for the backend to handle (e.g. the addr
2588 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002589 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002590 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002591
2592 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2593 if (CE->getOpcode() == Instruction::BitCast) {
2594 // If we're evaluating a store through a bitcast, then we need
2595 // to pull the bitcast off the pointer type and push it onto the
2596 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002597 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002598
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002599 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002600
Owen Anderson66f708f2011-01-16 04:33:33 +00002601 // In order to push the bitcast onto the stored value, a bitcast
2602 // from NewTy to Val's type must be legal. If it's not, we can try
2603 // introspecting NewTy to find a legal conversion.
2604 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2605 // If NewTy is a struct, we can convert the pointer to the struct
2606 // into a pointer to its first member.
2607 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002608 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002609 NewTy = STy->getTypeAtIndex(0U);
2610
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002611 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002612 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2613 Constant * const IdxList[] = {IdxZero, IdxZero};
2614
Jay Foadb4263a62011-07-22 08:52:50 +00002615 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002616 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2617 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2618
Owen Anderson66f708f2011-01-16 04:33:33 +00002619 // If we can't improve the situation by introspecting NewTy,
2620 // we have to give up.
2621 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002622 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002623 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002624 }
2625
Owen Anderson66f708f2011-01-16 04:33:33 +00002626 // If we found compatible types, go ahead and push the bitcast
2627 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002628 Val = ConstantExpr::getBitCast(Val, NewTy);
2629 }
2630
Chris Lattner79c11012005-09-26 04:44:35 +00002631 MutatedMemory[Ptr] = Val;
2632 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002633 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002634 getVal(BO->getOperand(0)),
2635 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002636 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002637 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002638 getVal(CI->getOperand(0)),
2639 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002640 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002641 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002642 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002643 CI->getType());
2644 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002645 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2646 getVal(SI->getOperand(1)),
2647 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002648 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002649 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002650 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002651 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2652 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002653 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002654 InstResult =
2655 ConstantExpr::getGetElementPtr(P, GEPOps,
2656 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002657 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002658 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002659 Constant *Ptr = getVal(LI->getOperand(0));
2660 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2661 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2662 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002663 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002664 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002665 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002666 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002667 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002668 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002669 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002670 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002671 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002672 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2673 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002674
2675 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002676 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002677 ++CurInst;
2678 continue;
2679 }
2680
Chris Lattner7cd580f2006-07-07 21:37:01 +00002681 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002682 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002683
Nick Lewycky81266c52012-02-17 06:59:21 +00002684 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2685 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2686 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002687 Constant *Ptr = getVal(MSI->getDest());
2688 Constant *Val = getVal(MSI->getValue());
2689 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002690 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2691 // This memset is a no-op.
2692 ++CurInst;
2693 continue;
2694 }
2695 }
2696
2697 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2698 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2699 ++CurInst;
2700 continue;
2701 }
2702
2703 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2704 // We don't insert an entry into Values, as it doesn't have a
2705 // meaningful return value.
2706 if (!II->use_empty())
2707 return false;
2708 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002709 Value *PtrArg = getVal(II->getArgOperand(1));
2710 Value *Ptr = PtrArg->stripPointerCasts();
2711 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2712 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2713 if (!Size->isAllOnesValue() &&
2714 Size->getValue().getLimitedValue() >=
2715 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002716 Invariants.insert(GV);
2717 }
2718 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002719 ++CurInst;
2720 continue;
2721 }
2722 return false;
2723 }
2724
Chris Lattnercd271422005-09-27 04:45:34 +00002725 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002726 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002727 if (!Callee || Callee->mayBeOverridden())
2728 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002729
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002730 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002731 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002732 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002733
Reid Spencer5cbf9852007-01-30 20:08:39 +00002734 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002735 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002736 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002737 InstResult = C;
2738 } else {
2739 return false;
2740 }
2741 } else {
2742 if (Callee->getFunctionType()->isVarArg())
2743 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002744
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002745 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002746 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002747 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2748 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002749 return false;
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002750 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002751 InstResult = RetVal;
2752 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002753 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002754 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2755 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002756 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002757 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002758 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002759 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002760 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002761
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002762 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002763 }
2764 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2765 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002766 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002767 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002768 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002769 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002770 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002771 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002772 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002773 else
2774 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002775 } else if (isa<ReturnInst>(CurInst)) {
2776 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002777 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002778 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002779 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002780 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002781
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002782 // We succeeded at evaluating this block!
2783 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002784 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002785 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002786 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002787 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002788
Chris Lattner1945d582010-12-07 04:33:29 +00002789 if (!CurInst->use_empty()) {
2790 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002791 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002792
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002793 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002794 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002795
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002796 // If we just processed an invoke, we finished evaluating the block.
2797 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2798 NextBB = II->getNormalDest();
2799 return true;
2800 }
2801
Chris Lattner79c11012005-09-26 04:44:35 +00002802 // Advance program counter.
2803 ++CurInst;
2804 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002805}
2806
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002807/// EvaluateFunction - Evaluate a call to function F, returning true if
2808/// successful, false if we can't evaluate it. ActualArgs contains the formal
2809/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002810bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2811 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002812 // Check to see if this function is already executing (recursion). If so,
2813 // bail out. TODO: we might want to accept limited recursion.
2814 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2815 return false;
2816
2817 CallStack.push_back(F);
2818
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002819 // Initialize arguments to the incoming values specified.
2820 unsigned ArgNo = 0;
2821 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2822 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002823 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002824
2825 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2826 // we can only evaluate any one basic block at most once. This set keeps
2827 // track of what we have executed so we can detect recursive cases etc.
2828 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2829
2830 // CurBB - The current basic block we're evaluating.
2831 BasicBlock *CurBB = F->begin();
2832
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002833 BasicBlock::iterator CurInst = CurBB->begin();
2834
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002835 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002836 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002837 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002838 return false;
2839
2840 if (NextBB == 0) {
2841 // Successfully running until there's no next block means that we found
2842 // the return. Fill it the return value and pop the call stack.
2843 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2844 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002845 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002846 CallStack.pop_back();
2847 return true;
2848 }
2849
2850 // Okay, we succeeded in evaluating this control flow. See if we have
2851 // executed the new block before. If so, we have a looping function,
2852 // which we cannot evaluate in reasonable time.
2853 if (!ExecutedBlocks.insert(NextBB))
2854 return false; // looped!
2855
2856 // Okay, we have never been in this block before. Check to see if there
2857 // are any PHI nodes. If so, evaluate them with information about where
2858 // we came from.
2859 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002860 for (CurInst = NextBB->begin();
2861 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002862 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002863
2864 // Advance to the next block.
2865 CurBB = NextBB;
2866 }
2867}
2868
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002869/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2870/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002871static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2872 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002873 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002874 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002875 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002876 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2877 SmallVector<Constant*, 0>());
Chris Lattner1945d582010-12-07 04:33:29 +00002878
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002879 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002880 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002881 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002882 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002883 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002884 for (DenseMap<Constant*, Constant*>::const_iterator I =
2885 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002886 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002887 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002888 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2889 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2890 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002891 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002892 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002893
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002894 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002895}
2896
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002897/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2898/// Return true if anything changed.
2899bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2900 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2901 bool MadeChange = false;
2902 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002903
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002904 // Loop over global ctors, optimizing them when we can.
2905 for (unsigned i = 0; i != Ctors.size(); ++i) {
2906 Function *F = Ctors[i];
2907 // Found a null terminator in the middle of the list, prune off the rest of
2908 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002909 if (F == 0) {
2910 if (i != Ctors.size()-1) {
2911 Ctors.resize(i+1);
2912 MadeChange = true;
2913 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002914 break;
2915 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002916
Chris Lattner79c11012005-09-26 04:44:35 +00002917 // We cannot simplify external ctor functions.
2918 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002919
Chris Lattner79c11012005-09-26 04:44:35 +00002920 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002921 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002922 Ctors.erase(Ctors.begin()+i);
2923 MadeChange = true;
2924 --i;
2925 ++NumCtorsEvaluated;
2926 continue;
2927 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002928 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002929
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002930 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002931
Chris Lattner7b550cc2009-11-06 04:27:31 +00002932 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002933 return true;
2934}
2935
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002936bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002937 bool Changed = false;
2938
Duncan Sands177d84e2009-01-07 20:01:06 +00002939 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002940 I != E;) {
2941 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002942 // Aliases without names cannot be referenced outside this module.
2943 if (!J->hasName() && !J->isDeclaration())
2944 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002945 // If the aliasee may change at link time, nothing can be done - bail out.
2946 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002947 continue;
2948
Duncan Sands4782b302009-02-15 09:56:08 +00002949 Constant *Aliasee = J->getAliasee();
2950 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002951 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002952 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2953
2954 // Make all users of the alias use the aliasee instead.
2955 if (!J->use_empty()) {
2956 J->replaceAllUsesWith(Aliasee);
2957 ++NumAliasesResolved;
2958 Changed = true;
2959 }
2960
Duncan Sands7a154cf2009-12-08 10:10:20 +00002961 // If the alias is externally visible, we may still be able to simplify it.
2962 if (!J->hasLocalLinkage()) {
2963 // If the aliasee has internal linkage, give it the name and linkage
2964 // of the alias, and delete the alias. This turns:
2965 // define internal ... @f(...)
2966 // @a = alias ... @f
2967 // into:
2968 // define ... @a(...)
2969 if (!Target->hasLocalLinkage())
2970 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002971
Duncan Sands7a154cf2009-12-08 10:10:20 +00002972 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002973 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002974 // and other attributes of the aliasee with those of the alias.
2975 if (!hasOneUse)
2976 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002977
Duncan Sands7a154cf2009-12-08 10:10:20 +00002978 // Give the aliasee the name, linkage and other attributes of the alias.
2979 Target->takeName(J);
2980 Target->setLinkage(J->getLinkage());
2981 Target->GlobalValue::copyAttributesFrom(J);
2982 }
Duncan Sands4782b302009-02-15 09:56:08 +00002983
2984 // Delete the alias.
2985 M.getAliasList().erase(J);
2986 ++NumAliasesRemoved;
2987 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002988 }
2989
2990 return Changed;
2991}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002992
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002993static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2994 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00002995 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002996
2997 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Anders Carlssona201c4c2011-03-20 17:59:11 +00002998
2999 if (!Fn)
3000 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003001
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003002 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00003003
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003004 // Checking that the function has the right return type, the right number of
3005 // parameters and that they all have pointer types should be enough.
3006 if (!FTy->getReturnType()->isIntegerTy() ||
3007 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003008 !FTy->getParamType(0)->isPointerTy() ||
3009 !FTy->getParamType(1)->isPointerTy() ||
3010 !FTy->getParamType(2)->isPointerTy())
3011 return 0;
3012
3013 return Fn;
3014}
3015
3016/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3017/// destructor and can therefore be eliminated.
3018/// Note that we assume that other optimization passes have already simplified
3019/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003020/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3021/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003022static bool cxxDtorIsEmpty(const Function &Fn,
3023 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003024 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003025 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003026 if (Fn.isDeclaration())
3027 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003028
3029 if (++Fn.begin() != Fn.end())
3030 return false;
3031
3032 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3033 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3034 I != E; ++I) {
3035 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003036 // Ignore debug intrinsics.
3037 if (isa<DbgInfoIntrinsic>(CI))
3038 continue;
3039
Anders Carlssona201c4c2011-03-20 17:59:11 +00003040 const Function *CalledFn = CI->getCalledFunction();
3041
3042 if (!CalledFn)
3043 return false;
3044
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003045 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3046
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003047 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003048 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003049 return false;
3050
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003051 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003052 return false;
3053 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003054 return true; // We're done.
3055 else if (I->mayHaveSideEffects())
3056 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003057 }
3058
3059 return false;
3060}
3061
3062bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3063 /// Itanium C++ ABI p3.3.5:
3064 ///
3065 /// After constructing a global (or local static) object, that will require
3066 /// destruction on exit, a termination function is registered as follows:
3067 ///
3068 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3069 ///
3070 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3071 /// call f(p) when DSO d is unloaded, before all such termination calls
3072 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003073 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003074
3075 // This pass will look for calls to __cxa_atexit where the function is trivial
3076 // and remove them.
3077 bool Changed = false;
3078
3079 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
3080 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003081 // We're only interested in calls. Theoretically, we could handle invoke
3082 // instructions as well, but neither llvm-gcc nor clang generate invokes
3083 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003084 CallInst *CI = dyn_cast<CallInst>(*I++);
3085 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003086 continue;
3087
Anders Carlssona201c4c2011-03-20 17:59:11 +00003088 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003089 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003090 if (!DtorFn)
3091 continue;
3092
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003093 SmallPtrSet<const Function *, 8> CalledFunctions;
3094 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003095 continue;
3096
3097 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003098 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3099 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003100
Anders Carlssona201c4c2011-03-20 17:59:11 +00003101 ++NumCXXDtorsRemoved;
3102
3103 Changed |= true;
3104 }
3105
3106 return Changed;
3107}
3108
Chris Lattner7a90b682004-10-07 04:16:33 +00003109bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003110 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003111
Nick Lewycky6a577f82012-02-12 01:13:18 +00003112 TD = getAnalysisIfAvailable<TargetData>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003113 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003114
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003115 // Try to find the llvm.globalctors list.
3116 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003117
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003118 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003119
Chris Lattner7a90b682004-10-07 04:16:33 +00003120 bool LocalChange = true;
3121 while (LocalChange) {
3122 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003123
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003124 // Delete functions that are trivially dead, ccc -> fastcc
3125 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003126
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003127 // Optimize global_ctors list.
3128 if (GlobalCtors)
3129 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003130
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003131 // Optimize non-address-taken globals.
3132 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003133
3134 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003135 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003136
3137 // Try to remove trivial global destructors.
3138 if (CXAAtExitFn)
3139 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3140
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003141 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003142 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003143
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003144 // TODO: Move all global ctors functions to the end of the module for code
3145 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003146
Chris Lattner079236d2004-02-25 21:34:36 +00003147 return Changed;
3148}