blob: d8edffcd70d86f94a712b5a941fbb33340461a12 [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
Jay Foad562b84b2011-04-11 09:35:34 +000024#include "llvm/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000025#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000027#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000028#include "llvm/Target/TargetData.h"
Chad Rosier00737bd2011-12-01 21:29:16 +000029#include "llvm/Target/TargetLibraryInfo.h"
Duncan Sands548448a2008-02-18 17:32:13 +000030#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000034#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000040#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000041#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000042using namespace llvm;
43
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000045STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000046STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49STATISTIC(NumDeleted , "Number of globals deleted");
50STATISTIC(NumFnDeleted , "Number of functions deleted");
51STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52STATISTIC(NumLocalized , "Number of globals localized");
53STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000056STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000057STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000059STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000060
Chris Lattner86453c52006-12-19 22:09:18 +000061namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000062 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000065 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000066 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000068 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
70 }
Misha Brukmanfd939082005-04-21 23:48:37 +000071
Chris Lattnerb12914b2004-09-20 04:48:05 +000072 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000073
74 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000075 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000078 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000079 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000080 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewycky6a577f82012-02-12 01:13:18 +000085
86 TargetData *TD;
87 TargetLibraryInfo *TLI;
Chris Lattner079236d2004-02-25 21:34:36 +000088 };
Chris Lattner079236d2004-02-25 21:34:36 +000089}
90
Dan Gohman844731a2008-05-13 00:00:25 +000091char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000092INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
93 "Global Variable Optimizer", false, false)
94INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
95INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000096 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000097
Chris Lattner7a90b682004-10-07 04:16:33 +000098ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000099
Dan Gohman844731a2008-05-13 00:00:25 +0000100namespace {
101
Chris Lattner7a90b682004-10-07 04:16:33 +0000102/// GlobalStatus - As we analyze each global, keep track of some information
103/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000104/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000105struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000106 /// isCompared - True if the global's address is used in a comparison.
107 bool isCompared;
108
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000109 /// isLoaded - True if the global is ever loaded. If the global isn't ever
110 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000111 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000112
113 /// StoredType - Keep track of what stores to the global look like.
114 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000115 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000116 /// NotStored - There is no store to this global. It can thus be marked
117 /// constant.
118 NotStored,
119
120 /// isInitializerStored - This global is stored to, but the only thing
121 /// stored is the constant it was initialized with. This is only tracked
122 /// for scalar globals.
123 isInitializerStored,
124
125 /// isStoredOnce - This global is stored to, but only its initializer and
126 /// one other value is ever stored to it. If this global isStoredOnce, we
127 /// track the value stored to it in StoredOnceValue below. This is only
128 /// tracked for scalar globals.
129 isStoredOnce,
130
131 /// isStored - This global is stored to by multiple values or something else
132 /// that we cannot track.
133 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000134 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000135
136 /// StoredOnceValue - If only one value (besides the initializer constant) is
137 /// ever stored to this global, keep track of what value it is.
138 Value *StoredOnceValue;
139
Chris Lattner25de4e52006-11-01 18:03:33 +0000140 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
141 /// null/false. When the first accessing function is noticed, it is recorded.
142 /// When a second different accessing function is noticed,
143 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000144 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000145 bool HasMultipleAccessingFunctions;
146
Chris Lattner25de4e52006-11-01 18:03:33 +0000147 /// HasNonInstructionUser - Set to true if this global has a user that is not
148 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000149 bool HasNonInstructionUser;
150
Chris Lattner25de4e52006-11-01 18:03:33 +0000151 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
152 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000153
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000154 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
155 AtomicOrdering Ordering;
156
Rafael Espindolac4440e32011-01-19 16:32:21 +0000157 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
158 StoredOnceValue(0), AccessingFunction(0),
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000159 HasMultipleAccessingFunctions(false),
160 HasNonInstructionUser(false), HasPHIUser(false),
161 Ordering(NotAtomic) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000162};
Chris Lattnere47ba742004-10-06 20:57:02 +0000163
Dan Gohman844731a2008-05-13 00:00:25 +0000164}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000165
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000166/// StrongerOrdering - Return the stronger of the two ordering. If the two
167/// orderings are acquire and release, then return AcquireRelease.
168///
169static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
170 if (X == Acquire && Y == Release) return AcquireRelease;
171 if (Y == Acquire && X == Release) return AcquireRelease;
172 return (AtomicOrdering)std::max(X, Y);
173}
174
Nick Lewyckybc384a12012-02-05 19:48:37 +0000175/// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
176/// by constants itself. Note that constants cannot be cyclic, so this test is
177/// pretty easy to implement recursively.
178///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000179static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000180 if (isa<GlobalValue>(C)) return false;
181
Gabor Greif27236912010-04-07 18:59:26 +0000182 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
183 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000184 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000185 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000186 } else
187 return false;
188 return true;
189}
190
191
Chris Lattner7a90b682004-10-07 04:16:33 +0000192/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
193/// structure. If the global has its address taken, return true to indicate we
194/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000195///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000196static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
197 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000198 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000199 ++UI) {
200 const User *U = *UI;
201 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000202 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000203
204 // If the result of the constantexpr isn't pointer type, then we won't
205 // know to expect it in various places. Just reject early.
206 if (!isa<PointerType>(CE->getType())) return true;
207
Chris Lattner7a90b682004-10-07 04:16:33 +0000208 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000209 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000210 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000211 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000212 if (GS.AccessingFunction == 0)
213 GS.AccessingFunction = F;
214 else if (GS.AccessingFunction != F)
215 GS.HasMultipleAccessingFunctions = true;
216 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000217 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000218 GS.isLoaded = true;
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000219 // Don't hack on volatile loads.
220 if (LI->isVolatile()) return true;
221 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000222 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000223 // Don't allow a store OF the address, only stores TO the address.
224 if (SI->getOperand(0) == V) return true;
225
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000226 // Don't hack on volatile stores.
227 if (SI->isVolatile()) return true;
228 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000229
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000230 // If this is a direct store to the global (i.e., the global is a scalar
231 // value, not an aggregate), keep more specific information about
232 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000233 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000234 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
235 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000236 Value *StoredVal = SI->getOperand(0);
237 if (StoredVal == GV->getInitializer()) {
238 if (GS.StoredType < GlobalStatus::isInitializerStored)
239 GS.StoredType = GlobalStatus::isInitializerStored;
240 } else if (isa<LoadInst>(StoredVal) &&
241 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000242 if (GS.StoredType < GlobalStatus::isInitializerStored)
243 GS.StoredType = GlobalStatus::isInitializerStored;
244 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
245 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000246 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000247 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000248 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000249 // noop.
250 } else {
251 GS.StoredType = GlobalStatus::isStored;
252 }
253 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000254 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000255 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000256 }
Duncan Sandsb2fe7f12012-07-02 18:55:39 +0000257 } else if (isa<BitCastInst>(I)) {
258 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000259 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000260 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000261 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000262 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000263 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000264 // PHI nodes we can check just like select or GEP instructions, but we
265 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000266 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000267 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000268 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000269 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000270 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000271 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
272 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000273 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000274 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000275 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000276 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000277 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
278 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
279 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000280 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000281 } else {
282 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000283 }
Gabor Greife6642672010-07-09 16:51:20 +0000284 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000285 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000286 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000287 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000288 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000289 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000290 GS.HasNonInstructionUser = true;
291 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000292 return true;
293 }
Gabor Greife6642672010-07-09 16:51:20 +0000294 }
Chris Lattner079236d2004-02-25 21:34:36 +0000295
296 return false;
297}
298
Nick Lewycky39e357f2012-07-19 22:35:28 +0000299/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
300/// as a root? If so, we might not really want to eliminate the stores to it.
301static bool isLeakCheckerRoot(GlobalVariable *GV) {
302 // A global variable is a root if it is a pointer, or could plausibly contain
303 // a pointer. There are two challenges; one is that we could have a struct
304 // the has an inner member which is a pointer. We recurse through the type to
305 // detect these (up to a point). The other is that we may actually be a union
306 // of a pointer and another type, and so our LLVM type is an integer which
307 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
308 // potentially contained here.
309
310 if (GV->hasPrivateLinkage())
311 return false;
312
313 SmallVector<Type *, 4> Types;
314 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
315
316 unsigned Limit = 20;
317 do {
318 Type *Ty = Types.pop_back_val();
319 switch (Ty->getTypeID()) {
320 default: break;
321 case Type::PointerTyID: return true;
322 case Type::ArrayTyID:
323 case Type::VectorTyID: {
324 SequentialType *STy = cast<SequentialType>(Ty);
325 Types.push_back(STy->getElementType());
326 break;
327 }
328 case Type::StructTyID: {
329 StructType *STy = cast<StructType>(Ty);
330 if (STy->isOpaque()) return true;
331 for (StructType::element_iterator I = STy->element_begin(),
332 E = STy->element_end(); I != E; ++I) {
333 Type *InnerTy = *I;
334 if (isa<PointerType>(InnerTy)) return true;
335 if (isa<CompositeType>(InnerTy))
336 Types.push_back(InnerTy);
337 }
338 break;
339 }
340 }
341 if (--Limit == 0) return true;
342 } while (!Types.empty());
343 return false;
344}
345
346/// Given a value that is stored to a global but never read, determine whether
347/// it's safe to remove the store and the chain of computation that feeds the
348/// store.
349static bool IsSafeComputationToRemove(Value *V) {
350 do {
351 if (!V->hasOneUse())
352 return false;
353 if (isa<LoadInst>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
354 return false;
355 if (isAllocationFn(V) || isa<Constant>(V))
356 return true;
357
358 Instruction *I = cast<Instruction>(V);
359 if (I->mayHaveSideEffects())
360 return false;
361 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
362 if (!GEP->hasAllConstantIndices())
363 return false;
364 } else if (I->getNumOperands() != 1) {
365 return false;
366 }
367
368 V = I->getOperand(0);
369 } while (1);
370}
371
372/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
373/// of the global and clean up any that obviously don't assign the global a
374/// value that isn't dynamically allocated.
375static bool CleanupPointerRootUsers(GlobalVariable *GV) {
376 bool Changed = false;
377
378 // If Dead[n].first is the only use of a malloc result, we can delete its
379 // chain of computation and the store to the global in Dead[n].second.
380 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
381
382 // Constants can't be pointers to dynamically allocated memory.
383 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
384 UI != E;) {
385 User *U = *UI++;
386 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
387 Value *V = SI->getValueOperand();
388 if (isa<Constant>(V)) {
389 Changed = true;
390 SI->eraseFromParent();
391 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
392 if (I->hasOneUse())
393 Dead.push_back(std::make_pair(I, SI));
394 }
395 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
396 if (isa<Constant>(MSI->getValue())) {
397 Changed = true;
398 MSI->eraseFromParent();
399 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
400 if (I->hasOneUse())
401 Dead.push_back(std::make_pair(I, MSI));
402 }
403 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
404 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
405 if (MemSrc && MemSrc->isConstant()) {
406 Changed = true;
407 MTI->eraseFromParent();
408 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
409 if (I->hasOneUse())
410 Dead.push_back(std::make_pair(I, MTI));
411 }
412 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
413 if (CE->use_empty()) {
414 CE->destroyConstant();
415 Changed = true;
416 }
417 } else if (Constant *C = dyn_cast<Constant>(U)) {
418 if (SafeToDestroyConstant(C)) {
419 C->destroyConstant();
420 // This could have invalidated UI, start over from scratch.
421 Dead.clear();
422 CleanupPointerRootUsers(GV);
423 return true;
424 }
425 }
426 }
427
428 for (int i = 0, e = Dead.size(); i != e; ++i) {
429 if (IsSafeComputationToRemove(Dead[i].first)) {
430 Dead[i].second->eraseFromParent();
431 Instruction *I = Dead[i].first;
432 do {
433 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
434 if (!J)
435 break;
436 I->eraseFromParent();
437 I = J;
438 } while (!isAllocationFn(I));
439 I->eraseFromParent();
440 }
441 }
442
443 if (GV->use_empty()) {
444 GV->eraseFromParent();
445 ++NumDeleted;
446 Changed = true;
447 }
448
449 return Changed;
450}
451
Chris Lattnere47ba742004-10-06 20:57:02 +0000452/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
453/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000454/// quick scan over the use list to clean up the easy and obvious cruft. This
455/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000456static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
457 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000458 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000459 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
460 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000461
Chris Lattner7a90b682004-10-07 04:16:33 +0000462 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000463 if (Init) {
464 // Replace the load with the initializer.
465 LI->replaceAllUsesWith(Init);
466 LI->eraseFromParent();
467 Changed = true;
468 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000469 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000470 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000471 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000472 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000473 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
474 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000475 Constant *SubInit = 0;
476 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000477 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000478 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000479 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000480 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000481 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000482 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000483 }
484
485 if (CE->use_empty()) {
486 CE->destroyConstant();
487 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000488 }
489 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000490 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
491 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
492 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000493 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000494 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000495 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000496 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000497 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000498 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000499
500 // If the initializer is an all-null value and we have an inbounds GEP,
501 // we already know what the result of any load from that GEP is.
502 // TODO: Handle splats.
503 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
504 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000505 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000506 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000507
Chris Lattner031955d2004-10-10 16:43:46 +0000508 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000509 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000510 Changed = true;
511 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000512 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
513 if (MI->getRawDest() == V) {
514 MI->eraseFromParent();
515 Changed = true;
516 }
517
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000518 } else if (Constant *C = dyn_cast<Constant>(U)) {
519 // If we have a chain of dead constantexprs or other things dangling from
520 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000521 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000522 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000523 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000524 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000525 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000526 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000527 }
528 }
Chris Lattner031955d2004-10-10 16:43:46 +0000529 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000530}
531
Chris Lattner941db492008-01-14 02:09:12 +0000532/// isSafeSROAElementUse - Return true if the specified instruction is a safe
533/// user of a derived expression from a global that we want to SROA.
534static bool isSafeSROAElementUse(Value *V) {
535 // We might have a dead and dangling constant hanging off of here.
536 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000537 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000538
Chris Lattner941db492008-01-14 02:09:12 +0000539 Instruction *I = dyn_cast<Instruction>(V);
540 if (!I) return false;
541
542 // Loads are ok.
543 if (isa<LoadInst>(I)) return true;
544
545 // Stores *to* the pointer are ok.
546 if (StoreInst *SI = dyn_cast<StoreInst>(I))
547 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000548
Chris Lattner941db492008-01-14 02:09:12 +0000549 // Otherwise, it must be a GEP.
550 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
551 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000552
Chris Lattner941db492008-01-14 02:09:12 +0000553 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
554 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
555 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000556
Chris Lattner941db492008-01-14 02:09:12 +0000557 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
558 I != E; ++I)
559 if (!isSafeSROAElementUse(*I))
560 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000561 return true;
562}
563
Chris Lattner941db492008-01-14 02:09:12 +0000564
565/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
566/// Look at it and its uses and decide whether it is safe to SROA this global.
567///
568static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
569 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000570 if (!isa<GetElementPtrInst>(U) &&
571 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000572 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
573 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000574
Chris Lattner941db492008-01-14 02:09:12 +0000575 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
576 // don't like < 3 operand CE's, and we don't like non-constant integer
577 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
578 // value of C.
579 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
580 !cast<Constant>(U->getOperand(1))->isNullValue() ||
581 !isa<ConstantInt>(U->getOperand(2)))
582 return false;
583
584 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
585 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000586
Chris Lattner941db492008-01-14 02:09:12 +0000587 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000588 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000589 uint64_t NumElements = AT->getNumElements();
590 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000591
Chris Lattner941db492008-01-14 02:09:12 +0000592 // Check to make sure that index falls within the array. If not,
593 // something funny is going on, so we won't do the optimization.
594 //
595 if (Idx->getZExtValue() >= NumElements)
596 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000597
Chris Lattner941db492008-01-14 02:09:12 +0000598 // We cannot scalar repl this level of the array unless any array
599 // sub-indices are in-range constants. In particular, consider:
600 // A[0][i]. We cannot know that the user isn't doing invalid things like
601 // allowing i to index an out-of-range subscript that accesses A[1].
602 //
603 // Scalar replacing *just* the outer index of the array is probably not
604 // going to be a win anyway, so just give up.
605 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000606 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000607 ++GEPI) {
608 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000609 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000610 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000611 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000612 NumElements = SubVectorTy->getNumElements();
613 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000614 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000615 "Indexed GEP type is not array, vector, or struct!");
616 continue;
617 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000618
Chris Lattner941db492008-01-14 02:09:12 +0000619 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
620 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
621 return false;
622 }
623 }
624
625 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
626 if (!isSafeSROAElementUse(*I))
627 return false;
628 return true;
629}
630
631/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
632/// is safe for us to perform this transformation.
633///
634static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
635 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
636 UI != E; ++UI) {
637 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
638 return false;
639 }
640 return true;
641}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000642
Chris Lattner941db492008-01-14 02:09:12 +0000643
Chris Lattner670c8892004-10-08 17:32:09 +0000644/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
645/// variable. This opens the door for other optimizations by exposing the
646/// behavior of the program in a more fine-grained way. We have determined that
647/// this transformation is safe already. We return the first global variable we
648/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000649static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000650 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000651 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000652 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000653
Rafael Espindolabb46f522009-01-15 20:18:42 +0000654 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000655 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000656 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000657
Chris Lattner670c8892004-10-08 17:32:09 +0000658 std::vector<GlobalVariable*> NewGlobals;
659 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
660
Chris Lattner998182b2008-04-26 07:40:11 +0000661 // Get the alignment of the global, either explicit or target-specific.
662 unsigned StartAlignment = GV->getAlignment();
663 if (StartAlignment == 0)
664 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000665
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000666 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000667 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000668 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000669 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000670 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000671 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000672 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000673 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000674 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000675 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000676 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000677 Globals.insert(GV, NGV);
678 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000679
Chris Lattner998182b2008-04-26 07:40:11 +0000680 // Calculate the known alignment of the field. If the original aggregate
681 // had 256 byte alignment for example, something might depend on that:
682 // propagate info to each field.
683 uint64_t FieldOffset = Layout.getElementOffset(i);
684 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
685 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
686 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000687 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000688 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000689 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000690 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000691 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000692 else
Chris Lattner998182b2008-04-26 07:40:11 +0000693 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000694
Chris Lattner1f21ef12005-02-23 16:53:04 +0000695 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000696 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000697 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000698
Duncan Sands777d2302009-05-09 07:06:46 +0000699 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000700 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000701 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000702 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000703 assert(In && "Couldn't get element of initializer?");
704
Chris Lattner7b550cc2009-11-06 04:27:31 +0000705 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000706 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000707 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000708 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000709 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000710 Globals.insert(GV, NGV);
711 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000712
Chris Lattner998182b2008-04-26 07:40:11 +0000713 // Calculate the known alignment of the field. If the original aggregate
714 // had 256 byte alignment for example, something might depend on that:
715 // propagate info to each field.
716 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
717 if (NewAlign > EltAlign)
718 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000719 }
720 }
721
722 if (NewGlobals.empty())
723 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000724
David Greene3215b0e2010-01-05 01:28:05 +0000725 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000726
Chris Lattner7b550cc2009-11-06 04:27:31 +0000727 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000728
729 // Loop over all of the uses of the global, replacing the constantexpr geps,
730 // with smaller constantexpr geps or direct references.
731 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000732 User *GEP = GV->use_back();
733 assert(((isa<ConstantExpr>(GEP) &&
734 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
735 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000736
Chris Lattner670c8892004-10-08 17:32:09 +0000737 // Ignore the 1th operand, which has to be zero or else the program is quite
738 // broken (undefined). Get the 2nd operand, which is the structure or array
739 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000740 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000741 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
742
Chris Lattner30ba5692004-10-11 05:54:41 +0000743 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000744
745 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000746 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000747 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000748 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000749 Idxs.push_back(NullInt);
750 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
751 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000752 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000753 } else {
754 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000755 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000756 Idxs.push_back(NullInt);
757 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
758 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000759 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000760 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000761 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000762 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000763 GEP->replaceAllUsesWith(NewPtr);
764
765 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000766 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000767 else
768 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000769 }
770
Chris Lattnere40e2d12004-10-08 20:25:55 +0000771 // Delete the old global, now that it is dead.
772 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000773 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000774
775 // Loop over the new globals array deleting any globals that are obviously
776 // dead. This can arise due to scalarization of a structure or an array that
777 // has elements that are dead.
778 unsigned FirstGlobal = 0;
779 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
780 if (NewGlobals[i]->use_empty()) {
781 Globals.erase(NewGlobals[i]);
782 if (FirstGlobal == i) ++FirstGlobal;
783 }
784
785 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000786}
787
Chris Lattner9b34a612004-10-09 21:48:45 +0000788/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000789/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000790/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000791static bool AllUsesOfValueWillTrapIfNull(const Value *V,
792 SmallPtrSet<const PHINode*, 8> &PHIs) {
793 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000794 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000795 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000796
797 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000798 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000799 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000800 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000801 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000802 return false; // Storing the value.
803 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000804 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000805 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000806 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000807 return false; // Not calling the ptr
808 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000809 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000810 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000811 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000812 return false; // Not calling the ptr
813 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000814 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000815 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000816 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000817 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000818 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000819 // If we've already seen this phi node, ignore it, it has already been
820 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000821 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
822 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000823 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000824 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000825 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000826 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000827 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000828 return false;
829 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000830 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000831 return true;
832}
833
834/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000835/// from GV will trap if the loaded value is null. Note that this also permits
836/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000837static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
838 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000839 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000840 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000841
Gabor Greif6ce02b52010-04-06 19:24:18 +0000842 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
843 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000844 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000845 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000846 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000847 // Ignore stores to the global.
848 } else {
849 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000850 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000851 return false;
852 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000853 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000854 return true;
855}
856
Chris Lattner7b550cc2009-11-06 04:27:31 +0000857static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000858 bool Changed = false;
859 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
860 Instruction *I = cast<Instruction>(*UI++);
861 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
862 LI->setOperand(0, NewV);
863 Changed = true;
864 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
865 if (SI->getOperand(1) == V) {
866 SI->setOperand(1, NewV);
867 Changed = true;
868 }
869 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000870 CallSite CS(I);
871 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000872 // Calling through the pointer! Turn into a direct call, but be careful
873 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000874 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000875 Changed = true;
876 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000877 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
878 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000879 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000880 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000881 }
882
883 if (PassedAsArg) {
884 // Being passed as an argument also. Be careful to not invalidate UI!
885 UI = V->use_begin();
886 }
887 }
888 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
889 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000890 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000891 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000892 if (CI->use_empty()) {
893 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000894 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000895 }
896 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
897 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000898 SmallVector<Constant*, 8> Idxs;
899 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000900 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
901 i != e; ++i)
902 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000903 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000904 else
905 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000906 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000907 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000908 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000909 if (GEPI->use_empty()) {
910 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000911 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000912 }
913 }
914 }
915
916 return Changed;
917}
918
919
920/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
921/// value stored into it. If there are uses of the loaded value that would trap
922/// if the loaded value is dynamically null, then we know that they cannot be
923/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000924static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
925 TargetData *TD,
926 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000927 bool Changed = false;
928
Chris Lattner92c6bd22009-01-14 00:12:58 +0000929 // Keep track of whether we are able to remove all the uses of the global
930 // other than the store that defines it.
931 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000932
Chris Lattner708148e2004-10-10 23:14:11 +0000933 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000934 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
935 User *GlobalUser = *GUI++;
936 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000937 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000938 // If we were able to delete all uses of the loads
939 if (LI->use_empty()) {
940 LI->eraseFromParent();
941 Changed = true;
942 } else {
943 AllNonStoreUsesGone = false;
944 }
945 } else if (isa<StoreInst>(GlobalUser)) {
946 // Ignore the store that stores "LV" to the global.
947 assert(GlobalUser->getOperand(1) == GV &&
948 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000949 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000950 AllNonStoreUsesGone = false;
951
952 // If we get here we could have other crazy uses that are transitively
953 // loaded.
954 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000955 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
956 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000957 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000958 }
Chris Lattner708148e2004-10-10 23:14:11 +0000959
960 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000961 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000962 ++NumGlobUses;
963 }
964
Chris Lattner708148e2004-10-10 23:14:11 +0000965 // If we nuked all of the loads, then none of the stores are needed either,
966 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000967 if (AllNonStoreUsesGone) {
Nick Lewycky39e357f2012-07-19 22:35:28 +0000968 if (isLeakCheckerRoot(GV)) {
969 Changed |= CleanupPointerRootUsers(GV);
970 } else {
971 Changed = true;
972 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
973 }
Chris Lattner708148e2004-10-10 23:14:11 +0000974 if (GV->use_empty()) {
Nick Lewycky39e357f2012-07-19 22:35:28 +0000975 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
976 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000977 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000978 ++NumDeleted;
979 }
Chris Lattner708148e2004-10-10 23:14:11 +0000980 }
981 return Changed;
982}
983
Chris Lattner30ba5692004-10-11 05:54:41 +0000984/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
985/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000986static void ConstantPropUsersOf(Value *V,
987 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000988 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
989 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +0000990 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000991 I->replaceAllUsesWith(NewC);
992
Chris Lattnerd514d822005-02-01 01:23:31 +0000993 // Advance UI to the next non-I use to avoid invalidating it!
994 // Instructions could multiply use V.
995 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000996 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000997 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000998 }
999}
1000
1001/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
1002/// variable, and transforms the program as if it always contained the result of
1003/// the specified malloc. Because it is always the result of the specified
1004/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001005/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001006static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001007 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001008 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +00001009 ConstantInt *NElements,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001010 TargetData *TD,
1011 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +00001012 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001013
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001014 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +00001015 if (NElements->getZExtValue() == 1)
1016 GlobalType = AllocTy;
1017 else
1018 // If we have an array allocation, the global variable is of an array.
1019 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +00001020
1021 // Create the new global variable. The contents of the malloc'd memory is
1022 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001023 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +00001024 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +00001025 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +00001026 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +00001027 GV->getName()+".body",
1028 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001029 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001030
Chris Lattnera6874652010-02-25 22:33:52 +00001031 // If there are bitcast users of the malloc (which is typical, usually we have
1032 // a malloc + bitcast) then replace them with uses of the new global. Update
1033 // other users to use the global as well.
1034 BitCastInst *TheBC = 0;
1035 while (!CI->use_empty()) {
1036 Instruction *User = cast<Instruction>(CI->use_back());
1037 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1038 if (BCI->getType() == NewGV->getType()) {
1039 BCI->replaceAllUsesWith(NewGV);
1040 BCI->eraseFromParent();
1041 } else {
1042 BCI->setOperand(0, NewGV);
1043 }
1044 } else {
1045 if (TheBC == 0)
1046 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1047 User->replaceUsesOfWith(CI, TheBC);
1048 }
1049 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001050
Victor Hernandez83d63912009-09-18 22:35:49 +00001051 Constant *RepValue = NewGV;
1052 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001053 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +00001054 GV->getType()->getElementType());
1055
1056 // If there is a comparison against null, we will insert a global bool to
1057 // keep track of whether the global was initialized yet or not.
1058 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001059 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +00001060 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001061 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +00001062 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001063 bool InitBoolUsed = false;
1064
1065 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +00001066 while (!GV->use_empty()) {
1067 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +00001068 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001069 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1070 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001071 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +00001072 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +00001073 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001074
Chris Lattnera6874652010-02-25 22:33:52 +00001075 LoadInst *LI = cast<LoadInst>(GV->use_back());
1076 while (!LI->use_empty()) {
1077 Use &LoadUse = LI->use_begin().getUse();
1078 if (!isa<ICmpInst>(LoadUse.getUser())) {
1079 LoadUse = RepValue;
1080 continue;
1081 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001082
Chris Lattnera6874652010-02-25 22:33:52 +00001083 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1084 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001085 // Sink the load to where the compare was, if atomic rules allow us to.
1086 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1087 LI->getOrdering(), LI->getSynchScope(),
1088 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +00001089 InitBoolUsed = true;
1090 switch (ICI->getPredicate()) {
1091 default: llvm_unreachable("Unknown ICmp Predicate!");
1092 case ICmpInst::ICMP_ULT:
1093 case ICmpInst::ICMP_SLT: // X < null -> always false
1094 LV = ConstantInt::getFalse(GV->getContext());
1095 break;
1096 case ICmpInst::ICMP_ULE:
1097 case ICmpInst::ICMP_SLE:
1098 case ICmpInst::ICMP_EQ:
1099 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1100 break;
1101 case ICmpInst::ICMP_NE:
1102 case ICmpInst::ICMP_UGE:
1103 case ICmpInst::ICMP_SGE:
1104 case ICmpInst::ICMP_UGT:
1105 case ICmpInst::ICMP_SGT:
1106 break; // no change.
1107 }
1108 ICI->replaceAllUsesWith(LV);
1109 ICI->eraseFromParent();
1110 }
1111 LI->eraseFromParent();
1112 }
Victor Hernandez83d63912009-09-18 22:35:49 +00001113
1114 // If the initialization boolean was used, insert it, otherwise delete it.
1115 if (!InitBoolUsed) {
1116 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +00001117 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001118 delete InitBool;
1119 } else
1120 GV->getParent()->getGlobalList().insert(GV, InitBool);
1121
Chris Lattnera6874652010-02-25 22:33:52 +00001122 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +00001123 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +00001124 CI->eraseFromParent();
1125
1126 // To further other optimizations, loop over all users of NewGV and try to
1127 // constant prop them. This will promote GEP instructions with constant
1128 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001129 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001130 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +00001131 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001132
1133 return NewGV;
1134}
1135
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001136/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1137/// to make sure that there are no complex uses of V. We permit simple things
1138/// like dereferencing the pointer, but not storing through the address, unless
1139/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +00001140static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1141 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +00001142 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001143 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +00001144 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +00001145 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +00001146
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001147 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1148 continue; // Fine, ignore.
1149 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001150
Gabor Greif0b520db2010-04-06 18:58:22 +00001151 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001152 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1153 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001154 continue; // Otherwise, storing through it, or storing into GV... fine.
1155 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001156
Chris Lattnera2fb2342010-04-10 18:19:22 +00001157 // Must index into the array and into the struct.
1158 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001159 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001160 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001161 continue;
1162 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001163
Gabor Greif0b520db2010-04-06 18:58:22 +00001164 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001165 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1166 // cycles.
1167 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001168 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1169 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001170 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001171 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001172
Gabor Greif0b520db2010-04-06 18:58:22 +00001173 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001174 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1175 return false;
1176 continue;
1177 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001178
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001179 return false;
1180 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001181 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001182}
1183
Chris Lattner86395032006-09-30 23:32:09 +00001184/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1185/// somewhere. Transform all uses of the allocation into loads from the
1186/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001187/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001188/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001189static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001190 GlobalVariable *GV) {
1191 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001192 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1193 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001194 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1195 // If this is the store of the allocation into the global, remove it.
1196 if (SI->getOperand(1) == GV) {
1197 SI->eraseFromParent();
1198 continue;
1199 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001200 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1201 // Insert the load in the corresponding predecessor, not right before the
1202 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001203 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001204 } else if (isa<BitCastInst>(U)) {
1205 // Must be bitcast between the malloc and store to initialize the global.
1206 ReplaceUsesOfMallocWithGlobal(U, GV);
1207 U->eraseFromParent();
1208 continue;
1209 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1210 // If this is a "GEP bitcast" and the user is a store to the global, then
1211 // just process it as a bitcast.
1212 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1213 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1214 if (SI->getOperand(1) == GV) {
1215 // Must be bitcast GEP between the malloc and store to initialize
1216 // the global.
1217 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1218 GEPI->eraseFromParent();
1219 continue;
1220 }
Chris Lattner86395032006-09-30 23:32:09 +00001221 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001222
Chris Lattner86395032006-09-30 23:32:09 +00001223 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001224 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001225 U->replaceUsesOfWith(Alloc, NL);
1226 }
1227}
1228
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001229/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1230/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1231/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001232static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001233 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1234 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001235 // We permit two users of the load: setcc comparing against the null
1236 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001237 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1238 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001239 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001240
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001241 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001242 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001243 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1244 return false;
1245 continue;
1246 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001247
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001248 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001249 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001250 // Must index into the array and into the struct.
1251 if (GEPI->getNumOperands() < 3)
1252 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001253
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001254 // Otherwise the GEP is ok.
1255 continue;
1256 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001257
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001258 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001259 if (!LoadUsingPHIsPerLoad.insert(PN))
1260 // This means some phi nodes are dependent on each other.
1261 // Avoid infinite looping!
1262 return false;
1263 if (!LoadUsingPHIs.insert(PN))
1264 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001265 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001266
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001267 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001268 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1269 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001270 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001271
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001272 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001273 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001274
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001275 // Otherwise we don't know what this is, not ok.
1276 return false;
1277 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001278
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001279 return true;
1280}
1281
1282
1283/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1284/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001285static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001286 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001287 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1288 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001289 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1290 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001291 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001292 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1293 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001294 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001295 LoadUsingPHIsPerLoad.clear();
1296 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001297
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001298 // If we reach here, we know that all uses of the loads and transitive uses
1299 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001300 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001301 // Check to verify that all operands of the PHIs are either PHIS that can be
1302 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001303 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1304 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001305 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001306 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1307 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001308
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001309 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001310 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001311
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001312 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001313 // One of the PHIs in our set is (optimistically) ok.
1314 if (LoadUsingPHIs.count(InPN))
1315 continue;
1316 return false;
1317 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001318
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001319 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001320 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001321 if (LI->getOperand(0) == GV)
1322 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001323
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001324 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001325
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001326 // Anything else is rejected.
1327 return false;
1328 }
1329 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001330
Chris Lattner86395032006-09-30 23:32:09 +00001331 return true;
1332}
1333
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001334static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1335 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001336 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001337 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001338
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001339 if (FieldNo >= FieldVals.size())
1340 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001341
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001342 // If we already have this value, just reuse the previously scalarized
1343 // version.
1344 if (Value *FieldVal = FieldVals[FieldNo])
1345 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001346
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001347 // Depending on what instruction this is, we have several cases.
1348 Value *Result;
1349 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1350 // This is a scalarized version of the load from the global. Just create
1351 // a new Load of the scalarized global.
1352 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1353 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001354 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001355 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001356 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1357 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1358 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001359 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001360 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001361
Jay Foadd8b4fb42011-03-30 11:19:20 +00001362 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001363 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001364 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001365 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001366 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001367 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1368 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001369 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001370 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001371
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001372 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001373}
1374
Chris Lattner330245e2007-09-13 17:29:05 +00001375/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1376/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001377static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001378 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001379 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001380 // If this is a comparison against null, handle it.
1381 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1382 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1383 // If we have a setcc of the loaded pointer, we can use a setcc of any
1384 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001385 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001386 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001387
Owen Anderson333c4002009-07-09 23:48:35 +00001388 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001389 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001390 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001391 SCI->replaceAllUsesWith(New);
1392 SCI->eraseFromParent();
1393 return;
1394 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001395
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001396 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001397 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1398 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1399 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001400
Chris Lattnera637a8b2007-09-13 18:00:31 +00001401 // Load the pointer for this field.
1402 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001403 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001404 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001405
Chris Lattnera637a8b2007-09-13 18:00:31 +00001406 // Create the new GEP idx vector.
1407 SmallVector<Value*, 8> GEPIdx;
1408 GEPIdx.push_back(GEPI->getOperand(1));
1409 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001410
Jay Foada9203102011-07-25 09:48:08 +00001411 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001412 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001413 GEPI->replaceAllUsesWith(NGEPI);
1414 GEPI->eraseFromParent();
1415 return;
1416 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001417
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001418 // Recursively transform the users of PHI nodes. This will lazily create the
1419 // PHIs that are needed for individual elements. Keep track of what PHIs we
1420 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1421 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1422 // already been seen first by another load, so its uses have already been
1423 // processed.
1424 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001425 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1426 std::vector<Value*>())).second)
1427 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001428
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001429 // If this is the first time we've seen this PHI, recursively process all
1430 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001431 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1432 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001433 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001434 }
Chris Lattner330245e2007-09-13 17:29:05 +00001435}
1436
Chris Lattner86395032006-09-30 23:32:09 +00001437/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1438/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1439/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001440/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001441static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001442 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001443 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001444 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001445 UI != E; ) {
1446 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001447 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001448 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001449
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001450 if (Load->use_empty()) {
1451 Load->eraseFromParent();
1452 InsertedScalarizedValues.erase(Load);
1453 }
Chris Lattner86395032006-09-30 23:32:09 +00001454}
1455
Victor Hernandez83d63912009-09-18 22:35:49 +00001456/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1457/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001458static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Nick Lewyckybc384a12012-02-05 19:48:37 +00001459 Value *NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001460 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Nick Lewyckybc384a12012-02-05 19:48:37 +00001461 Type *MAT = getMallocAllocatedType(CI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001462 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001463
1464 // There is guaranteed to be at least one use of the malloc (storing
1465 // it into GV). If there are other uses, change them to be uses of
1466 // the global to simplify later code. This also deletes the store
1467 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001468 ReplaceUsesOfMallocWithGlobal(CI, GV);
1469
Victor Hernandez83d63912009-09-18 22:35:49 +00001470 // Okay, at this point, there are no users of the malloc. Insert N
1471 // new mallocs at the same place as CI, and N globals.
1472 std::vector<Value*> FieldGlobals;
1473 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001474
Victor Hernandez83d63912009-09-18 22:35:49 +00001475 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001476 Type *FieldTy = STy->getElementType(FieldNo);
1477 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001478
Victor Hernandez83d63912009-09-18 22:35:49 +00001479 GlobalVariable *NGV =
1480 new GlobalVariable(*GV->getParent(),
1481 PFieldTy, false, GlobalValue::InternalLinkage,
1482 Constant::getNullValue(PFieldTy),
1483 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001484 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001485 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001486
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001487 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001488 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001489 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001490 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001491 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1492 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001493 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001494 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001495 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001496 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001497 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001498
Victor Hernandez83d63912009-09-18 22:35:49 +00001499 // The tricky aspect of this transformation is handling the case when malloc
1500 // fails. In the original code, malloc failing would set the result pointer
1501 // of malloc to null. In this case, some mallocs could succeed and others
1502 // could fail. As such, we emit code that looks like this:
1503 // F0 = malloc(field0)
1504 // F1 = malloc(field1)
1505 // F2 = malloc(field2)
1506 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1507 // if (F0) { free(F0); F0 = 0; }
1508 // if (F1) { free(F1); F1 = 0; }
1509 // if (F2) { free(F2); F2 = 0; }
1510 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001511 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001512 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1513 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001514 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001515 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001516 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1517 Constant::getNullValue(FieldMallocs[i]->getType()),
1518 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001519 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001520 }
1521
1522 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001523 BasicBlock *OrigBB = CI->getParent();
1524 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001525
Victor Hernandez83d63912009-09-18 22:35:49 +00001526 // Create the block to check the first condition. Put all these blocks at the
1527 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001528 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1529 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001530 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001531
Victor Hernandez83d63912009-09-18 22:35:49 +00001532 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1533 // branch on RunningOr.
1534 OrigBB->getTerminator()->eraseFromParent();
1535 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001536
Victor Hernandez83d63912009-09-18 22:35:49 +00001537 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1538 // pointer, because some may be null while others are not.
1539 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1540 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001541 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001542 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001543 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001544 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001545 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001546 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001547 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1548 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001549
1550 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001551 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001552 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1553 FreeBlock);
1554 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001555
Victor Hernandez83d63912009-09-18 22:35:49 +00001556 NullPtrBlock = NextBlock;
1557 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001558
Victor Hernandez83d63912009-09-18 22:35:49 +00001559 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001560
1561 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001562 CI->eraseFromParent();
1563
1564 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1565 /// update all uses of the load, keep track of what scalarized loads are
1566 /// inserted for a given load.
1567 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1568 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001569
Victor Hernandez83d63912009-09-18 22:35:49 +00001570 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001571
Victor Hernandez83d63912009-09-18 22:35:49 +00001572 // Okay, the malloc site is completely handled. All of the uses of GV are now
1573 // loads, and all uses of those loads are simple. Rewrite them to use loads
1574 // of the per-field globals instead.
1575 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1576 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001577
Victor Hernandez83d63912009-09-18 22:35:49 +00001578 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001579 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001580 continue;
1581 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001582
Victor Hernandez83d63912009-09-18 22:35:49 +00001583 // Must be a store of null.
1584 StoreInst *SI = cast<StoreInst>(User);
1585 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1586 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001587
Victor Hernandez83d63912009-09-18 22:35:49 +00001588 // Insert a store of null into each global.
1589 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001590 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001591 Constant *Null = Constant::getNullValue(PT->getElementType());
1592 new StoreInst(Null, FieldGlobals[i], SI);
1593 }
1594 // Erase the original store.
1595 SI->eraseFromParent();
1596 }
1597
1598 // While we have PHIs that are interesting to rewrite, do it.
1599 while (!PHIsToRewrite.empty()) {
1600 PHINode *PN = PHIsToRewrite.back().first;
1601 unsigned FieldNo = PHIsToRewrite.back().second;
1602 PHIsToRewrite.pop_back();
1603 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1604 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1605
1606 // Add all the incoming values. This can materialize more phis.
1607 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1608 Value *InVal = PN->getIncomingValue(i);
1609 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001610 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001611 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1612 }
1613 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001614
Victor Hernandez83d63912009-09-18 22:35:49 +00001615 // Drop all inter-phi links and any loads that made it this far.
1616 for (DenseMap<Value*, std::vector<Value*> >::iterator
1617 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1618 I != E; ++I) {
1619 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1620 PN->dropAllReferences();
1621 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1622 LI->dropAllReferences();
1623 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001624
Victor Hernandez83d63912009-09-18 22:35:49 +00001625 // Delete all the phis and loads now that inter-references are dead.
1626 for (DenseMap<Value*, std::vector<Value*> >::iterator
1627 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1628 I != E; ++I) {
1629 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1630 PN->eraseFromParent();
1631 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1632 LI->eraseFromParent();
1633 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001634
Victor Hernandez83d63912009-09-18 22:35:49 +00001635 // The old global is now dead, remove it.
1636 GV->eraseFromParent();
1637
1638 ++NumHeapSRA;
1639 return cast<GlobalVariable>(FieldGlobals[0]);
1640}
1641
Chris Lattnere61d0a62008-12-15 21:02:25 +00001642/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1643/// pointer global variable with a single value stored it that is a malloc or
1644/// cast of malloc.
1645static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001646 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001647 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001648 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001649 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001650 TargetData *TD,
1651 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001652 if (!TD)
1653 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001654
Victor Hernandez83d63912009-09-18 22:35:49 +00001655 // If this is a malloc of an abstract type, don't touch it.
1656 if (!AllocTy->isSized())
1657 return false;
1658
1659 // We can't optimize this global unless all uses of it are *known* to be
1660 // of the malloc value, not of the null initializer value (consider a use
1661 // that compares the global's value against zero to see if the malloc has
1662 // been reached). To do this, we check to see if all uses of the global
1663 // would trap if the global were null: this proves that they must all
1664 // happen after the malloc.
1665 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1666 return false;
1667
1668 // We can't optimize this if the malloc itself is used in a complex way,
1669 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001670 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001671 // GEP'd. These are all things we could transform to using the global
1672 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001673 SmallPtrSet<const PHINode*, 8> PHIs;
1674 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1675 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001676
1677 // If we have a global that is only initialized with a fixed size malloc,
1678 // transform the program to use global memory instead of malloc'd memory.
1679 // This eliminates dynamic allocation, avoids an indirection accessing the
1680 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001681 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001682 Value *NElems = getMallocArraySize(CI, TD, true);
1683 if (!NElems)
1684 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001685
Evan Cheng86cd4452010-04-14 20:52:55 +00001686 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1687 // Restrict this transformation to only working on small allocations
1688 // (2048 bytes currently), as we don't want to introduce a 16M global or
1689 // something.
1690 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001691 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001692 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001693 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001694
Evan Cheng86cd4452010-04-14 20:52:55 +00001695 // If the allocation is an array of structures, consider transforming this
1696 // into multiple malloc'd arrays, one for each field. This is basically
1697 // SRoA for malloc'd memory.
1698
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001699 if (Ordering != NotAtomic)
1700 return false;
1701
Evan Cheng86cd4452010-04-14 20:52:55 +00001702 // If this is an allocation of a fixed size array of structs, analyze as a
1703 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001704 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001705 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001706 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001707
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001708 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001709 if (!AllocSTy)
1710 return false;
1711
1712 // This the structure has an unreasonable number of fields, leave it
1713 // alone.
1714 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1715 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1716
1717 // If this is a fixed size array, transform the Malloc to be an alloc of
1718 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001719 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1720 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001721 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1722 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1723 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1724 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1725 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001726 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001727 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1728 CI->replaceAllUsesWith(Cast);
1729 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001730 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1731 CI = cast<CallInst>(BCI->getOperand(0));
1732 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001733 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001734 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001735
Nick Lewyckybc384a12012-02-05 19:48:37 +00001736 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true), TD);
Evan Cheng86cd4452010-04-14 20:52:55 +00001737 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001738 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001739
Victor Hernandez83d63912009-09-18 22:35:49 +00001740 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001741}
Victor Hernandez83d63912009-09-18 22:35:49 +00001742
Chris Lattner9b34a612004-10-09 21:48:45 +00001743// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1744// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001745static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001746 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001747 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001748 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001749 // Ignore no-op GEPs and bitcasts.
1750 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001751
Chris Lattner708148e2004-10-10 23:14:11 +00001752 // If we are dealing with a pointer global that is initialized to null and
1753 // only has one (non-null) value stored into it, then we can optimize any
1754 // users of the loaded value (often calls and loads) that would trap if the
1755 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001756 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001757 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001758 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1759 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001760 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001761
Chris Lattner708148e2004-10-10 23:14:11 +00001762 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001763 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001764 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001765 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Nick Lewyckybc384a12012-02-05 19:48:37 +00001766 Type *MallocType = getMallocAllocatedType(CI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001767 if (MallocType &&
1768 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1769 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001770 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001771 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001772 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001773
Chris Lattner9b34a612004-10-09 21:48:45 +00001774 return false;
1775}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001776
Chris Lattner58e44f42008-01-14 01:17:44 +00001777/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1778/// two values ever stored into GV are its initializer and OtherVal. See if we
1779/// can shrink the global into a boolean and select between the two values
1780/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001781static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001782 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001783
Chris Lattner58e44f42008-01-14 01:17:44 +00001784 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001785 // an FP value, pointer or vector, don't do this optimization because a select
1786 // between them is very expensive and unlikely to lead to later
1787 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1788 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001789 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001790 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001791 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001792 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001793
Chris Lattner58e44f42008-01-14 01:17:44 +00001794 // Walk the use list of the global seeing if all the uses are load or store.
1795 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001796 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1797 User *U = *I;
1798 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001799 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001800 }
1801
David Greene3215b0e2010-01-05 01:28:05 +00001802 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001803
Chris Lattner96a86b22004-12-12 05:53:50 +00001804 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001805 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1806 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001807 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001808 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001809 GV->getName()+".b",
Hans Wennborgce718ff2012-06-23 11:37:03 +00001810 GV->getThreadLocalMode());
Chris Lattner96a86b22004-12-12 05:53:50 +00001811 GV->getParent()->getGlobalList().insert(GV, NewGV);
1812
1813 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001814 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001815 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001816
1817 // If initialized to zero and storing one into the global, we can use a cast
1818 // instead of a select to synthesize the desired value.
1819 bool IsOneZero = false;
1820 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001821 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001822
1823 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001824 Instruction *UI = cast<Instruction>(GV->use_back());
1825 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001826 // Change the store into a boolean store.
1827 bool StoringOther = SI->getOperand(0) == OtherVal;
1828 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001829 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001830 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001831 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1832 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001833 else {
1834 // Otherwise, we are storing a previously loaded copy. To do this,
1835 // change the copy from copying the original value to just copying the
1836 // bool.
1837 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1838
Gabor Greif9e4f2432010-06-24 14:42:01 +00001839 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001840 // select instruction. If not, it will be a load of the original
1841 // global.
1842 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1843 assert(LI->getOperand(0) == GV && "Not a copy!");
1844 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001845 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1846 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001847 } else {
1848 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1849 "This is not a form that we understand!");
1850 StoreVal = StoredVal->getOperand(0);
1851 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1852 }
1853 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001854 new StoreInst(StoreVal, NewGV, false, 0,
1855 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001856 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001857 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001858 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001859 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1860 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001861 Value *NSI;
1862 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001863 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001864 else
Gabor Greif051a9502008-04-06 20:25:17 +00001865 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001866 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001867 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001868 }
1869 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001870 }
1871
1872 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001873 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001874}
1875
1876
Nick Lewyckydb292a62012-02-12 00:52:26 +00001877/// ProcessGlobal - Analyze the specified global variable and optimize it if
1878/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001879bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1880 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001881 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001882 return false;
1883
1884 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001885 GV->removeDeadConstantUsers();
1886
1887 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001888 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001889 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001890 ++NumDeleted;
1891 return true;
1892 }
1893
Rafael Espindola2f135d42012-06-15 18:00:24 +00001894 if (!GV->hasLocalLinkage())
1895 return false;
1896
Rafael Espindolac4440e32011-01-19 16:32:21 +00001897 SmallPtrSet<const PHINode*, 16> PHIUsers;
1898 GlobalStatus GS;
1899
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001900 if (AnalyzeGlobal(GV, GS, PHIUsers))
1901 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001902
Rafael Espindolac4440e32011-01-19 16:32:21 +00001903 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1904 GV->setUnnamedAddr(true);
1905 NumUnnamed++;
1906 }
1907
1908 if (GV->isConstant() || !GV->hasInitializer())
1909 return false;
1910
1911 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1912}
1913
1914/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1915/// it if possible. If we make a change, return true.
1916bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1917 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001918 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001919 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001920 // If this is a first class global and has only one accessing function
1921 // and this function is main (which we know is not recursive we can make
1922 // this global a local variable) we replace the global with a local alloca
1923 // in this function.
1924 //
1925 // NOTE: It doesn't make sense to promote non single-value types since we
1926 // are just replacing static memory to stack memory.
1927 //
1928 // If the global is in different address space, don't bring it to stack.
1929 if (!GS.HasMultipleAccessingFunctions &&
1930 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1931 GV->getType()->getElementType()->isSingleValueType() &&
1932 GS.AccessingFunction->getName() == "main" &&
1933 GS.AccessingFunction->hasExternalLinkage() &&
1934 GV->getType()->getAddressSpace() == 0) {
1935 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001936 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001937 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001938 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001939 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001940 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001941 if (!isa<UndefValue>(GV->getInitializer()))
1942 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001943
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001944 GV->replaceAllUsesWith(Alloca);
1945 GV->eraseFromParent();
1946 ++NumLocalized;
1947 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001948 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001949
1950 // If the global is never loaded (but may be stored to), it is dead.
1951 // Delete it now.
1952 if (!GS.isLoaded) {
1953 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1954
Nick Lewycky39e357f2012-07-19 22:35:28 +00001955 bool Changed;
1956 if (isLeakCheckerRoot(GV)) {
1957 // Delete any constant stores to the global.
1958 Changed = CleanupPointerRootUsers(GV);
1959 } else {
1960 // Delete any stores we can find to the global. We may not be able to
1961 // make it completely dead though.
1962 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1963 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001964
1965 // If the global is dead now, delete it.
1966 if (GV->use_empty()) {
1967 GV->eraseFromParent();
1968 ++NumDeleted;
1969 Changed = true;
1970 }
1971 return Changed;
1972
1973 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1974 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1975 GV->setConstant(true);
1976
1977 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001978 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001979
1980 // If the global is dead now, just nuke it.
1981 if (GV->use_empty()) {
1982 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1983 << "all users and delete global!\n");
1984 GV->eraseFromParent();
1985 ++NumDeleted;
1986 }
1987
1988 ++NumMarked;
1989 return true;
1990 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1991 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1992 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1993 GVI = FirstNewGV; // Don't skip the newly produced globals!
1994 return true;
1995 }
1996 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1997 // If the initial value for the global was an undef value, and if only
1998 // one other value was stored into it, we can just change the
1999 // initializer to be the stored value, then delete all stores to the
2000 // global. This allows us to mark it constant.
2001 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2002 if (isa<UndefValue>(GV->getInitializer())) {
2003 // Change the initial value here.
2004 GV->setInitializer(SOVConstant);
2005
2006 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00002007 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002008
2009 if (GV->use_empty()) {
2010 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky39e357f2012-07-19 22:35:28 +00002011 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002012 GV->eraseFromParent();
2013 ++NumDeleted;
2014 } else {
2015 GVI = GV;
2016 }
2017 ++NumSubstitute;
2018 return true;
2019 }
2020
2021 // Try to optimize globals based on the knowledge that only one value
2022 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00002023 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00002024 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00002025 return true;
2026
2027 // Otherwise, if the global was not a boolean, we can shrink it to be a
2028 // boolean.
2029 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2030 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
2031 ++NumShrunkToBool;
2032 return true;
2033 }
2034 }
2035
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002036 return false;
2037}
2038
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002039/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2040/// function, changing them to FastCC.
2041static void ChangeCalleesToFastCall(Function *F) {
2042 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002043 if (isa<BlockAddress>(*UI))
2044 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002045 CallSite User(cast<Instruction>(*UI));
2046 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00002047 }
2048}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00002049
Devang Patel05988662008-09-25 21:00:45 +00002050static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00002051 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00002052 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00002053 continue;
2054
Duncan Sands548448a2008-02-18 17:32:13 +00002055 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00002056 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00002057 }
2058
2059 return Attrs;
2060}
2061
2062static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00002063 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002064 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00002065 if (isa<BlockAddress>(*UI))
2066 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00002067 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00002068 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00002069 }
2070}
2071
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002072bool GlobalOpt::OptimizeFunctions(Module &M) {
2073 bool Changed = false;
2074 // Optimize functions.
2075 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2076 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002077 // Functions without names cannot be referenced outside this module.
2078 if (!F->hasName() && !F->isDeclaration())
2079 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002080 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00002081 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00002082 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002083 Changed = true;
2084 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00002085 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002086 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00002087 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002088 // If this function has C calling conventions, is not a varargs
2089 // function, and is only called directly, promote it to use the Fast
2090 // calling convention.
2091 F->setCallingConv(CallingConv::Fast);
2092 ChangeCalleesToFastCall(F);
2093 ++NumFastCallFns;
2094 Changed = true;
2095 }
2096
Devang Patel05988662008-09-25 21:00:45 +00002097 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00002098 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00002099 // The function is not used by a trampoline intrinsic, so it is safe
2100 // to remove the 'nest' attribute.
2101 RemoveNestAttribute(F);
2102 ++NumNestRemoved;
2103 Changed = true;
2104 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002105 }
2106 }
2107 return Changed;
2108}
2109
2110bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2111 bool Changed = false;
2112 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2113 GVI != E; ) {
2114 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002115 // Global variables without names cannot be referenced outside this module.
2116 if (!GV->hasName() && !GV->isDeclaration())
2117 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002118 // Simplify the initializer.
2119 if (GV->hasInitializer())
2120 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00002121 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00002122 if (New && New != CE)
2123 GV->setInitializer(New);
2124 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00002125
2126 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002127 }
2128 return Changed;
2129}
2130
Nick Lewycky2c44a802011-04-08 07:30:21 +00002131/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002132/// initializers have an init priority of 65535.
2133GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002134 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2135 if (GV == 0) return 0;
2136
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002137 // Verify that the initializer is simple enough for us to handle. We are
2138 // only allowed to optimize the initializer if it is unique.
2139 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002140
2141 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2142 return GV;
2143 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00002144
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002145 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002146 if (isa<ConstantAggregateZero>(*i))
2147 continue;
2148 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002149 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2150 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002151
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002152 // Must have a function or null ptr.
2153 if (!isa<Function>(CS->getOperand(1)))
2154 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002155
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002156 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00002157 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2158 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002159 return 0;
2160 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002161
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00002162 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002163}
2164
Chris Lattnerdb973e62005-09-26 02:31:18 +00002165/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2166/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002167static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002168 if (GV->getInitializer()->isNullValue())
2169 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002170 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2171 std::vector<Function*> Result;
2172 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00002173 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2174 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002175 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2176 }
2177 return Result;
2178}
2179
Chris Lattnerdb973e62005-09-26 02:31:18 +00002180/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2181/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002182static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002183 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002184 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002185 Constant *CSVals[2];
2186 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2187 CSVals[1] = 0;
2188
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002189 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002190 cast <StructType>(
2191 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002192
Chris Lattnerdb973e62005-09-26 02:31:18 +00002193 // Create the new init list.
2194 std::vector<Constant*> CAList;
2195 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002196 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002197 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002198 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002199 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002200 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002201 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002202 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002203 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002204 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002205 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002206 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002207 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002208
Chris Lattnerdb973e62005-09-26 02:31:18 +00002209 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002210 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002211 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002212
Chris Lattnerdb973e62005-09-26 02:31:18 +00002213 // If we didn't change the number of elements, don't create a new GV.
2214 if (CA->getType() == GCL->getInitializer()->getType()) {
2215 GCL->setInitializer(CA);
2216 return GCL;
2217 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002218
Chris Lattnerdb973e62005-09-26 02:31:18 +00002219 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002220 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002221 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002222 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002223 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002224 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002225
Chris Lattnerdb973e62005-09-26 02:31:18 +00002226 // Nuke the old list, replacing any uses with the new one.
2227 if (!GCL->use_empty()) {
2228 Constant *V = NGV;
2229 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002230 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002231 GCL->replaceAllUsesWith(V);
2232 }
2233 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002234
Chris Lattnerdb973e62005-09-26 02:31:18 +00002235 if (Ctors.size())
2236 return NGV;
2237 else
2238 return 0;
2239}
Chris Lattner79c11012005-09-26 04:44:35 +00002240
2241
Chris Lattner1945d582010-12-07 04:33:29 +00002242static inline bool
2243isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002244 SmallPtrSet<Constant*, 8> &SimpleConstants,
2245 const TargetData *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002246
2247
2248/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2249/// handled by the code generator. We don't want to generate something like:
2250/// void *X = &X/42;
2251/// because the code generator doesn't have a relocation that can handle that.
2252///
2253/// This function should be called if C was not found (but just got inserted)
2254/// in SimpleConstants to avoid having to rescan the same constants all the
2255/// time.
2256static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002257 SmallPtrSet<Constant*, 8> &SimpleConstants,
2258 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002259 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2260 // all supported.
2261 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2262 isa<GlobalValue>(C))
2263 return true;
2264
2265 // Aggregate values are safe if all their elements are.
2266 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2267 isa<ConstantVector>(C)) {
2268 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2269 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002270 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002271 return false;
2272 }
2273 return true;
2274 }
2275
2276 // We don't know exactly what relocations are allowed in constant expressions,
2277 // so we allow &global+constantoffset, which is safe and uniformly supported
2278 // across targets.
2279 ConstantExpr *CE = cast<ConstantExpr>(C);
2280 switch (CE->getOpcode()) {
2281 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002282 // Bitcast is fine if the casted value is fine.
2283 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2284
Chris Lattner1945d582010-12-07 04:33:29 +00002285 case Instruction::IntToPtr:
2286 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002287 // int <=> ptr is fine if the int type is the same size as the
2288 // pointer type.
2289 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2290 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2291 return false;
2292 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002293
2294 // GEP is fine if it is simple + constant offset.
2295 case Instruction::GetElementPtr:
2296 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2297 if (!isa<ConstantInt>(CE->getOperand(i)))
2298 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002299 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002300
2301 case Instruction::Add:
2302 // We allow simple+cst.
2303 if (!isa<ConstantInt>(CE->getOperand(1)))
2304 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002305 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002306 }
2307 return false;
2308}
2309
2310static inline bool
2311isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002312 SmallPtrSet<Constant*, 8> &SimpleConstants,
2313 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002314 // If we already checked this constant, we win.
2315 if (!SimpleConstants.insert(C)) return true;
2316 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002317 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002318}
2319
2320
Chris Lattner79c11012005-09-26 04:44:35 +00002321/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002322/// enough for us to understand. In particular, if it is a cast to anything
2323/// other than from one pointer type to another pointer type, we punt.
2324/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002325/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002326static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002327 // Conservatively, avoid aggregate types. This is because we don't
2328 // want to worry about them partially overlapping other stores.
2329 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2330 return false;
2331
Dan Gohmanfd54a892009-09-07 22:31:26 +00002332 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002333 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002334 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002335 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002336
Owen Andersone95a32c2011-01-14 22:31:13 +00002337 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002338 // Handle a constantexpr gep.
2339 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002340 isa<GlobalVariable>(CE->getOperand(0)) &&
2341 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002342 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002343 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002344 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002345 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002346 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002347
Dan Gohman80bdc962009-09-07 22:44:55 +00002348 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002349 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002350 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002351
2352 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002353 // notional bounds of the corresponding static array types.
2354 if (!CE->isGEPWithNoNotionalOverIndexing())
2355 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002356
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002357 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002358
2359 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2360 // and we know how to evaluate it by moving the bitcast from the pointer
2361 // operand to the value operand.
2362 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002363 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002364 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2365 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002366 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002367 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002368 }
2369
Chris Lattner79c11012005-09-26 04:44:35 +00002370 return false;
2371}
2372
Chris Lattner798b4d52005-09-26 06:52:44 +00002373/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2374/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2375/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2376static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002377 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002378 // Base case of the recursion.
2379 if (OpNo == Addr->getNumOperands()) {
2380 assert(Val->getType() == Init->getType() && "Type mismatch!");
2381 return Val;
2382 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002383
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002384 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002385 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002386 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002387 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2388 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002389
Chris Lattner798b4d52005-09-26 06:52:44 +00002390 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002391 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2392 unsigned Idx = CU->getZExtValue();
2393 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002394 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002395
Chris Lattner798b4d52005-09-26 06:52:44 +00002396 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002397 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002398 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002399
2400 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002401 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002402
2403 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002404 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002405 NumElts = ATy->getNumElements();
2406 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002407 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002408
2409 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002410 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2411 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002412
2413 assert(CI->getZExtValue() < NumElts);
2414 Elts[CI->getZExtValue()] =
2415 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2416
2417 if (Init->getType()->isArrayTy())
2418 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2419 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002420}
2421
Chris Lattner79c11012005-09-26 04:44:35 +00002422/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2423/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002424static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002425 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2426 assert(GV->hasInitializer());
2427 GV->setInitializer(Val);
2428 return;
2429 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002430
Chris Lattner798b4d52005-09-26 06:52:44 +00002431 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2432 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002433 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002434}
2435
Nick Lewycky7fa76772012-02-20 03:25:59 +00002436namespace {
2437
2438/// Evaluator - This class evaluates LLVM IR, producing the Constant
2439/// representing each SSA instruction. Changes to global variables are stored
2440/// in a mapping that can be iterated over after the evaluation is complete.
2441/// Once an evaluation call fails, the evaluation object should not be reused.
2442class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002443public:
Nick Lewycky7fa76772012-02-20 03:25:59 +00002444 Evaluator(const TargetData *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002445 : TD(TD), TLI(TLI) {
2446 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2447 }
2448
Nick Lewycky7fa76772012-02-20 03:25:59 +00002449 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002450 DeleteContainerPointers(ValueStack);
2451 while (!AllocaTmps.empty()) {
2452 GlobalVariable *Tmp = AllocaTmps.back();
2453 AllocaTmps.pop_back();
2454
2455 // If there are still users of the alloca, the program is doing something
2456 // silly, e.g. storing the address of the alloca somewhere and using it
2457 // later. Since this is undefined, we'll just make it be null.
2458 if (!Tmp->use_empty())
2459 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2460 delete Tmp;
2461 }
2462 }
2463
2464 /// EvaluateFunction - Evaluate a call to function F, returning true if
2465 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2466 /// arguments for the function.
2467 bool EvaluateFunction(Function *F, Constant *&RetVal,
2468 const SmallVectorImpl<Constant*> &ActualArgs);
2469
2470 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2471 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2472 /// control flows into, or null upon return.
2473 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2474
2475 Constant *getVal(Value *V) {
2476 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2477 Constant *R = ValueStack.back()->lookup(V);
2478 assert(R && "Reference to an uncomputed value!");
2479 return R;
2480 }
2481
2482 void setVal(Value *V, Constant *C) {
2483 ValueStack.back()->operator[](V) = C;
2484 }
2485
2486 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2487 return MutatedMemory;
2488 }
2489
2490 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2491 return Invariants;
2492 }
2493
2494private:
2495 Constant *ComputeLoadResult(Constant *P);
2496
2497 /// ValueStack - As we compute SSA register values, we store their contents
2498 /// here. The back of the vector contains the current function and the stack
2499 /// contains the values in the calling frames.
2500 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2501
2502 /// CallStack - This is used to detect recursion. In pathological situations
2503 /// we could hit exponential behavior, but at least there is nothing
2504 /// unbounded.
2505 SmallVector<Function*, 4> CallStack;
2506
2507 /// MutatedMemory - For each store we execute, we update this map. Loads
2508 /// check this to get the most up-to-date value. If evaluation is successful,
2509 /// this state is committed to the process.
2510 DenseMap<Constant*, Constant*> MutatedMemory;
2511
2512 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2513 /// to represent its body. This vector is needed so we can delete the
2514 /// temporary globals when we are done.
2515 SmallVector<GlobalVariable*, 32> AllocaTmps;
2516
2517 /// Invariants - These global variables have been marked invariant by the
2518 /// static constructor.
2519 SmallPtrSet<GlobalVariable*, 8> Invariants;
2520
2521 /// SimpleConstants - These are constants we have checked and know to be
2522 /// simple enough to live in a static initializer of a global.
2523 SmallPtrSet<Constant*, 8> SimpleConstants;
2524
2525 const TargetData *TD;
2526 const TargetLibraryInfo *TLI;
2527};
2528
Nick Lewycky7fa76772012-02-20 03:25:59 +00002529} // anonymous namespace
2530
Chris Lattner562a0552005-09-26 05:16:34 +00002531/// ComputeLoadResult - Return the value that would be computed by a load from
2532/// P after the stores reflected by 'memory' have been performed. If we can't
2533/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002534Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002535 // If this memory location has been recently stored, use the stored value: it
2536 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002537 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2538 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002539
Chris Lattner04de1cf2005-09-26 05:15:37 +00002540 // Access it.
2541 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002542 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002543 return GV->getInitializer();
2544 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002545 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002546
Chris Lattner798b4d52005-09-26 06:52:44 +00002547 // Handle a constantexpr getelementptr.
2548 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2549 if (CE->getOpcode() == Instruction::GetElementPtr &&
2550 isa<GlobalVariable>(CE->getOperand(0))) {
2551 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002552 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002553 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002554 }
2555
2556 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002557}
2558
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002559/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2560/// successful, false if we can't evaluate it. NewBB returns the next BB that
2561/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002562bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2563 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002564 // This is the main evaluation loop.
2565 while (1) {
2566 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002567
Chris Lattner79c11012005-09-26 04:44:35 +00002568 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002569 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002570 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002571 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2572 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002573 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002574 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002575 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002576
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002577 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002578
2579 // If this might be too difficult for the backend to handle (e.g. the addr
2580 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002581 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002582 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002583
2584 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2585 if (CE->getOpcode() == Instruction::BitCast) {
2586 // If we're evaluating a store through a bitcast, then we need
2587 // to pull the bitcast off the pointer type and push it onto the
2588 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002589 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002590
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002591 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002592
Owen Anderson66f708f2011-01-16 04:33:33 +00002593 // In order to push the bitcast onto the stored value, a bitcast
2594 // from NewTy to Val's type must be legal. If it's not, we can try
2595 // introspecting NewTy to find a legal conversion.
2596 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2597 // If NewTy is a struct, we can convert the pointer to the struct
2598 // into a pointer to its first member.
2599 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002600 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002601 NewTy = STy->getTypeAtIndex(0U);
2602
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002603 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002604 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2605 Constant * const IdxList[] = {IdxZero, IdxZero};
2606
Jay Foadb4263a62011-07-22 08:52:50 +00002607 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002608 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2609 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2610
Owen Anderson66f708f2011-01-16 04:33:33 +00002611 // If we can't improve the situation by introspecting NewTy,
2612 // we have to give up.
2613 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002614 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002615 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002616 }
2617
Owen Anderson66f708f2011-01-16 04:33:33 +00002618 // If we found compatible types, go ahead and push the bitcast
2619 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002620 Val = ConstantExpr::getBitCast(Val, NewTy);
2621 }
2622
Chris Lattner79c11012005-09-26 04:44:35 +00002623 MutatedMemory[Ptr] = Val;
2624 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002625 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002626 getVal(BO->getOperand(0)),
2627 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002628 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002629 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002630 getVal(CI->getOperand(0)),
2631 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002632 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002633 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002634 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002635 CI->getType());
2636 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002637 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2638 getVal(SI->getOperand(1)),
2639 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002640 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002641 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002642 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002643 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2644 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002645 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002646 InstResult =
2647 ConstantExpr::getGetElementPtr(P, GEPOps,
2648 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002649 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002650 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002651 Constant *Ptr = getVal(LI->getOperand(0));
2652 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2653 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2654 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002655 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002656 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002657 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002658 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002659 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002660 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002661 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002662 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002663 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002664 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2665 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002666
2667 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002668 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002669 ++CurInst;
2670 continue;
2671 }
2672
Chris Lattner7cd580f2006-07-07 21:37:01 +00002673 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002674 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002675
Nick Lewycky81266c52012-02-17 06:59:21 +00002676 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2677 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2678 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002679 Constant *Ptr = getVal(MSI->getDest());
2680 Constant *Val = getVal(MSI->getValue());
2681 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002682 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2683 // This memset is a no-op.
2684 ++CurInst;
2685 continue;
2686 }
2687 }
2688
2689 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2690 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2691 ++CurInst;
2692 continue;
2693 }
2694
2695 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2696 // We don't insert an entry into Values, as it doesn't have a
2697 // meaningful return value.
2698 if (!II->use_empty())
2699 return false;
2700 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002701 Value *PtrArg = getVal(II->getArgOperand(1));
2702 Value *Ptr = PtrArg->stripPointerCasts();
2703 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2704 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2705 if (!Size->isAllOnesValue() &&
2706 Size->getValue().getLimitedValue() >=
2707 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002708 Invariants.insert(GV);
2709 }
2710 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002711 ++CurInst;
2712 continue;
2713 }
2714 return false;
2715 }
2716
Chris Lattnercd271422005-09-27 04:45:34 +00002717 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002718 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002719 if (!Callee || Callee->mayBeOverridden())
2720 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002721
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002722 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002723 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002724 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002725
Reid Spencer5cbf9852007-01-30 20:08:39 +00002726 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002727 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002728 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002729 InstResult = C;
2730 } else {
2731 return false;
2732 }
2733 } else {
2734 if (Callee->getFunctionType()->isVarArg())
2735 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002736
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002737 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002738 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002739 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2740 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002741 return false;
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002742 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002743 InstResult = RetVal;
2744 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002745 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002746 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2747 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002748 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002749 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002750 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002751 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002752 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002753
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002754 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002755 }
2756 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2757 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002758 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002759 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002760 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002761 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002762 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002763 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002764 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002765 else
2766 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002767 } else if (isa<ReturnInst>(CurInst)) {
2768 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002769 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002770 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002771 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002772 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002773
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002774 // We succeeded at evaluating this block!
2775 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002776 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002777 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002778 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002779 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002780
Chris Lattner1945d582010-12-07 04:33:29 +00002781 if (!CurInst->use_empty()) {
2782 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002783 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002784
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002785 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002786 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002787
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002788 // If we just processed an invoke, we finished evaluating the block.
2789 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2790 NextBB = II->getNormalDest();
2791 return true;
2792 }
2793
Chris Lattner79c11012005-09-26 04:44:35 +00002794 // Advance program counter.
2795 ++CurInst;
2796 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002797}
2798
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002799/// EvaluateFunction - Evaluate a call to function F, returning true if
2800/// successful, false if we can't evaluate it. ActualArgs contains the formal
2801/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002802bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2803 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002804 // Check to see if this function is already executing (recursion). If so,
2805 // bail out. TODO: we might want to accept limited recursion.
2806 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2807 return false;
2808
2809 CallStack.push_back(F);
2810
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002811 // Initialize arguments to the incoming values specified.
2812 unsigned ArgNo = 0;
2813 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2814 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002815 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002816
2817 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2818 // we can only evaluate any one basic block at most once. This set keeps
2819 // track of what we have executed so we can detect recursive cases etc.
2820 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2821
2822 // CurBB - The current basic block we're evaluating.
2823 BasicBlock *CurBB = F->begin();
2824
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002825 BasicBlock::iterator CurInst = CurBB->begin();
2826
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002827 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002828 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002829 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002830 return false;
2831
2832 if (NextBB == 0) {
2833 // Successfully running until there's no next block means that we found
2834 // the return. Fill it the return value and pop the call stack.
2835 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2836 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002837 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002838 CallStack.pop_back();
2839 return true;
2840 }
2841
2842 // Okay, we succeeded in evaluating this control flow. See if we have
2843 // executed the new block before. If so, we have a looping function,
2844 // which we cannot evaluate in reasonable time.
2845 if (!ExecutedBlocks.insert(NextBB))
2846 return false; // looped!
2847
2848 // Okay, we have never been in this block before. Check to see if there
2849 // are any PHI nodes. If so, evaluate them with information about where
2850 // we came from.
2851 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002852 for (CurInst = NextBB->begin();
2853 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002854 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002855
2856 // Advance to the next block.
2857 CurBB = NextBB;
2858 }
2859}
2860
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002861/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2862/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002863static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2864 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002865 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002866 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002867 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002868 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2869 SmallVector<Constant*, 0>());
Chris Lattner1945d582010-12-07 04:33:29 +00002870
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002871 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002872 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002873 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002874 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002875 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002876 for (DenseMap<Constant*, Constant*>::const_iterator I =
2877 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002878 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002879 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002880 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2881 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2882 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002883 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002884 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002885
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002886 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002887}
2888
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002889/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2890/// Return true if anything changed.
2891bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2892 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2893 bool MadeChange = false;
2894 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002895
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002896 // Loop over global ctors, optimizing them when we can.
2897 for (unsigned i = 0; i != Ctors.size(); ++i) {
2898 Function *F = Ctors[i];
2899 // Found a null terminator in the middle of the list, prune off the rest of
2900 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002901 if (F == 0) {
2902 if (i != Ctors.size()-1) {
2903 Ctors.resize(i+1);
2904 MadeChange = true;
2905 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002906 break;
2907 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002908
Chris Lattner79c11012005-09-26 04:44:35 +00002909 // We cannot simplify external ctor functions.
2910 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002911
Chris Lattner79c11012005-09-26 04:44:35 +00002912 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002913 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002914 Ctors.erase(Ctors.begin()+i);
2915 MadeChange = true;
2916 --i;
2917 ++NumCtorsEvaluated;
2918 continue;
2919 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002920 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002921
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002922 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002923
Chris Lattner7b550cc2009-11-06 04:27:31 +00002924 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002925 return true;
2926}
2927
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002928bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002929 bool Changed = false;
2930
Duncan Sands177d84e2009-01-07 20:01:06 +00002931 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002932 I != E;) {
2933 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002934 // Aliases without names cannot be referenced outside this module.
2935 if (!J->hasName() && !J->isDeclaration())
2936 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002937 // If the aliasee may change at link time, nothing can be done - bail out.
2938 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002939 continue;
2940
Duncan Sands4782b302009-02-15 09:56:08 +00002941 Constant *Aliasee = J->getAliasee();
2942 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002943 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002944 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2945
2946 // Make all users of the alias use the aliasee instead.
2947 if (!J->use_empty()) {
2948 J->replaceAllUsesWith(Aliasee);
2949 ++NumAliasesResolved;
2950 Changed = true;
2951 }
2952
Duncan Sands7a154cf2009-12-08 10:10:20 +00002953 // If the alias is externally visible, we may still be able to simplify it.
2954 if (!J->hasLocalLinkage()) {
2955 // If the aliasee has internal linkage, give it the name and linkage
2956 // of the alias, and delete the alias. This turns:
2957 // define internal ... @f(...)
2958 // @a = alias ... @f
2959 // into:
2960 // define ... @a(...)
2961 if (!Target->hasLocalLinkage())
2962 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002963
Duncan Sands7a154cf2009-12-08 10:10:20 +00002964 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002965 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002966 // and other attributes of the aliasee with those of the alias.
2967 if (!hasOneUse)
2968 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002969
Duncan Sands7a154cf2009-12-08 10:10:20 +00002970 // Give the aliasee the name, linkage and other attributes of the alias.
2971 Target->takeName(J);
2972 Target->setLinkage(J->getLinkage());
2973 Target->GlobalValue::copyAttributesFrom(J);
2974 }
Duncan Sands4782b302009-02-15 09:56:08 +00002975
2976 // Delete the alias.
2977 M.getAliasList().erase(J);
2978 ++NumAliasesRemoved;
2979 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002980 }
2981
2982 return Changed;
2983}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002984
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002985static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2986 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00002987 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002988
2989 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Anders Carlssona201c4c2011-03-20 17:59:11 +00002990
2991 if (!Fn)
2992 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002993
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002994 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00002995
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002996 // Checking that the function has the right return type, the right number of
2997 // parameters and that they all have pointer types should be enough.
2998 if (!FTy->getReturnType()->isIntegerTy() ||
2999 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003000 !FTy->getParamType(0)->isPointerTy() ||
3001 !FTy->getParamType(1)->isPointerTy() ||
3002 !FTy->getParamType(2)->isPointerTy())
3003 return 0;
3004
3005 return Fn;
3006}
3007
3008/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3009/// destructor and can therefore be eliminated.
3010/// Note that we assume that other optimization passes have already simplified
3011/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003012/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3013/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003014static bool cxxDtorIsEmpty(const Function &Fn,
3015 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003016 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003017 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003018 if (Fn.isDeclaration())
3019 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003020
3021 if (++Fn.begin() != Fn.end())
3022 return false;
3023
3024 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3025 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3026 I != E; ++I) {
3027 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003028 // Ignore debug intrinsics.
3029 if (isa<DbgInfoIntrinsic>(CI))
3030 continue;
3031
Anders Carlssona201c4c2011-03-20 17:59:11 +00003032 const Function *CalledFn = CI->getCalledFunction();
3033
3034 if (!CalledFn)
3035 return false;
3036
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003037 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3038
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003039 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003040 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003041 return false;
3042
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003043 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003044 return false;
3045 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003046 return true; // We're done.
3047 else if (I->mayHaveSideEffects())
3048 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003049 }
3050
3051 return false;
3052}
3053
3054bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3055 /// Itanium C++ ABI p3.3.5:
3056 ///
3057 /// After constructing a global (or local static) object, that will require
3058 /// destruction on exit, a termination function is registered as follows:
3059 ///
3060 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3061 ///
3062 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3063 /// call f(p) when DSO d is unloaded, before all such termination calls
3064 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003065 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003066
3067 // This pass will look for calls to __cxa_atexit where the function is trivial
3068 // and remove them.
3069 bool Changed = false;
3070
3071 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
3072 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003073 // We're only interested in calls. Theoretically, we could handle invoke
3074 // instructions as well, but neither llvm-gcc nor clang generate invokes
3075 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003076 CallInst *CI = dyn_cast<CallInst>(*I++);
3077 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003078 continue;
3079
Anders Carlssona201c4c2011-03-20 17:59:11 +00003080 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003081 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003082 if (!DtorFn)
3083 continue;
3084
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003085 SmallPtrSet<const Function *, 8> CalledFunctions;
3086 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003087 continue;
3088
3089 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003090 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3091 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003092
Anders Carlssona201c4c2011-03-20 17:59:11 +00003093 ++NumCXXDtorsRemoved;
3094
3095 Changed |= true;
3096 }
3097
3098 return Changed;
3099}
3100
Chris Lattner7a90b682004-10-07 04:16:33 +00003101bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003102 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003103
Nick Lewycky6a577f82012-02-12 01:13:18 +00003104 TD = getAnalysisIfAvailable<TargetData>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003105 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003106
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003107 // Try to find the llvm.globalctors list.
3108 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003109
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003110 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003111
Chris Lattner7a90b682004-10-07 04:16:33 +00003112 bool LocalChange = true;
3113 while (LocalChange) {
3114 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003115
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003116 // Delete functions that are trivially dead, ccc -> fastcc
3117 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003118
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003119 // Optimize global_ctors list.
3120 if (GlobalCtors)
3121 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003122
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003123 // Optimize non-address-taken globals.
3124 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003125
3126 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003127 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003128
3129 // Try to remove trivial global destructors.
3130 if (CXAAtExitFn)
3131 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3132
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003133 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003134 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003135
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003136 // TODO: Move all global ctors functions to the end of the module for code
3137 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003138
Chris Lattner079236d2004-02-25 21:34:36 +00003139 return Changed;
3140}