blob: 54b97fabdc523c1050224a4b22e927499511cf9c [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"
Micah Villmow3574eca2012-10-08 16:38:25 +000028#include "llvm/DataLayout.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"
Zhou Sheng702aa2e2012-12-01 04:38:53 +000039#include "llvm/ADT/SetVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000041#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000042#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000043using namespace llvm;
44
Chris Lattner86453c52006-12-19 22:09:18 +000045STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000046STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000047STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
48STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
49STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
50STATISTIC(NumDeleted , "Number of globals deleted");
51STATISTIC(NumFnDeleted , "Number of functions deleted");
52STATISTIC(NumGlobUses , "Number of global uses devirtualized");
53STATISTIC(NumLocalized , "Number of globals localized");
54STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
55STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
56STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000057STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000058STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
59STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000060STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000061
Chris Lattner86453c52006-12-19 22:09:18 +000062namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000063 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000064 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000065 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000066 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000067 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000068 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000069 GlobalOpt() : ModulePass(ID) {
70 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
71 }
Misha Brukmanfd939082005-04-21 23:48:37 +000072
Chris Lattnerb12914b2004-09-20 04:48:05 +000073 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000074
75 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000076 GlobalVariable *FindGlobalCtors(Module &M);
77 bool OptimizeFunctions(Module &M);
78 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000079 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000080 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000081 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
82 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
83 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
84 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000085 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewycky6a577f82012-02-12 01:13:18 +000086
Micah Villmow3574eca2012-10-08 16:38:25 +000087 DataLayout *TD;
Nick Lewycky6a577f82012-02-12 01:13:18 +000088 TargetLibraryInfo *TLI;
Chris Lattner079236d2004-02-25 21:34:36 +000089 };
Chris Lattner079236d2004-02-25 21:34:36 +000090}
91
Dan Gohman844731a2008-05-13 00:00:25 +000092char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000093INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
94 "Global Variable Optimizer", false, false)
95INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
96INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000097 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000098
Chris Lattner7a90b682004-10-07 04:16:33 +000099ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +0000100
Dan Gohman844731a2008-05-13 00:00:25 +0000101namespace {
102
Chris Lattner7a90b682004-10-07 04:16:33 +0000103/// GlobalStatus - As we analyze each global, keep track of some information
104/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000105/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000106struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000107 /// isCompared - True if the global's address is used in a comparison.
108 bool isCompared;
109
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000110 /// isLoaded - True if the global is ever loaded. If the global isn't ever
111 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000112 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000113
114 /// StoredType - Keep track of what stores to the global look like.
115 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000116 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000117 /// NotStored - There is no store to this global. It can thus be marked
118 /// constant.
119 NotStored,
120
121 /// isInitializerStored - This global is stored to, but the only thing
122 /// stored is the constant it was initialized with. This is only tracked
123 /// for scalar globals.
124 isInitializerStored,
125
126 /// isStoredOnce - This global is stored to, but only its initializer and
127 /// one other value is ever stored to it. If this global isStoredOnce, we
128 /// track the value stored to it in StoredOnceValue below. This is only
129 /// tracked for scalar globals.
130 isStoredOnce,
131
132 /// isStored - This global is stored to by multiple values or something else
133 /// that we cannot track.
134 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000135 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000136
137 /// StoredOnceValue - If only one value (besides the initializer constant) is
138 /// ever stored to this global, keep track of what value it is.
139 Value *StoredOnceValue;
140
Chris Lattner25de4e52006-11-01 18:03:33 +0000141 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
142 /// null/false. When the first accessing function is noticed, it is recorded.
143 /// When a second different accessing function is noticed,
144 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000145 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000146 bool HasMultipleAccessingFunctions;
147
Chris Lattner25de4e52006-11-01 18:03:33 +0000148 /// HasNonInstructionUser - Set to true if this global has a user that is not
149 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000150 bool HasNonInstructionUser;
151
Chris Lattner25de4e52006-11-01 18:03:33 +0000152 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
153 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000154
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000155 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
156 AtomicOrdering Ordering;
157
Rafael Espindolac4440e32011-01-19 16:32:21 +0000158 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
159 StoredOnceValue(0), AccessingFunction(0),
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000160 HasMultipleAccessingFunctions(false),
161 HasNonInstructionUser(false), HasPHIUser(false),
162 Ordering(NotAtomic) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000163};
Chris Lattnere47ba742004-10-06 20:57:02 +0000164
Dan Gohman844731a2008-05-13 00:00:25 +0000165}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000166
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000167/// StrongerOrdering - Return the stronger of the two ordering. If the two
168/// orderings are acquire and release, then return AcquireRelease.
169///
170static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
171 if (X == Acquire && Y == Release) return AcquireRelease;
172 if (Y == Acquire && X == Release) return AcquireRelease;
173 return (AtomicOrdering)std::max(X, Y);
174}
175
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000176/// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
Nick Lewyckybc384a12012-02-05 19:48:37 +0000177/// by constants itself. Note that constants cannot be cyclic, so this test is
178/// pretty easy to implement recursively.
179///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000180static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000181 if (isa<GlobalValue>(C)) return false;
182
Gabor Greif27236912010-04-07 18:59:26 +0000183 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
184 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000185 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000186 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000187 } else
188 return false;
189 return true;
190}
191
192
Chris Lattner7a90b682004-10-07 04:16:33 +0000193/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
194/// structure. If the global has its address taken, return true to indicate we
195/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000196///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000197static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
198 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000199 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000200 ++UI) {
201 const User *U = *UI;
202 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000203 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000204
205 // If the result of the constantexpr isn't pointer type, then we won't
206 // know to expect it in various places. Just reject early.
207 if (!isa<PointerType>(CE->getType())) return true;
208
Chris Lattner7a90b682004-10-07 04:16:33 +0000209 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000210 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000211 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000212 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000213 if (GS.AccessingFunction == 0)
214 GS.AccessingFunction = F;
215 else if (GS.AccessingFunction != F)
216 GS.HasMultipleAccessingFunctions = true;
217 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000218 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000219 GS.isLoaded = true;
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000220 // Don't hack on volatile loads.
221 if (LI->isVolatile()) return true;
222 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000223 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000224 // Don't allow a store OF the address, only stores TO the address.
225 if (SI->getOperand(0) == V) return true;
226
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000227 // Don't hack on volatile stores.
228 if (SI->isVolatile()) return true;
Hans Wennborg18398582012-11-15 11:40:00 +0000229
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000230 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000231
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000232 // If this is a direct store to the global (i.e., the global is a scalar
233 // value, not an aggregate), keep more specific information about
234 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000235 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000236 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
237 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000238 Value *StoredVal = SI->getOperand(0);
Hans Wennborg18398582012-11-15 11:40:00 +0000239
240 if (Constant *C = dyn_cast<Constant>(StoredVal)) {
241 if (C->isThreadDependent()) {
242 // The stored value changes between threads; don't track it.
243 return true;
244 }
245 }
246
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000247 if (StoredVal == GV->getInitializer()) {
248 if (GS.StoredType < GlobalStatus::isInitializerStored)
249 GS.StoredType = GlobalStatus::isInitializerStored;
250 } else if (isa<LoadInst>(StoredVal) &&
251 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000252 if (GS.StoredType < GlobalStatus::isInitializerStored)
253 GS.StoredType = GlobalStatus::isInitializerStored;
254 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
255 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000256 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000257 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000258 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000259 // noop.
260 } else {
261 GS.StoredType = GlobalStatus::isStored;
262 }
263 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000264 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000265 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000266 }
Duncan Sandsb2fe7f12012-07-02 18:55:39 +0000267 } else if (isa<BitCastInst>(I)) {
268 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000269 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000270 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000271 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000272 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000273 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000274 // PHI nodes we can check just like select or GEP instructions, but we
275 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000276 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000277 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000278 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000279 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000280 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000281 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
282 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000283 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000284 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000285 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000286 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000287 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
288 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
289 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000290 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000291 } else {
292 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000293 }
Gabor Greife6642672010-07-09 16:51:20 +0000294 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000295 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000296 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000297 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000298 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000299 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000300 GS.HasNonInstructionUser = true;
301 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000302 return true;
303 }
Gabor Greife6642672010-07-09 16:51:20 +0000304 }
Chris Lattner079236d2004-02-25 21:34:36 +0000305
306 return false;
307}
308
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000309/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
310/// as a root? If so, we might not really want to eliminate the stores to it.
311static bool isLeakCheckerRoot(GlobalVariable *GV) {
312 // A global variable is a root if it is a pointer, or could plausibly contain
313 // a pointer. There are two challenges; one is that we could have a struct
314 // the has an inner member which is a pointer. We recurse through the type to
315 // detect these (up to a point). The other is that we may actually be a union
316 // of a pointer and another type, and so our LLVM type is an integer which
317 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
318 // potentially contained here.
319
320 if (GV->hasPrivateLinkage())
321 return false;
322
323 SmallVector<Type *, 4> Types;
324 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
325
326 unsigned Limit = 20;
327 do {
328 Type *Ty = Types.pop_back_val();
329 switch (Ty->getTypeID()) {
330 default: break;
331 case Type::PointerTyID: return true;
332 case Type::ArrayTyID:
333 case Type::VectorTyID: {
334 SequentialType *STy = cast<SequentialType>(Ty);
335 Types.push_back(STy->getElementType());
336 break;
337 }
338 case Type::StructTyID: {
339 StructType *STy = cast<StructType>(Ty);
340 if (STy->isOpaque()) return true;
341 for (StructType::element_iterator I = STy->element_begin(),
342 E = STy->element_end(); I != E; ++I) {
343 Type *InnerTy = *I;
344 if (isa<PointerType>(InnerTy)) return true;
345 if (isa<CompositeType>(InnerTy))
346 Types.push_back(InnerTy);
347 }
348 break;
349 }
350 }
351 if (--Limit == 0) return true;
352 } while (!Types.empty());
353 return false;
354}
355
356/// Given a value that is stored to a global but never read, determine whether
357/// it's safe to remove the store and the chain of computation that feeds the
358/// store.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000359static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000360 do {
361 if (isa<Constant>(V))
362 return true;
363 if (!V->hasOneUse())
364 return false;
Nick Lewyckyb8cd66b2012-07-25 21:19:40 +0000365 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
366 isa<GlobalValue>(V))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000367 return false;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000368 if (isAllocationFn(V, TLI))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000369 return true;
370
371 Instruction *I = cast<Instruction>(V);
372 if (I->mayHaveSideEffects())
373 return false;
374 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
375 if (!GEP->hasAllConstantIndices())
376 return false;
377 } else if (I->getNumOperands() != 1) {
378 return false;
379 }
380
381 V = I->getOperand(0);
382 } while (1);
383}
384
385/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
386/// of the global and clean up any that obviously don't assign the global a
387/// value that isn't dynamically allocated.
388///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000389static bool CleanupPointerRootUsers(GlobalVariable *GV,
390 const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000391 // A brief explanation of leak checkers. The goal is to find bugs where
392 // pointers are forgotten, causing an accumulating growth in memory
393 // usage over time. The common strategy for leak checkers is to whitelist the
394 // memory pointed to by globals at exit. This is popular because it also
395 // solves another problem where the main thread of a C++ program may shut down
396 // before other threads that are still expecting to use those globals. To
397 // handle that case, we expect the program may create a singleton and never
398 // destroy it.
399
400 bool Changed = false;
401
402 // If Dead[n].first is the only use of a malloc result, we can delete its
403 // chain of computation and the store to the global in Dead[n].second.
404 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
405
406 // Constants can't be pointers to dynamically allocated memory.
407 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
408 UI != E;) {
409 User *U = *UI++;
410 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
411 Value *V = SI->getValueOperand();
412 if (isa<Constant>(V)) {
413 Changed = true;
414 SI->eraseFromParent();
415 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
416 if (I->hasOneUse())
417 Dead.push_back(std::make_pair(I, SI));
418 }
419 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
420 if (isa<Constant>(MSI->getValue())) {
421 Changed = true;
422 MSI->eraseFromParent();
423 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
424 if (I->hasOneUse())
425 Dead.push_back(std::make_pair(I, MSI));
426 }
427 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
428 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
429 if (MemSrc && MemSrc->isConstant()) {
430 Changed = true;
431 MTI->eraseFromParent();
432 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
433 if (I->hasOneUse())
434 Dead.push_back(std::make_pair(I, MTI));
435 }
436 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
437 if (CE->use_empty()) {
438 CE->destroyConstant();
439 Changed = true;
440 }
441 } else if (Constant *C = dyn_cast<Constant>(U)) {
442 if (SafeToDestroyConstant(C)) {
443 C->destroyConstant();
444 // This could have invalidated UI, start over from scratch.
445 Dead.clear();
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000446 CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000447 return true;
448 }
449 }
450 }
451
452 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000453 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000454 Dead[i].second->eraseFromParent();
455 Instruction *I = Dead[i].first;
456 do {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000457 if (isAllocationFn(I, TLI))
Nick Lewycky952f5d52012-07-24 21:33:00 +0000458 break;
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000459 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
460 if (!J)
461 break;
462 I->eraseFromParent();
463 I = J;
Nick Lewycky952f5d52012-07-24 21:33:00 +0000464 } while (1);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000465 I->eraseFromParent();
466 }
467 }
468
469 return Changed;
470}
471
Chris Lattnere47ba742004-10-06 20:57:02 +0000472/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
473/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000474/// quick scan over the use list to clean up the easy and obvious cruft. This
475/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000476static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Micah Villmow3574eca2012-10-08 16:38:25 +0000477 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000478 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000479 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
480 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000481
Chris Lattner7a90b682004-10-07 04:16:33 +0000482 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000483 if (Init) {
484 // Replace the load with the initializer.
485 LI->replaceAllUsesWith(Init);
486 LI->eraseFromParent();
487 Changed = true;
488 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000489 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000490 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000491 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000492 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000493 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
494 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000495 Constant *SubInit = 0;
496 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000497 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000498 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000499 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000500 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000501 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000502 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000503 }
504
505 if (CE->use_empty()) {
506 CE->destroyConstant();
507 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000508 }
509 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000510 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
511 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
512 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000513 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000514 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000515 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000516 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000517 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000518 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000519
520 // If the initializer is an all-null value and we have an inbounds GEP,
521 // we already know what the result of any load from that GEP is.
522 // TODO: Handle splats.
523 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
524 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000525 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000526 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000527
Chris Lattner031955d2004-10-10 16:43:46 +0000528 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000529 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000530 Changed = true;
531 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000532 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
533 if (MI->getRawDest() == V) {
534 MI->eraseFromParent();
535 Changed = true;
536 }
537
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000538 } else if (Constant *C = dyn_cast<Constant>(U)) {
539 // If we have a chain of dead constantexprs or other things dangling from
540 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000541 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000542 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000543 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000544 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000545 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000546 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000547 }
548 }
Chris Lattner031955d2004-10-10 16:43:46 +0000549 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000550}
551
Chris Lattner941db492008-01-14 02:09:12 +0000552/// isSafeSROAElementUse - Return true if the specified instruction is a safe
553/// user of a derived expression from a global that we want to SROA.
554static bool isSafeSROAElementUse(Value *V) {
555 // We might have a dead and dangling constant hanging off of here.
556 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000557 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000558
Chris Lattner941db492008-01-14 02:09:12 +0000559 Instruction *I = dyn_cast<Instruction>(V);
560 if (!I) return false;
561
562 // Loads are ok.
563 if (isa<LoadInst>(I)) return true;
564
565 // Stores *to* the pointer are ok.
566 if (StoreInst *SI = dyn_cast<StoreInst>(I))
567 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000568
Chris Lattner941db492008-01-14 02:09:12 +0000569 // Otherwise, it must be a GEP.
570 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
571 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000572
Chris Lattner941db492008-01-14 02:09:12 +0000573 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
574 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
575 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000576
Chris Lattner941db492008-01-14 02:09:12 +0000577 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
578 I != E; ++I)
579 if (!isSafeSROAElementUse(*I))
580 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000581 return true;
582}
583
Chris Lattner941db492008-01-14 02:09:12 +0000584
585/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
586/// Look at it and its uses and decide whether it is safe to SROA this global.
587///
588static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
589 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000590 if (!isa<GetElementPtrInst>(U) &&
591 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000592 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
593 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000594
Chris Lattner941db492008-01-14 02:09:12 +0000595 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
596 // don't like < 3 operand CE's, and we don't like non-constant integer
597 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
598 // value of C.
599 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
600 !cast<Constant>(U->getOperand(1))->isNullValue() ||
601 !isa<ConstantInt>(U->getOperand(2)))
602 return false;
603
604 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
605 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000606
Chris Lattner941db492008-01-14 02:09:12 +0000607 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000608 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000609 uint64_t NumElements = AT->getNumElements();
610 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000611
Chris Lattner941db492008-01-14 02:09:12 +0000612 // Check to make sure that index falls within the array. If not,
613 // something funny is going on, so we won't do the optimization.
614 //
615 if (Idx->getZExtValue() >= NumElements)
616 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000617
Chris Lattner941db492008-01-14 02:09:12 +0000618 // We cannot scalar repl this level of the array unless any array
619 // sub-indices are in-range constants. In particular, consider:
620 // A[0][i]. We cannot know that the user isn't doing invalid things like
621 // allowing i to index an out-of-range subscript that accesses A[1].
622 //
623 // Scalar replacing *just* the outer index of the array is probably not
624 // going to be a win anyway, so just give up.
625 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000626 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000627 ++GEPI) {
628 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000629 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000630 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000631 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000632 NumElements = SubVectorTy->getNumElements();
633 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000634 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000635 "Indexed GEP type is not array, vector, or struct!");
636 continue;
637 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000638
Chris Lattner941db492008-01-14 02:09:12 +0000639 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
640 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
641 return false;
642 }
643 }
644
645 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
646 if (!isSafeSROAElementUse(*I))
647 return false;
648 return true;
649}
650
651/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
652/// is safe for us to perform this transformation.
653///
654static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
655 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
656 UI != E; ++UI) {
657 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
658 return false;
659 }
660 return true;
661}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000662
Chris Lattner941db492008-01-14 02:09:12 +0000663
Chris Lattner670c8892004-10-08 17:32:09 +0000664/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
665/// variable. This opens the door for other optimizations by exposing the
666/// behavior of the program in a more fine-grained way. We have determined that
667/// this transformation is safe already. We return the first global variable we
668/// insert so that the caller can reprocess it.
Micah Villmow3574eca2012-10-08 16:38:25 +0000669static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000670 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000671 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000672 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000673
Rafael Espindolabb46f522009-01-15 20:18:42 +0000674 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000675 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000676 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000677
Chris Lattner670c8892004-10-08 17:32:09 +0000678 std::vector<GlobalVariable*> NewGlobals;
679 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
680
Chris Lattner998182b2008-04-26 07:40:11 +0000681 // Get the alignment of the global, either explicit or target-specific.
682 unsigned StartAlignment = GV->getAlignment();
683 if (StartAlignment == 0)
684 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000685
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000686 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000687 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000688 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000689 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000690 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000691 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000692 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000693 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000694 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000695 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000696 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000697 Globals.insert(GV, NGV);
698 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000699
Chris Lattner998182b2008-04-26 07:40:11 +0000700 // Calculate the known alignment of the field. If the original aggregate
701 // had 256 byte alignment for example, something might depend on that:
702 // propagate info to each field.
703 uint64_t FieldOffset = Layout.getElementOffset(i);
704 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
705 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
706 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000707 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000708 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000709 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000710 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000711 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000712 else
Chris Lattner998182b2008-04-26 07:40:11 +0000713 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000714
Chris Lattner1f21ef12005-02-23 16:53:04 +0000715 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000716 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000717 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000718
Duncan Sands777d2302009-05-09 07:06:46 +0000719 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000720 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000721 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000722 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000723 assert(In && "Couldn't get element of initializer?");
724
Chris Lattner7b550cc2009-11-06 04:27:31 +0000725 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000726 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000727 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000728 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000729 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000730 Globals.insert(GV, NGV);
731 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000732
Chris Lattner998182b2008-04-26 07:40:11 +0000733 // Calculate the known alignment of the field. If the original aggregate
734 // had 256 byte alignment for example, something might depend on that:
735 // propagate info to each field.
736 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
737 if (NewAlign > EltAlign)
738 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000739 }
740 }
741
742 if (NewGlobals.empty())
743 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000744
David Greene3215b0e2010-01-05 01:28:05 +0000745 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000746
Chris Lattner7b550cc2009-11-06 04:27:31 +0000747 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000748
749 // Loop over all of the uses of the global, replacing the constantexpr geps,
750 // with smaller constantexpr geps or direct references.
751 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000752 User *GEP = GV->use_back();
753 assert(((isa<ConstantExpr>(GEP) &&
754 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
755 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000756
Chris Lattner670c8892004-10-08 17:32:09 +0000757 // Ignore the 1th operand, which has to be zero or else the program is quite
758 // broken (undefined). Get the 2nd operand, which is the structure or array
759 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000760 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000761 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
762
Chris Lattner30ba5692004-10-11 05:54:41 +0000763 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000764
765 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000766 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000767 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000768 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000769 Idxs.push_back(NullInt);
770 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
771 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000772 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000773 } else {
774 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000775 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000776 Idxs.push_back(NullInt);
777 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
778 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000779 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000780 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000781 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000782 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000783 GEP->replaceAllUsesWith(NewPtr);
784
785 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000786 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000787 else
788 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000789 }
790
Chris Lattnere40e2d12004-10-08 20:25:55 +0000791 // Delete the old global, now that it is dead.
792 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000793 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000794
795 // Loop over the new globals array deleting any globals that are obviously
796 // dead. This can arise due to scalarization of a structure or an array that
797 // has elements that are dead.
798 unsigned FirstGlobal = 0;
799 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
800 if (NewGlobals[i]->use_empty()) {
801 Globals.erase(NewGlobals[i]);
802 if (FirstGlobal == i) ++FirstGlobal;
803 }
804
805 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000806}
807
Chris Lattner9b34a612004-10-09 21:48:45 +0000808/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000809/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000810/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000811static bool AllUsesOfValueWillTrapIfNull(const Value *V,
812 SmallPtrSet<const PHINode*, 8> &PHIs) {
813 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000814 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000815 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000816
817 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000818 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000819 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000820 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000821 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000822 return false; // Storing the value.
823 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000824 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000825 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000826 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000827 return false; // Not calling the ptr
828 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000829 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000830 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000831 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000832 return false; // Not calling the ptr
833 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000834 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000835 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000836 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000837 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000838 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000839 // If we've already seen this phi node, ignore it, it has already been
840 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000841 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
842 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000843 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000844 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000845 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000846 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000847 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000848 return false;
849 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000850 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000851 return true;
852}
853
854/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000855/// from GV will trap if the loaded value is null. Note that this also permits
856/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000857static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
858 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000859 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000860 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000861
Gabor Greif6ce02b52010-04-06 19:24:18 +0000862 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
863 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000864 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000865 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000866 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000867 // Ignore stores to the global.
868 } else {
869 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000870 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000871 return false;
872 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000873 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000874 return true;
875}
876
Chris Lattner7b550cc2009-11-06 04:27:31 +0000877static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000878 bool Changed = false;
879 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
880 Instruction *I = cast<Instruction>(*UI++);
881 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
882 LI->setOperand(0, NewV);
883 Changed = true;
884 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
885 if (SI->getOperand(1) == V) {
886 SI->setOperand(1, NewV);
887 Changed = true;
888 }
889 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000890 CallSite CS(I);
891 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000892 // Calling through the pointer! Turn into a direct call, but be careful
893 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000894 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000895 Changed = true;
896 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000897 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
898 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000899 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000900 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000901 }
902
903 if (PassedAsArg) {
904 // Being passed as an argument also. Be careful to not invalidate UI!
905 UI = V->use_begin();
906 }
907 }
908 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
909 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000910 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000911 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000912 if (CI->use_empty()) {
913 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000914 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000915 }
916 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
917 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000918 SmallVector<Constant*, 8> Idxs;
919 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000920 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
921 i != e; ++i)
922 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000923 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000924 else
925 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000926 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000927 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000928 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000929 if (GEPI->use_empty()) {
930 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000931 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000932 }
933 }
934 }
935
936 return Changed;
937}
938
939
940/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
941/// value stored into it. If there are uses of the loaded value that would trap
942/// if the loaded value is dynamically null, then we know that they cannot be
943/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000944static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Micah Villmow3574eca2012-10-08 16:38:25 +0000945 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000946 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000947 bool Changed = false;
948
Chris Lattner92c6bd22009-01-14 00:12:58 +0000949 // Keep track of whether we are able to remove all the uses of the global
950 // other than the store that defines it.
951 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000952
Chris Lattner708148e2004-10-10 23:14:11 +0000953 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000954 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
955 User *GlobalUser = *GUI++;
956 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000957 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000958 // If we were able to delete all uses of the loads
959 if (LI->use_empty()) {
960 LI->eraseFromParent();
961 Changed = true;
962 } else {
963 AllNonStoreUsesGone = false;
964 }
965 } else if (isa<StoreInst>(GlobalUser)) {
966 // Ignore the store that stores "LV" to the global.
967 assert(GlobalUser->getOperand(1) == GV &&
968 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000969 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000970 AllNonStoreUsesGone = false;
971
972 // If we get here we could have other crazy uses that are transitively
973 // loaded.
974 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramerab164232012-09-28 10:01:27 +0000975 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
976 isa<BitCastInst>(GlobalUser) ||
977 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner98a42b22011-05-22 07:15:13 +0000978 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000979 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000980 }
Chris Lattner708148e2004-10-10 23:14:11 +0000981
982 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000983 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000984 ++NumGlobUses;
985 }
986
Chris Lattner708148e2004-10-10 23:14:11 +0000987 // If we nuked all of the loads, then none of the stores are needed either,
988 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000989 if (AllNonStoreUsesGone) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000990 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000991 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000992 } else {
993 Changed = true;
994 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
995 }
Chris Lattner708148e2004-10-10 23:14:11 +0000996 if (GV->use_empty()) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000997 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
998 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000999 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +00001000 ++NumDeleted;
1001 }
Chris Lattner708148e2004-10-10 23:14:11 +00001002 }
1003 return Changed;
1004}
1005
Chris Lattner30ba5692004-10-11 05:54:41 +00001006/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
1007/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001008static void ConstantPropUsersOf(Value *V,
Micah Villmow3574eca2012-10-08 16:38:25 +00001009 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001010 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
1011 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +00001012 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001013 I->replaceAllUsesWith(NewC);
1014
Chris Lattnerd514d822005-02-01 01:23:31 +00001015 // Advance UI to the next non-I use to avoid invalidating it!
1016 // Instructions could multiply use V.
1017 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +00001018 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +00001019 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +00001020 }
1021}
1022
1023/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
1024/// variable, and transforms the program as if it always contained the result of
1025/// the specified malloc. Because it is always the result of the specified
1026/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001027/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001028static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001029 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001030 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +00001031 ConstantInt *NElements,
Micah Villmow3574eca2012-10-08 16:38:25 +00001032 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001033 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +00001034 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001035
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001036 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +00001037 if (NElements->getZExtValue() == 1)
1038 GlobalType = AllocTy;
1039 else
1040 // If we have an array allocation, the global variable is of an array.
1041 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +00001042
1043 // Create the new global variable. The contents of the malloc'd memory is
1044 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001045 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +00001046 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +00001047 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +00001048 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +00001049 GV->getName()+".body",
1050 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001051 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001052
Chris Lattnera6874652010-02-25 22:33:52 +00001053 // If there are bitcast users of the malloc (which is typical, usually we have
1054 // a malloc + bitcast) then replace them with uses of the new global. Update
1055 // other users to use the global as well.
1056 BitCastInst *TheBC = 0;
1057 while (!CI->use_empty()) {
1058 Instruction *User = cast<Instruction>(CI->use_back());
1059 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1060 if (BCI->getType() == NewGV->getType()) {
1061 BCI->replaceAllUsesWith(NewGV);
1062 BCI->eraseFromParent();
1063 } else {
1064 BCI->setOperand(0, NewGV);
1065 }
1066 } else {
1067 if (TheBC == 0)
1068 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1069 User->replaceUsesOfWith(CI, TheBC);
1070 }
1071 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001072
Victor Hernandez83d63912009-09-18 22:35:49 +00001073 Constant *RepValue = NewGV;
1074 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001075 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +00001076 GV->getType()->getElementType());
1077
1078 // If there is a comparison against null, we will insert a global bool to
1079 // keep track of whether the global was initialized yet or not.
1080 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001081 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +00001082 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001083 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +00001084 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001085 bool InitBoolUsed = false;
1086
1087 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +00001088 while (!GV->use_empty()) {
1089 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001090 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001091 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1092 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001093 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +00001094 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +00001095 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001096
Chris Lattnera6874652010-02-25 22:33:52 +00001097 LoadInst *LI = cast<LoadInst>(GV->use_back());
1098 while (!LI->use_empty()) {
1099 Use &LoadUse = LI->use_begin().getUse();
1100 if (!isa<ICmpInst>(LoadUse.getUser())) {
1101 LoadUse = RepValue;
1102 continue;
1103 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001104
Chris Lattnera6874652010-02-25 22:33:52 +00001105 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1106 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001107 // Sink the load to where the compare was, if atomic rules allow us to.
1108 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1109 LI->getOrdering(), LI->getSynchScope(),
1110 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +00001111 InitBoolUsed = true;
1112 switch (ICI->getPredicate()) {
1113 default: llvm_unreachable("Unknown ICmp Predicate!");
1114 case ICmpInst::ICMP_ULT:
1115 case ICmpInst::ICMP_SLT: // X < null -> always false
1116 LV = ConstantInt::getFalse(GV->getContext());
1117 break;
1118 case ICmpInst::ICMP_ULE:
1119 case ICmpInst::ICMP_SLE:
1120 case ICmpInst::ICMP_EQ:
1121 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1122 break;
1123 case ICmpInst::ICMP_NE:
1124 case ICmpInst::ICMP_UGE:
1125 case ICmpInst::ICMP_SGE:
1126 case ICmpInst::ICMP_UGT:
1127 case ICmpInst::ICMP_SGT:
1128 break; // no change.
1129 }
1130 ICI->replaceAllUsesWith(LV);
1131 ICI->eraseFromParent();
1132 }
1133 LI->eraseFromParent();
1134 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001135
1136 // If the initialization boolean was used, insert it, otherwise delete it.
1137 if (!InitBoolUsed) {
1138 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +00001139 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001140 delete InitBool;
1141 } else
1142 GV->getParent()->getGlobalList().insert(GV, InitBool);
1143
Chris Lattnera6874652010-02-25 22:33:52 +00001144 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +00001145 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001146 CI->eraseFromParent();
1147
1148 // To further other optimizations, loop over all users of NewGV and try to
1149 // constant prop them. This will promote GEP instructions with constant
1150 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001151 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001152 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +00001153 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001154
1155 return NewGV;
1156}
1157
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001158/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1159/// to make sure that there are no complex uses of V. We permit simple things
1160/// like dereferencing the pointer, but not storing through the address, unless
1161/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +00001162static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1163 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +00001164 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001165 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +00001166 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001167 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +00001168
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001169 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1170 continue; // Fine, ignore.
1171 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001172
Gabor Greif0b520db2010-04-06 18:58:22 +00001173 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001174 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1175 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001176 continue; // Otherwise, storing through it, or storing into GV... fine.
1177 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001178
Chris Lattnera2fb2342010-04-10 18:19:22 +00001179 // Must index into the array and into the struct.
1180 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001181 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001182 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001183 continue;
1184 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001185
Gabor Greif0b520db2010-04-06 18:58:22 +00001186 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001187 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1188 // cycles.
1189 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001190 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1191 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001192 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001193 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001194
Gabor Greif0b520db2010-04-06 18:58:22 +00001195 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001196 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1197 return false;
1198 continue;
1199 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001200
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001201 return false;
1202 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001203 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001204}
1205
Chris Lattner86395032006-09-30 23:32:09 +00001206/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1207/// somewhere. Transform all uses of the allocation into loads from the
1208/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001209/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001210/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001211static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001212 GlobalVariable *GV) {
1213 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001214 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1215 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001216 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1217 // If this is the store of the allocation into the global, remove it.
1218 if (SI->getOperand(1) == GV) {
1219 SI->eraseFromParent();
1220 continue;
1221 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001222 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1223 // Insert the load in the corresponding predecessor, not right before the
1224 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001225 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001226 } else if (isa<BitCastInst>(U)) {
1227 // Must be bitcast between the malloc and store to initialize the global.
1228 ReplaceUsesOfMallocWithGlobal(U, GV);
1229 U->eraseFromParent();
1230 continue;
1231 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1232 // If this is a "GEP bitcast" and the user is a store to the global, then
1233 // just process it as a bitcast.
1234 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1235 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1236 if (SI->getOperand(1) == GV) {
1237 // Must be bitcast GEP between the malloc and store to initialize
1238 // the global.
1239 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1240 GEPI->eraseFromParent();
1241 continue;
1242 }
Chris Lattner86395032006-09-30 23:32:09 +00001243 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001244
Chris Lattner86395032006-09-30 23:32:09 +00001245 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001246 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001247 U->replaceUsesOfWith(Alloc, NL);
1248 }
1249}
1250
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001251/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1252/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1253/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001254static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001255 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1256 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001257 // We permit two users of the load: setcc comparing against the null
1258 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001259 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1260 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001261 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001262
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001263 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001264 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001265 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1266 return false;
1267 continue;
1268 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001269
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001270 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001271 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001272 // Must index into the array and into the struct.
1273 if (GEPI->getNumOperands() < 3)
1274 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001275
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001276 // Otherwise the GEP is ok.
1277 continue;
1278 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001279
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001280 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001281 if (!LoadUsingPHIsPerLoad.insert(PN))
1282 // This means some phi nodes are dependent on each other.
1283 // Avoid infinite looping!
1284 return false;
1285 if (!LoadUsingPHIs.insert(PN))
1286 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001287 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001288
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001289 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001290 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1291 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001292 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001293
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001294 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001295 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001296
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001297 // Otherwise we don't know what this is, not ok.
1298 return false;
1299 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001300
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001301 return true;
1302}
1303
1304
1305/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1306/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001307static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001308 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001309 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1310 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001311 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1312 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001313 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001314 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1315 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001316 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001317 LoadUsingPHIsPerLoad.clear();
1318 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001319
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001320 // If we reach here, we know that all uses of the loads and transitive uses
1321 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001322 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001323 // Check to verify that all operands of the PHIs are either PHIS that can be
1324 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001325 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1326 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001327 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001328 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1329 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001330
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001331 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001332 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001333
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001334 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001335 // One of the PHIs in our set is (optimistically) ok.
1336 if (LoadUsingPHIs.count(InPN))
1337 continue;
1338 return false;
1339 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001340
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001341 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001342 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001343 if (LI->getOperand(0) == GV)
1344 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001345
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001346 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001347
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001348 // Anything else is rejected.
1349 return false;
1350 }
1351 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001352
Chris Lattner86395032006-09-30 23:32:09 +00001353 return true;
1354}
1355
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001356static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1357 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001358 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001359 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001360
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001361 if (FieldNo >= FieldVals.size())
1362 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001363
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001364 // If we already have this value, just reuse the previously scalarized
1365 // version.
1366 if (Value *FieldVal = FieldVals[FieldNo])
1367 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001368
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001369 // Depending on what instruction this is, we have several cases.
1370 Value *Result;
1371 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1372 // This is a scalarized version of the load from the global. Just create
1373 // a new Load of the scalarized global.
1374 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1375 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001376 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001377 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001378 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1379 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1380 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001381 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001382 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001383
Jay Foadd8b4fb42011-03-30 11:19:20 +00001384 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001385 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001386 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001387 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001388 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001389 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1390 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001391 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001392 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001393
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001394 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001395}
1396
Chris Lattner330245e2007-09-13 17:29:05 +00001397/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1398/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001399static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001400 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001401 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001402 // If this is a comparison against null, handle it.
1403 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1404 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1405 // If we have a setcc of the loaded pointer, we can use a setcc of any
1406 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001407 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001408 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001409
Owen Anderson333c4002009-07-09 23:48:35 +00001410 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001411 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001412 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001413 SCI->replaceAllUsesWith(New);
1414 SCI->eraseFromParent();
1415 return;
1416 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001417
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001418 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001419 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1420 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1421 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001422
Chris Lattnera637a8b2007-09-13 18:00:31 +00001423 // Load the pointer for this field.
1424 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001425 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001426 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001427
Chris Lattnera637a8b2007-09-13 18:00:31 +00001428 // Create the new GEP idx vector.
1429 SmallVector<Value*, 8> GEPIdx;
1430 GEPIdx.push_back(GEPI->getOperand(1));
1431 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001432
Jay Foada9203102011-07-25 09:48:08 +00001433 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001434 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001435 GEPI->replaceAllUsesWith(NGEPI);
1436 GEPI->eraseFromParent();
1437 return;
1438 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001439
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001440 // Recursively transform the users of PHI nodes. This will lazily create the
1441 // PHIs that are needed for individual elements. Keep track of what PHIs we
1442 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1443 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1444 // already been seen first by another load, so its uses have already been
1445 // processed.
1446 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001447 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1448 std::vector<Value*>())).second)
1449 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001450
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001451 // If this is the first time we've seen this PHI, recursively process all
1452 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001453 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); 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 }
Chris Lattner330245e2007-09-13 17:29:05 +00001457}
1458
Chris Lattner86395032006-09-30 23:32:09 +00001459/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1460/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1461/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001462/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001463static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001464 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001465 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001466 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001467 UI != E; ) {
1468 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001469 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001470 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001471
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001472 if (Load->use_empty()) {
1473 Load->eraseFromParent();
1474 InsertedScalarizedValues.erase(Load);
1475 }
Chris Lattner86395032006-09-30 23:32:09 +00001476}
1477
Victor Hernandez83d63912009-09-18 22:35:49 +00001478/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1479/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001480static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001481 Value *NElems, DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001482 const TargetLibraryInfo *TLI) {
David Greene3215b0e2010-01-05 01:28:05 +00001483 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001484 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001485 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001486
1487 // There is guaranteed to be at least one use of the malloc (storing
1488 // it into GV). If there are other uses, change them to be uses of
1489 // the global to simplify later code. This also deletes the store
1490 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001491 ReplaceUsesOfMallocWithGlobal(CI, GV);
1492
Victor Hernandez83d63912009-09-18 22:35:49 +00001493 // Okay, at this point, there are no users of the malloc. Insert N
1494 // new mallocs at the same place as CI, and N globals.
1495 std::vector<Value*> FieldGlobals;
1496 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001497
Victor Hernandez83d63912009-09-18 22:35:49 +00001498 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001499 Type *FieldTy = STy->getElementType(FieldNo);
1500 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001501
Victor Hernandez83d63912009-09-18 22:35:49 +00001502 GlobalVariable *NGV =
1503 new GlobalVariable(*GV->getParent(),
1504 PFieldTy, false, GlobalValue::InternalLinkage,
1505 Constant::getNullValue(PFieldTy),
1506 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001507 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001508 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001509
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001510 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001511 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001512 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001513 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001514 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1515 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001516 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001517 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001518 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001519 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001520 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001521
Victor Hernandez83d63912009-09-18 22:35:49 +00001522 // The tricky aspect of this transformation is handling the case when malloc
1523 // fails. In the original code, malloc failing would set the result pointer
1524 // of malloc to null. In this case, some mallocs could succeed and others
1525 // could fail. As such, we emit code that looks like this:
1526 // F0 = malloc(field0)
1527 // F1 = malloc(field1)
1528 // F2 = malloc(field2)
1529 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1530 // if (F0) { free(F0); F0 = 0; }
1531 // if (F1) { free(F1); F1 = 0; }
1532 // if (F2) { free(F2); F2 = 0; }
1533 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001534 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001535 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1536 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001537 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001538 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001539 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1540 Constant::getNullValue(FieldMallocs[i]->getType()),
1541 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001542 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001543 }
1544
1545 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001546 BasicBlock *OrigBB = CI->getParent();
1547 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001548
Victor Hernandez83d63912009-09-18 22:35:49 +00001549 // Create the block to check the first condition. Put all these blocks at the
1550 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001551 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1552 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001553 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001554
Victor Hernandez83d63912009-09-18 22:35:49 +00001555 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1556 // branch on RunningOr.
1557 OrigBB->getTerminator()->eraseFromParent();
1558 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001559
Victor Hernandez83d63912009-09-18 22:35:49 +00001560 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1561 // pointer, because some may be null while others are not.
1562 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1563 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001564 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001565 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001566 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001567 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001568 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001569 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001570 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1571 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001572
1573 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001574 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001575 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1576 FreeBlock);
1577 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001578
Victor Hernandez83d63912009-09-18 22:35:49 +00001579 NullPtrBlock = NextBlock;
1580 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001581
Victor Hernandez83d63912009-09-18 22:35:49 +00001582 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001583
1584 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001585 CI->eraseFromParent();
1586
1587 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1588 /// update all uses of the load, keep track of what scalarized loads are
1589 /// inserted for a given load.
1590 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1591 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001592
Victor Hernandez83d63912009-09-18 22:35:49 +00001593 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001594
Victor Hernandez83d63912009-09-18 22:35:49 +00001595 // Okay, the malloc site is completely handled. All of the uses of GV are now
1596 // loads, and all uses of those loads are simple. Rewrite them to use loads
1597 // of the per-field globals instead.
1598 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1599 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001600
Victor Hernandez83d63912009-09-18 22:35:49 +00001601 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001602 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001603 continue;
1604 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001605
Victor Hernandez83d63912009-09-18 22:35:49 +00001606 // Must be a store of null.
1607 StoreInst *SI = cast<StoreInst>(User);
1608 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1609 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001610
Victor Hernandez83d63912009-09-18 22:35:49 +00001611 // Insert a store of null into each global.
1612 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001613 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001614 Constant *Null = Constant::getNullValue(PT->getElementType());
1615 new StoreInst(Null, FieldGlobals[i], SI);
1616 }
1617 // Erase the original store.
1618 SI->eraseFromParent();
1619 }
1620
1621 // While we have PHIs that are interesting to rewrite, do it.
1622 while (!PHIsToRewrite.empty()) {
1623 PHINode *PN = PHIsToRewrite.back().first;
1624 unsigned FieldNo = PHIsToRewrite.back().second;
1625 PHIsToRewrite.pop_back();
1626 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1627 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1628
1629 // Add all the incoming values. This can materialize more phis.
1630 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1631 Value *InVal = PN->getIncomingValue(i);
1632 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001633 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001634 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1635 }
1636 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001637
Victor Hernandez83d63912009-09-18 22:35:49 +00001638 // Drop all inter-phi links and any loads that made it this far.
1639 for (DenseMap<Value*, std::vector<Value*> >::iterator
1640 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1641 I != E; ++I) {
1642 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1643 PN->dropAllReferences();
1644 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1645 LI->dropAllReferences();
1646 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001647
Victor Hernandez83d63912009-09-18 22:35:49 +00001648 // Delete all the phis and loads now that inter-references are dead.
1649 for (DenseMap<Value*, std::vector<Value*> >::iterator
1650 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1651 I != E; ++I) {
1652 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1653 PN->eraseFromParent();
1654 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1655 LI->eraseFromParent();
1656 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001657
Victor Hernandez83d63912009-09-18 22:35:49 +00001658 // The old global is now dead, remove it.
1659 GV->eraseFromParent();
1660
1661 ++NumHeapSRA;
1662 return cast<GlobalVariable>(FieldGlobals[0]);
1663}
1664
Chris Lattnere61d0a62008-12-15 21:02:25 +00001665/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1666/// pointer global variable with a single value stored it that is a malloc or
1667/// cast of malloc.
1668static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001669 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001670 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001671 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001672 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001673 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001674 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001675 if (!TD)
1676 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001677
Victor Hernandez83d63912009-09-18 22:35:49 +00001678 // If this is a malloc of an abstract type, don't touch it.
1679 if (!AllocTy->isSized())
1680 return false;
1681
1682 // We can't optimize this global unless all uses of it are *known* to be
1683 // of the malloc value, not of the null initializer value (consider a use
1684 // that compares the global's value against zero to see if the malloc has
1685 // been reached). To do this, we check to see if all uses of the global
1686 // would trap if the global were null: this proves that they must all
1687 // happen after the malloc.
1688 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1689 return false;
1690
1691 // We can't optimize this if the malloc itself is used in a complex way,
1692 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001693 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001694 // GEP'd. These are all things we could transform to using the global
1695 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001696 SmallPtrSet<const PHINode*, 8> PHIs;
1697 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1698 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001699
1700 // If we have a global that is only initialized with a fixed size malloc,
1701 // transform the program to use global memory instead of malloc'd memory.
1702 // This eliminates dynamic allocation, avoids an indirection accessing the
1703 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001704 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001705 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng86cd4452010-04-14 20:52:55 +00001706 if (!NElems)
1707 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001708
Evan Cheng86cd4452010-04-14 20:52:55 +00001709 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1710 // Restrict this transformation to only working on small allocations
1711 // (2048 bytes currently), as we don't want to introduce a 16M global or
1712 // something.
1713 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001714 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001715 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001716 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001717
Evan Cheng86cd4452010-04-14 20:52:55 +00001718 // If the allocation is an array of structures, consider transforming this
1719 // into multiple malloc'd arrays, one for each field. This is basically
1720 // SRoA for malloc'd memory.
1721
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001722 if (Ordering != NotAtomic)
1723 return false;
1724
Evan Cheng86cd4452010-04-14 20:52:55 +00001725 // If this is an allocation of a fixed size array of structs, analyze as a
1726 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001727 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001728 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001729 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001730
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001731 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001732 if (!AllocSTy)
1733 return false;
1734
1735 // This the structure has an unreasonable number of fields, leave it
1736 // alone.
1737 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1738 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1739
1740 // If this is a fixed size array, transform the Malloc to be an alloc of
1741 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001742 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001743 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001744 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1745 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1746 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1747 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1748 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001749 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001750 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1751 CI->replaceAllUsesWith(Cast);
1752 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001753 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1754 CI = cast<CallInst>(BCI->getOperand(0));
1755 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001756 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001757 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001758
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001759 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1760 TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001761 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001762 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001763
Victor Hernandez83d63912009-09-18 22:35:49 +00001764 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001765}
Victor Hernandez83d63912009-09-18 22:35:49 +00001766
Chris Lattner9b34a612004-10-09 21:48:45 +00001767// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1768// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001769static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001770 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001771 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001772 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001773 // Ignore no-op GEPs and bitcasts.
1774 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001775
Chris Lattner708148e2004-10-10 23:14:11 +00001776 // If we are dealing with a pointer global that is initialized to null and
1777 // only has one (non-null) value stored into it, then we can optimize any
1778 // users of the loaded value (often calls and loads) that would trap if the
1779 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001780 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001781 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001782 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1783 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001784 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001785
Chris Lattner708148e2004-10-10 23:14:11 +00001786 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001787 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001788 return true;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001789 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1790 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001791 if (MallocType &&
1792 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1793 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001794 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001795 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001796 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001797
Chris Lattner9b34a612004-10-09 21:48:45 +00001798 return false;
1799}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001800
Chris Lattner58e44f42008-01-14 01:17:44 +00001801/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1802/// two values ever stored into GV are its initializer and OtherVal. See if we
1803/// can shrink the global into a boolean and select between the two values
1804/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001805static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001806 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001807
Chris Lattner58e44f42008-01-14 01:17:44 +00001808 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001809 // an FP value, pointer or vector, don't do this optimization because a select
1810 // between them is very expensive and unlikely to lead to later
1811 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1812 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001813 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001814 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001815 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001816 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001817
Chris Lattner58e44f42008-01-14 01:17:44 +00001818 // Walk the use list of the global seeing if all the uses are load or store.
1819 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001820 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1821 User *U = *I;
1822 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001823 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001824 }
1825
David Greene3215b0e2010-01-05 01:28:05 +00001826 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001827
Chris Lattner96a86b22004-12-12 05:53:50 +00001828 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001829 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1830 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001831 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001832 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001833 GV->getName()+".b",
Hans Wennborgce718ff2012-06-23 11:37:03 +00001834 GV->getThreadLocalMode());
Chris Lattner96a86b22004-12-12 05:53:50 +00001835 GV->getParent()->getGlobalList().insert(GV, NewGV);
1836
1837 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001838 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001839 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001840
1841 // If initialized to zero and storing one into the global, we can use a cast
1842 // instead of a select to synthesize the desired value.
1843 bool IsOneZero = false;
1844 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001845 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001846
1847 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001848 Instruction *UI = cast<Instruction>(GV->use_back());
1849 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001850 // Change the store into a boolean store.
1851 bool StoringOther = SI->getOperand(0) == OtherVal;
1852 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001853 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001854 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001855 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1856 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001857 else {
1858 // Otherwise, we are storing a previously loaded copy. To do this,
1859 // change the copy from copying the original value to just copying the
1860 // bool.
1861 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1862
Gabor Greif9e4f2432010-06-24 14:42:01 +00001863 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001864 // select instruction. If not, it will be a load of the original
1865 // global.
1866 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1867 assert(LI->getOperand(0) == GV && "Not a copy!");
1868 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001869 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1870 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001871 } else {
1872 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1873 "This is not a form that we understand!");
1874 StoreVal = StoredVal->getOperand(0);
1875 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1876 }
1877 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001878 new StoreInst(StoreVal, NewGV, false, 0,
1879 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001880 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001881 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001882 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001883 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1884 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001885 Value *NSI;
1886 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001887 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001888 else
Gabor Greif051a9502008-04-06 20:25:17 +00001889 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001890 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001891 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001892 }
1893 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001894 }
1895
1896 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001897 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001898}
1899
1900
Nick Lewyckydb292a62012-02-12 00:52:26 +00001901/// ProcessGlobal - Analyze the specified global variable and optimize it if
1902/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001903bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1904 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001905 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001906 return false;
1907
1908 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001909 GV->removeDeadConstantUsers();
1910
1911 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001912 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001913 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001914 ++NumDeleted;
1915 return true;
1916 }
1917
Rafael Espindola2f135d42012-06-15 18:00:24 +00001918 if (!GV->hasLocalLinkage())
1919 return false;
1920
Rafael Espindolac4440e32011-01-19 16:32:21 +00001921 SmallPtrSet<const PHINode*, 16> PHIUsers;
1922 GlobalStatus GS;
1923
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001924 if (AnalyzeGlobal(GV, GS, PHIUsers))
1925 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001926
Rafael Espindolac4440e32011-01-19 16:32:21 +00001927 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1928 GV->setUnnamedAddr(true);
1929 NumUnnamed++;
1930 }
1931
1932 if (GV->isConstant() || !GV->hasInitializer())
1933 return false;
1934
1935 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1936}
1937
1938/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1939/// it if possible. If we make a change, return true.
1940bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1941 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001942 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001943 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001944 // If this is a first class global and has only one accessing function
1945 // and this function is main (which we know is not recursive we can make
1946 // this global a local variable) we replace the global with a local alloca
1947 // in this function.
1948 //
1949 // NOTE: It doesn't make sense to promote non single-value types since we
1950 // are just replacing static memory to stack memory.
1951 //
1952 // If the global is in different address space, don't bring it to stack.
1953 if (!GS.HasMultipleAccessingFunctions &&
1954 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1955 GV->getType()->getElementType()->isSingleValueType() &&
1956 GS.AccessingFunction->getName() == "main" &&
1957 GS.AccessingFunction->hasExternalLinkage() &&
1958 GV->getType()->getAddressSpace() == 0) {
1959 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001960 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001961 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001962 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001963 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001964 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001965 if (!isa<UndefValue>(GV->getInitializer()))
1966 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001967
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001968 GV->replaceAllUsesWith(Alloca);
1969 GV->eraseFromParent();
1970 ++NumLocalized;
1971 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001972 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001973
1974 // If the global is never loaded (but may be stored to), it is dead.
1975 // Delete it now.
1976 if (!GS.isLoaded) {
1977 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1978
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001979 bool Changed;
1980 if (isLeakCheckerRoot(GV)) {
1981 // Delete any constant stores to the global.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001982 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001983 } else {
1984 // Delete any stores we can find to the global. We may not be able to
1985 // make it completely dead though.
1986 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1987 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001988
1989 // If the global is dead now, delete it.
1990 if (GV->use_empty()) {
1991 GV->eraseFromParent();
1992 ++NumDeleted;
1993 Changed = true;
1994 }
1995 return Changed;
1996
1997 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1998 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1999 GV->setConstant(true);
2000
2001 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002002 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002003
2004 // If the global is dead now, just nuke it.
2005 if (GV->use_empty()) {
2006 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
2007 << "all users and delete global!\n");
2008 GV->eraseFromParent();
2009 ++NumDeleted;
2010 }
2011
2012 ++NumMarked;
2013 return true;
2014 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmow3574eca2012-10-08 16:38:25 +00002015 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002016 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
2017 GVI = FirstNewGV; // Don't skip the newly produced globals!
2018 return true;
2019 }
2020 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
2021 // If the initial value for the global was an undef value, and if only
2022 // one other value was stored into it, we can just change the
2023 // initializer to be the stored value, then delete all stores to the
2024 // global. This allows us to mark it constant.
2025 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2026 if (isa<UndefValue>(GV->getInitializer())) {
2027 // Change the initial value here.
2028 GV->setInitializer(SOVConstant);
2029
2030 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002031 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002032
2033 if (GV->use_empty()) {
2034 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00002035 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002036 GV->eraseFromParent();
2037 ++NumDeleted;
2038 } else {
2039 GVI = GV;
2040 }
2041 ++NumSubstitute;
2042 return true;
2043 }
2044
2045 // Try to optimize globals based on the knowledge that only one value
2046 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00002047 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00002048 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002049 return true;
2050
2051 // Otherwise, if the global was not a boolean, we can shrink it to be a
2052 // boolean.
2053 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2054 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
2055 ++NumShrunkToBool;
2056 return true;
2057 }
2058 }
2059
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002060 return false;
2061}
2062
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002063/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2064/// function, changing them to FastCC.
2065static void ChangeCalleesToFastCall(Function *F) {
2066 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002067 if (isa<BlockAddress>(*UI))
2068 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002069 CallSite User(cast<Instruction>(*UI));
2070 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002071 }
2072}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002073
Bill Wendling5886b7b2012-10-14 06:39:53 +00002074static AttrListPtr StripNest(LLVMContext &C, const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00002075 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling67658342012-10-09 07:45:08 +00002076 if (!Attrs.getSlot(i).Attrs.hasAttribute(Attributes::Nest))
Duncan Sands548448a2008-02-18 17:32:13 +00002077 continue;
2078
Duncan Sands548448a2008-02-18 17:32:13 +00002079 // There can be only one.
Bill Wendling46d5dd92012-10-16 05:23:31 +00002080 return Attrs.removeAttr(C, Attrs.getSlot(i).Index,
2081 Attributes::get(C, Attributes::Nest));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002082 }
2083
2084 return Attrs;
2085}
2086
2087static void RemoveNestAttribute(Function *F) {
Bill Wendling5886b7b2012-10-14 06:39:53 +00002088 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002089 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002090 if (isa<BlockAddress>(*UI))
2091 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002092 CallSite User(cast<Instruction>(*UI));
Bill Wendling5886b7b2012-10-14 06:39:53 +00002093 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002094 }
2095}
2096
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002097bool GlobalOpt::OptimizeFunctions(Module &M) {
2098 bool Changed = false;
2099 // Optimize functions.
2100 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2101 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002102 // Functions without names cannot be referenced outside this module.
2103 if (!F->hasName() && !F->isDeclaration())
2104 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002105 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00002106 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00002107 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002108 Changed = true;
2109 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002110 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002111 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002112 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002113 // If this function has C calling conventions, is not a varargs
2114 // function, and is only called directly, promote it to use the Fast
2115 // calling convention.
2116 F->setCallingConv(CallingConv::Fast);
2117 ChangeCalleesToFastCall(F);
2118 ++NumFastCallFns;
2119 Changed = true;
2120 }
2121
Bill Wendling7d2f2492012-10-10 07:36:45 +00002122 if (F->getAttributes().hasAttrSomewhere(Attributes::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002123 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002124 // The function is not used by a trampoline intrinsic, so it is safe
2125 // to remove the 'nest' attribute.
2126 RemoveNestAttribute(F);
2127 ++NumNestRemoved;
2128 Changed = true;
2129 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002130 }
2131 }
2132 return Changed;
2133}
2134
2135bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2136 bool Changed = false;
2137 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2138 GVI != E; ) {
2139 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002140 // Global variables without names cannot be referenced outside this module.
2141 if (!GV->hasName() && !GV->isDeclaration())
2142 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002143 // Simplify the initializer.
2144 if (GV->hasInitializer())
2145 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00002146 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002147 if (New && New != CE)
2148 GV->setInitializer(New);
2149 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00002150
2151 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002152 }
2153 return Changed;
2154}
2155
Nick Lewycky2c44a802011-04-08 07:30:21 +00002156/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002157/// initializers have an init priority of 65535.
2158GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002159 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2160 if (GV == 0) return 0;
2161
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002162 // Verify that the initializer is simple enough for us to handle. We are
2163 // only allowed to optimize the initializer if it is unique.
2164 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002165
2166 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2167 return GV;
2168 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00002169
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002170 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002171 if (isa<ConstantAggregateZero>(*i))
2172 continue;
2173 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002174 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2175 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002176
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002177 // Must have a function or null ptr.
2178 if (!isa<Function>(CS->getOperand(1)))
2179 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002180
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002181 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00002182 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2183 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002184 return 0;
2185 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002186
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002187 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002188}
2189
Chris Lattnerdb973e62005-09-26 02:31:18 +00002190/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2191/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002192static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002193 if (GV->getInitializer()->isNullValue())
2194 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002195 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2196 std::vector<Function*> Result;
2197 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002198 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2199 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002200 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2201 }
2202 return Result;
2203}
2204
Chris Lattnerdb973e62005-09-26 02:31:18 +00002205/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2206/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002207static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002208 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002209 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002210 Constant *CSVals[2];
2211 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2212 CSVals[1] = 0;
2213
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002214 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002215 cast <StructType>(
2216 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002217
Chris Lattnerdb973e62005-09-26 02:31:18 +00002218 // Create the new init list.
2219 std::vector<Constant*> CAList;
2220 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002221 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002222 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002223 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002224 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002225 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002226 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002227 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002228 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002229 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002230 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002231 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002232 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002233
Chris Lattnerdb973e62005-09-26 02:31:18 +00002234 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002235 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002236 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002237
Chris Lattnerdb973e62005-09-26 02:31:18 +00002238 // If we didn't change the number of elements, don't create a new GV.
2239 if (CA->getType() == GCL->getInitializer()->getType()) {
2240 GCL->setInitializer(CA);
2241 return GCL;
2242 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002243
Chris Lattnerdb973e62005-09-26 02:31:18 +00002244 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002245 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002246 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002247 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002248 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002249 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002250
Chris Lattnerdb973e62005-09-26 02:31:18 +00002251 // Nuke the old list, replacing any uses with the new one.
2252 if (!GCL->use_empty()) {
2253 Constant *V = NGV;
2254 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002255 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002256 GCL->replaceAllUsesWith(V);
2257 }
2258 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002259
Chris Lattnerdb973e62005-09-26 02:31:18 +00002260 if (Ctors.size())
2261 return NGV;
2262 else
2263 return 0;
2264}
Chris Lattner79c11012005-09-26 04:44:35 +00002265
2266
Chris Lattner1945d582010-12-07 04:33:29 +00002267static inline bool
2268isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002269 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002270 const DataLayout *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002271
2272
2273/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2274/// handled by the code generator. We don't want to generate something like:
2275/// void *X = &X/42;
2276/// because the code generator doesn't have a relocation that can handle that.
2277///
2278/// This function should be called if C was not found (but just got inserted)
2279/// in SimpleConstants to avoid having to rescan the same constants all the
2280/// time.
2281static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002282 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002283 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002284 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2285 // all supported.
2286 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2287 isa<GlobalValue>(C))
2288 return true;
2289
2290 // Aggregate values are safe if all their elements are.
2291 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2292 isa<ConstantVector>(C)) {
2293 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2294 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002295 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002296 return false;
2297 }
2298 return true;
2299 }
2300
2301 // We don't know exactly what relocations are allowed in constant expressions,
2302 // so we allow &global+constantoffset, which is safe and uniformly supported
2303 // across targets.
2304 ConstantExpr *CE = cast<ConstantExpr>(C);
2305 switch (CE->getOpcode()) {
2306 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002307 // Bitcast is fine if the casted value is fine.
2308 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2309
Chris Lattner1945d582010-12-07 04:33:29 +00002310 case Instruction::IntToPtr:
2311 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002312 // int <=> ptr is fine if the int type is the same size as the
2313 // pointer type.
2314 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2315 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2316 return false;
2317 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002318
2319 // GEP is fine if it is simple + constant offset.
2320 case Instruction::GetElementPtr:
2321 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2322 if (!isa<ConstantInt>(CE->getOperand(i)))
2323 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002324 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002325
2326 case Instruction::Add:
2327 // We allow simple+cst.
2328 if (!isa<ConstantInt>(CE->getOperand(1)))
2329 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002330 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002331 }
2332 return false;
2333}
2334
2335static inline bool
2336isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002337 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002338 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002339 // If we already checked this constant, we win.
2340 if (!SimpleConstants.insert(C)) return true;
2341 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002342 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002343}
2344
2345
Chris Lattner79c11012005-09-26 04:44:35 +00002346/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002347/// enough for us to understand. In particular, if it is a cast to anything
2348/// other than from one pointer type to another pointer type, we punt.
2349/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002350/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002351static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002352 // Conservatively, avoid aggregate types. This is because we don't
2353 // want to worry about them partially overlapping other stores.
2354 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2355 return false;
2356
Dan Gohmanfd54a892009-09-07 22:31:26 +00002357 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002358 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002359 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002360 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002361
Owen Andersone95a32c2011-01-14 22:31:13 +00002362 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002363 // Handle a constantexpr gep.
2364 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002365 isa<GlobalVariable>(CE->getOperand(0)) &&
2366 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002367 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002368 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002369 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002370 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002371 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002372
Dan Gohman80bdc962009-09-07 22:44:55 +00002373 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002374 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002375 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002376
2377 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002378 // notional bounds of the corresponding static array types.
2379 if (!CE->isGEPWithNoNotionalOverIndexing())
2380 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002381
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002382 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002383
2384 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2385 // and we know how to evaluate it by moving the bitcast from the pointer
2386 // operand to the value operand.
2387 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002388 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002389 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2390 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002391 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002392 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002393 }
2394
Chris Lattner79c11012005-09-26 04:44:35 +00002395 return false;
2396}
2397
Chris Lattner798b4d52005-09-26 06:52:44 +00002398/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2399/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2400/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2401static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Sheng702aa2e2012-12-01 04:38:53 +00002402 ConstantExpr *Addr, unsigned OpNo,
2403 SetVector<Constant*>& Obsolete) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002404 // Base case of the recursion.
2405 if (OpNo == Addr->getNumOperands()) {
2406 assert(Val->getType() == Init->getType() && "Type mismatch!");
2407 return Val;
2408 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002409
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002410 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002411 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002412 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002413 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2414 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002415
Chris Lattner798b4d52005-09-26 06:52:44 +00002416 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002417 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2418 unsigned Idx = CU->getZExtValue();
2419 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Sheng702aa2e2012-12-01 04:38:53 +00002420 if (Elts[Idx]->getType()->isAggregateType())
2421 Obsolete.insert(Elts[Idx]);
2422 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Obsolete);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002423
Chris Lattner798b4d52005-09-26 06:52:44 +00002424 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002425 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002426 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002427
2428 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002429 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002430
2431 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002432 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002433 NumElts = ATy->getNumElements();
2434 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002435 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002436
2437 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002438 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2439 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002440
2441 assert(CI->getZExtValue() < NumElts);
Zhou Sheng702aa2e2012-12-01 04:38:53 +00002442 Constant *OrigElem = Elts[CI->getZExtValue()];
2443 if (OrigElem->getType()->isAggregateType())
2444 Obsolete.insert(OrigElem);
Chris Lattnerb065b062011-06-20 04:01:31 +00002445 Elts[CI->getZExtValue()] =
Zhou Sheng702aa2e2012-12-01 04:38:53 +00002446 EvaluateStoreInto(OrigElem, Val, Addr, OpNo+1, Obsolete);
Chris Lattnerb065b062011-06-20 04:01:31 +00002447
2448 if (Init->getType()->isArrayTy())
2449 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2450 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002451}
2452
Chris Lattner79c11012005-09-26 04:44:35 +00002453/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2454/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002455static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002456 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2457 assert(GV->hasInitializer());
2458 GV->setInitializer(Val);
2459 return;
2460 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002461
Zhou Sheng702aa2e2012-12-01 04:38:53 +00002462 // Collect obsolete constants created in previous CommitValueTo() invoke.
2463 SetVector<Constant*> Obsolete;
Chris Lattner798b4d52005-09-26 06:52:44 +00002464 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2465 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Sheng702aa2e2012-12-01 04:38:53 +00002466 Constant *OrigInit = GV->getInitializer();
2467 if (OrigInit->getType()->isAggregateType())
2468 Obsolete.insert(OrigInit);
2469 Constant *Init = EvaluateStoreInto(OrigInit, Val, CE, 2, Obsolete);
2470 GV->setInitializer(Init);
2471
2472 for (unsigned i = 0; i < Obsolete.size(); ++i) {
2473 if (Obsolete[i]->use_empty())
2474 Obsolete[i]->destroyConstant();
2475 }
Chris Lattner79c11012005-09-26 04:44:35 +00002476}
2477
Nick Lewycky7fa76772012-02-20 03:25:59 +00002478namespace {
2479
2480/// Evaluator - This class evaluates LLVM IR, producing the Constant
2481/// representing each SSA instruction. Changes to global variables are stored
2482/// in a mapping that can be iterated over after the evaluation is complete.
2483/// Once an evaluation call fails, the evaluation object should not be reused.
2484class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002485public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002486 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002487 : TD(TD), TLI(TLI) {
2488 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2489 }
2490
Nick Lewycky7fa76772012-02-20 03:25:59 +00002491 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002492 DeleteContainerPointers(ValueStack);
2493 while (!AllocaTmps.empty()) {
2494 GlobalVariable *Tmp = AllocaTmps.back();
2495 AllocaTmps.pop_back();
2496
2497 // If there are still users of the alloca, the program is doing something
2498 // silly, e.g. storing the address of the alloca somewhere and using it
2499 // later. Since this is undefined, we'll just make it be null.
2500 if (!Tmp->use_empty())
2501 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2502 delete Tmp;
2503 }
2504 }
2505
2506 /// EvaluateFunction - Evaluate a call to function F, returning true if
2507 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2508 /// arguments for the function.
2509 bool EvaluateFunction(Function *F, Constant *&RetVal,
2510 const SmallVectorImpl<Constant*> &ActualArgs);
2511
2512 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2513 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2514 /// control flows into, or null upon return.
2515 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2516
2517 Constant *getVal(Value *V) {
2518 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2519 Constant *R = ValueStack.back()->lookup(V);
2520 assert(R && "Reference to an uncomputed value!");
2521 return R;
2522 }
2523
2524 void setVal(Value *V, Constant *C) {
2525 ValueStack.back()->operator[](V) = C;
2526 }
2527
2528 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2529 return MutatedMemory;
2530 }
2531
2532 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2533 return Invariants;
2534 }
2535
2536private:
2537 Constant *ComputeLoadResult(Constant *P);
2538
2539 /// ValueStack - As we compute SSA register values, we store their contents
2540 /// here. The back of the vector contains the current function and the stack
2541 /// contains the values in the calling frames.
2542 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2543
2544 /// CallStack - This is used to detect recursion. In pathological situations
2545 /// we could hit exponential behavior, but at least there is nothing
2546 /// unbounded.
2547 SmallVector<Function*, 4> CallStack;
2548
2549 /// MutatedMemory - For each store we execute, we update this map. Loads
2550 /// check this to get the most up-to-date value. If evaluation is successful,
2551 /// this state is committed to the process.
2552 DenseMap<Constant*, Constant*> MutatedMemory;
2553
2554 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2555 /// to represent its body. This vector is needed so we can delete the
2556 /// temporary globals when we are done.
2557 SmallVector<GlobalVariable*, 32> AllocaTmps;
2558
2559 /// Invariants - These global variables have been marked invariant by the
2560 /// static constructor.
2561 SmallPtrSet<GlobalVariable*, 8> Invariants;
2562
2563 /// SimpleConstants - These are constants we have checked and know to be
2564 /// simple enough to live in a static initializer of a global.
2565 SmallPtrSet<Constant*, 8> SimpleConstants;
2566
Micah Villmow3574eca2012-10-08 16:38:25 +00002567 const DataLayout *TD;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002568 const TargetLibraryInfo *TLI;
2569};
2570
Nick Lewycky7fa76772012-02-20 03:25:59 +00002571} // anonymous namespace
2572
Chris Lattner562a0552005-09-26 05:16:34 +00002573/// ComputeLoadResult - Return the value that would be computed by a load from
2574/// P after the stores reflected by 'memory' have been performed. If we can't
2575/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002576Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002577 // If this memory location has been recently stored, use the stored value: it
2578 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002579 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2580 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002581
Chris Lattner04de1cf2005-09-26 05:15:37 +00002582 // Access it.
2583 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002584 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002585 return GV->getInitializer();
2586 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002587 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002588
Chris Lattner798b4d52005-09-26 06:52:44 +00002589 // Handle a constantexpr getelementptr.
2590 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2591 if (CE->getOpcode() == Instruction::GetElementPtr &&
2592 isa<GlobalVariable>(CE->getOperand(0))) {
2593 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002594 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002595 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002596 }
2597
2598 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002599}
2600
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002601/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2602/// successful, false if we can't evaluate it. NewBB returns the next BB that
2603/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002604bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2605 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002606 // This is the main evaluation loop.
2607 while (1) {
2608 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002609
Chris Lattner79c11012005-09-26 04:44:35 +00002610 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002611 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002612 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002613 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2614 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002615 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002616 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002617 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002618
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002619 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002620
2621 // If this might be too difficult for the backend to handle (e.g. the addr
2622 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002623 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002624 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002625
2626 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2627 if (CE->getOpcode() == Instruction::BitCast) {
2628 // If we're evaluating a store through a bitcast, then we need
2629 // to pull the bitcast off the pointer type and push it onto the
2630 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002631 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002632
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002633 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002634
Owen Anderson66f708f2011-01-16 04:33:33 +00002635 // In order to push the bitcast onto the stored value, a bitcast
2636 // from NewTy to Val's type must be legal. If it's not, we can try
2637 // introspecting NewTy to find a legal conversion.
2638 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2639 // If NewTy is a struct, we can convert the pointer to the struct
2640 // into a pointer to its first member.
2641 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002642 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002643 NewTy = STy->getTypeAtIndex(0U);
2644
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002645 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002646 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2647 Constant * const IdxList[] = {IdxZero, IdxZero};
2648
Jay Foadb4263a62011-07-22 08:52:50 +00002649 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002650 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2651 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2652
Owen Anderson66f708f2011-01-16 04:33:33 +00002653 // If we can't improve the situation by introspecting NewTy,
2654 // we have to give up.
2655 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002656 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002657 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002658 }
2659
Owen Anderson66f708f2011-01-16 04:33:33 +00002660 // If we found compatible types, go ahead and push the bitcast
2661 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002662 Val = ConstantExpr::getBitCast(Val, NewTy);
2663 }
2664
Chris Lattner79c11012005-09-26 04:44:35 +00002665 MutatedMemory[Ptr] = Val;
2666 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002667 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002668 getVal(BO->getOperand(0)),
2669 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002670 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002671 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002672 getVal(CI->getOperand(0)),
2673 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002674 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002675 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002676 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002677 CI->getType());
2678 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002679 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2680 getVal(SI->getOperand(1)),
2681 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002682 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002683 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002684 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002685 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2686 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002687 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002688 InstResult =
2689 ConstantExpr::getGetElementPtr(P, GEPOps,
2690 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002691 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002692 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002693 Constant *Ptr = getVal(LI->getOperand(0));
2694 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2695 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2696 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002697 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002698 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002699 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002700 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002701 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002702 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002703 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002704 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002705 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002706 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2707 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002708
2709 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002710 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002711 ++CurInst;
2712 continue;
2713 }
2714
Chris Lattner7cd580f2006-07-07 21:37:01 +00002715 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002716 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002717
Nick Lewycky81266c52012-02-17 06:59:21 +00002718 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2719 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2720 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002721 Constant *Ptr = getVal(MSI->getDest());
2722 Constant *Val = getVal(MSI->getValue());
2723 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002724 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2725 // This memset is a no-op.
2726 ++CurInst;
2727 continue;
2728 }
2729 }
2730
2731 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2732 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2733 ++CurInst;
2734 continue;
2735 }
2736
2737 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2738 // We don't insert an entry into Values, as it doesn't have a
2739 // meaningful return value.
2740 if (!II->use_empty())
2741 return false;
2742 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002743 Value *PtrArg = getVal(II->getArgOperand(1));
2744 Value *Ptr = PtrArg->stripPointerCasts();
2745 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2746 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2747 if (!Size->isAllOnesValue() &&
2748 Size->getValue().getLimitedValue() >=
2749 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002750 Invariants.insert(GV);
2751 }
2752 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002753 ++CurInst;
2754 continue;
2755 }
2756 return false;
2757 }
2758
Chris Lattnercd271422005-09-27 04:45:34 +00002759 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002760 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002761 if (!Callee || Callee->mayBeOverridden())
2762 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002763
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002764 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002765 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002766 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002767
Reid Spencer5cbf9852007-01-30 20:08:39 +00002768 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002769 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002770 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002771 InstResult = C;
2772 } else {
2773 return false;
2774 }
2775 } else {
2776 if (Callee->getFunctionType()->isVarArg())
2777 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002778
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002779 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002780 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002781 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2782 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002783 return false;
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002784 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002785 InstResult = RetVal;
2786 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002787 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002788 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2789 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002790 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002791 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002792 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002793 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002794 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002795
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002796 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002797 }
2798 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2799 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002800 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002801 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002802 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002803 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002804 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002805 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002806 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002807 else
2808 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002809 } else if (isa<ReturnInst>(CurInst)) {
2810 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002811 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002812 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002813 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002814 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002815
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002816 // We succeeded at evaluating this block!
2817 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002818 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002819 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002820 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002821 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002822
Chris Lattner1945d582010-12-07 04:33:29 +00002823 if (!CurInst->use_empty()) {
2824 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002825 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002826
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002827 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002828 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002829
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002830 // If we just processed an invoke, we finished evaluating the block.
2831 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2832 NextBB = II->getNormalDest();
2833 return true;
2834 }
2835
Chris Lattner79c11012005-09-26 04:44:35 +00002836 // Advance program counter.
2837 ++CurInst;
2838 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002839}
2840
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002841/// EvaluateFunction - Evaluate a call to function F, returning true if
2842/// successful, false if we can't evaluate it. ActualArgs contains the formal
2843/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002844bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2845 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002846 // Check to see if this function is already executing (recursion). If so,
2847 // bail out. TODO: we might want to accept limited recursion.
2848 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2849 return false;
2850
2851 CallStack.push_back(F);
2852
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002853 // Initialize arguments to the incoming values specified.
2854 unsigned ArgNo = 0;
2855 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2856 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002857 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002858
2859 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2860 // we can only evaluate any one basic block at most once. This set keeps
2861 // track of what we have executed so we can detect recursive cases etc.
2862 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2863
2864 // CurBB - The current basic block we're evaluating.
2865 BasicBlock *CurBB = F->begin();
2866
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002867 BasicBlock::iterator CurInst = CurBB->begin();
2868
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002869 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002870 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002871 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002872 return false;
2873
2874 if (NextBB == 0) {
2875 // Successfully running until there's no next block means that we found
2876 // the return. Fill it the return value and pop the call stack.
2877 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2878 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002879 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002880 CallStack.pop_back();
2881 return true;
2882 }
2883
2884 // Okay, we succeeded in evaluating this control flow. See if we have
2885 // executed the new block before. If so, we have a looping function,
2886 // which we cannot evaluate in reasonable time.
2887 if (!ExecutedBlocks.insert(NextBB))
2888 return false; // looped!
2889
2890 // Okay, we have never been in this block before. Check to see if there
2891 // are any PHI nodes. If so, evaluate them with information about where
2892 // we came from.
2893 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002894 for (CurInst = NextBB->begin();
2895 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002896 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002897
2898 // Advance to the next block.
2899 CurBB = NextBB;
2900 }
2901}
2902
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002903/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2904/// we can. Return true if we can, false otherwise.
Micah Villmow3574eca2012-10-08 16:38:25 +00002905static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosier00737bd2011-12-01 21:29:16 +00002906 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002907 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002908 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002909 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002910 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2911 SmallVector<Constant*, 0>());
Chris Lattner1945d582010-12-07 04:33:29 +00002912
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002913 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002914 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002915 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002916 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002917 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002918 for (DenseMap<Constant*, Constant*>::const_iterator I =
2919 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002920 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002921 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002922 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2923 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2924 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002925 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002926 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002927
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002928 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002929}
2930
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002931/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2932/// Return true if anything changed.
2933bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2934 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2935 bool MadeChange = false;
2936 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002937
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002938 // Loop over global ctors, optimizing them when we can.
2939 for (unsigned i = 0; i != Ctors.size(); ++i) {
2940 Function *F = Ctors[i];
2941 // Found a null terminator in the middle of the list, prune off the rest of
2942 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002943 if (F == 0) {
2944 if (i != Ctors.size()-1) {
2945 Ctors.resize(i+1);
2946 MadeChange = true;
2947 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002948 break;
2949 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002950
Chris Lattner79c11012005-09-26 04:44:35 +00002951 // We cannot simplify external ctor functions.
2952 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002953
Chris Lattner79c11012005-09-26 04:44:35 +00002954 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002955 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002956 Ctors.erase(Ctors.begin()+i);
2957 MadeChange = true;
2958 --i;
2959 ++NumCtorsEvaluated;
2960 continue;
2961 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002962 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002963
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002964 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002965
Chris Lattner7b550cc2009-11-06 04:27:31 +00002966 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002967 return true;
2968}
2969
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002970bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002971 bool Changed = false;
2972
Duncan Sands177d84e2009-01-07 20:01:06 +00002973 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002974 I != E;) {
2975 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002976 // Aliases without names cannot be referenced outside this module.
2977 if (!J->hasName() && !J->isDeclaration())
2978 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002979 // If the aliasee may change at link time, nothing can be done - bail out.
2980 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002981 continue;
2982
Duncan Sands4782b302009-02-15 09:56:08 +00002983 Constant *Aliasee = J->getAliasee();
2984 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002985 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002986 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2987
2988 // Make all users of the alias use the aliasee instead.
2989 if (!J->use_empty()) {
2990 J->replaceAllUsesWith(Aliasee);
2991 ++NumAliasesResolved;
2992 Changed = true;
2993 }
2994
Duncan Sands7a154cf2009-12-08 10:10:20 +00002995 // If the alias is externally visible, we may still be able to simplify it.
2996 if (!J->hasLocalLinkage()) {
2997 // If the aliasee has internal linkage, give it the name and linkage
2998 // of the alias, and delete the alias. This turns:
2999 // define internal ... @f(...)
3000 // @a = alias ... @f
3001 // into:
3002 // define ... @a(...)
3003 if (!Target->hasLocalLinkage())
3004 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00003005
Duncan Sands7a154cf2009-12-08 10:10:20 +00003006 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00003007 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00003008 // and other attributes of the aliasee with those of the alias.
3009 if (!hasOneUse)
3010 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00003011
Duncan Sands7a154cf2009-12-08 10:10:20 +00003012 // Give the aliasee the name, linkage and other attributes of the alias.
3013 Target->takeName(J);
3014 Target->setLinkage(J->getLinkage());
3015 Target->GlobalValue::copyAttributesFrom(J);
3016 }
Duncan Sands4782b302009-02-15 09:56:08 +00003017
3018 // Delete the alias.
3019 M.getAliasList().erase(J);
3020 ++NumAliasesRemoved;
3021 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003022 }
3023
3024 return Changed;
3025}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003026
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003027static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3028 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00003029 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003030
3031 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Anders Carlssona201c4c2011-03-20 17:59:11 +00003032
3033 if (!Fn)
3034 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003035
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003036 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00003037
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003038 // Checking that the function has the right return type, the right number of
3039 // parameters and that they all have pointer types should be enough.
3040 if (!FTy->getReturnType()->isIntegerTy() ||
3041 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003042 !FTy->getParamType(0)->isPointerTy() ||
3043 !FTy->getParamType(1)->isPointerTy() ||
3044 !FTy->getParamType(2)->isPointerTy())
3045 return 0;
3046
3047 return Fn;
3048}
3049
3050/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3051/// destructor and can therefore be eliminated.
3052/// Note that we assume that other optimization passes have already simplified
3053/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003054/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3055/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003056static bool cxxDtorIsEmpty(const Function &Fn,
3057 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003058 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003059 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003060 if (Fn.isDeclaration())
3061 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003062
3063 if (++Fn.begin() != Fn.end())
3064 return false;
3065
3066 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3067 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3068 I != E; ++I) {
3069 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003070 // Ignore debug intrinsics.
3071 if (isa<DbgInfoIntrinsic>(CI))
3072 continue;
3073
Anders Carlssona201c4c2011-03-20 17:59:11 +00003074 const Function *CalledFn = CI->getCalledFunction();
3075
3076 if (!CalledFn)
3077 return false;
3078
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003079 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3080
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003081 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003082 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003083 return false;
3084
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003085 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003086 return false;
3087 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003088 return true; // We're done.
3089 else if (I->mayHaveSideEffects())
3090 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003091 }
3092
3093 return false;
3094}
3095
3096bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3097 /// Itanium C++ ABI p3.3.5:
3098 ///
3099 /// After constructing a global (or local static) object, that will require
3100 /// destruction on exit, a termination function is registered as follows:
3101 ///
3102 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3103 ///
3104 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3105 /// call f(p) when DSO d is unloaded, before all such termination calls
3106 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003107 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003108
3109 // This pass will look for calls to __cxa_atexit where the function is trivial
3110 // and remove them.
3111 bool Changed = false;
3112
3113 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
3114 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003115 // We're only interested in calls. Theoretically, we could handle invoke
3116 // instructions as well, but neither llvm-gcc nor clang generate invokes
3117 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003118 CallInst *CI = dyn_cast<CallInst>(*I++);
3119 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003120 continue;
3121
Anders Carlssona201c4c2011-03-20 17:59:11 +00003122 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003123 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003124 if (!DtorFn)
3125 continue;
3126
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003127 SmallPtrSet<const Function *, 8> CalledFunctions;
3128 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003129 continue;
3130
3131 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003132 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3133 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003134
Anders Carlssona201c4c2011-03-20 17:59:11 +00003135 ++NumCXXDtorsRemoved;
3136
3137 Changed |= true;
3138 }
3139
3140 return Changed;
3141}
3142
Chris Lattner7a90b682004-10-07 04:16:33 +00003143bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003144 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003145
Micah Villmow3574eca2012-10-08 16:38:25 +00003146 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003147 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003148
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003149 // Try to find the llvm.globalctors list.
3150 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003151
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003152 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003153
Chris Lattner7a90b682004-10-07 04:16:33 +00003154 bool LocalChange = true;
3155 while (LocalChange) {
3156 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003157
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003158 // Delete functions that are trivially dead, ccc -> fastcc
3159 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003160
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003161 // Optimize global_ctors list.
3162 if (GlobalCtors)
3163 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003164
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003165 // Optimize non-address-taken globals.
3166 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003167
3168 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003169 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003170
3171 // Try to remove trivial global destructors.
3172 if (CXAAtExitFn)
3173 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3174
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003175 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003176 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003177
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003178 // TODO: Move all global ctors functions to the end of the module for code
3179 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003180
Chris Lattner079236d2004-02-25 21:34:36 +00003181 return Changed;
3182}