blob: acb723e1cc894bb83684f3469b3f00ecc5d4d306 [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 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000257 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000258 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000259 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000260 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000261 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000262 // PHI nodes we can check just like select or GEP instructions, but we
263 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000264 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000265 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000266 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000267 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000268 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000269 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
270 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000271 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000272 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000273 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000274 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000275 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
276 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
277 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000278 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000279 } else {
280 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000281 }
Gabor Greife6642672010-07-09 16:51:20 +0000282 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000283 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000284 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000285 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000286 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000287 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000288 GS.HasNonInstructionUser = true;
289 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000290 return true;
291 }
Gabor Greife6642672010-07-09 16:51:20 +0000292 }
Chris Lattner079236d2004-02-25 21:34:36 +0000293
294 return false;
295}
296
Chris Lattnere47ba742004-10-06 20:57:02 +0000297/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
298/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000299/// quick scan over the use list to clean up the easy and obvious cruft. This
300/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000301static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
302 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000303 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000304 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
305 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000306
Chris Lattner7a90b682004-10-07 04:16:33 +0000307 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000308 if (Init) {
309 // Replace the load with the initializer.
310 LI->replaceAllUsesWith(Init);
311 LI->eraseFromParent();
312 Changed = true;
313 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000314 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000315 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000316 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000317 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000318 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
319 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000320 Constant *SubInit = 0;
321 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000322 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000323 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000324 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000325 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000326 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000327 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000328 }
329
330 if (CE->use_empty()) {
331 CE->destroyConstant();
332 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000333 }
334 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000335 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
336 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
337 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000338 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000339 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000340 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000341 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000342 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000343 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000344 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000345 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000346
Chris Lattner031955d2004-10-10 16:43:46 +0000347 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000348 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000349 Changed = true;
350 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000351 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
352 if (MI->getRawDest() == V) {
353 MI->eraseFromParent();
354 Changed = true;
355 }
356
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000357 } else if (Constant *C = dyn_cast<Constant>(U)) {
358 // If we have a chain of dead constantexprs or other things dangling from
359 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000360 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000361 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000362 // This could have invalidated UI, start over from scratch.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000363 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000364 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000365 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000366 }
367 }
Chris Lattner031955d2004-10-10 16:43:46 +0000368 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000369}
370
Chris Lattner941db492008-01-14 02:09:12 +0000371/// isSafeSROAElementUse - Return true if the specified instruction is a safe
372/// user of a derived expression from a global that we want to SROA.
373static bool isSafeSROAElementUse(Value *V) {
374 // We might have a dead and dangling constant hanging off of here.
375 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000376 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000377
Chris Lattner941db492008-01-14 02:09:12 +0000378 Instruction *I = dyn_cast<Instruction>(V);
379 if (!I) return false;
380
381 // Loads are ok.
382 if (isa<LoadInst>(I)) return true;
383
384 // Stores *to* the pointer are ok.
385 if (StoreInst *SI = dyn_cast<StoreInst>(I))
386 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000387
Chris Lattner941db492008-01-14 02:09:12 +0000388 // Otherwise, it must be a GEP.
389 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
390 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000391
Chris Lattner941db492008-01-14 02:09:12 +0000392 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
393 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
394 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000395
Chris Lattner941db492008-01-14 02:09:12 +0000396 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
397 I != E; ++I)
398 if (!isSafeSROAElementUse(*I))
399 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000400 return true;
401}
402
Chris Lattner941db492008-01-14 02:09:12 +0000403
404/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
405/// Look at it and its uses and decide whether it is safe to SROA this global.
406///
407static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
408 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000409 if (!isa<GetElementPtrInst>(U) &&
410 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000411 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
412 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000413
Chris Lattner941db492008-01-14 02:09:12 +0000414 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
415 // don't like < 3 operand CE's, and we don't like non-constant integer
416 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
417 // value of C.
418 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
419 !cast<Constant>(U->getOperand(1))->isNullValue() ||
420 !isa<ConstantInt>(U->getOperand(2)))
421 return false;
422
423 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
424 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000425
Chris Lattner941db492008-01-14 02:09:12 +0000426 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000427 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000428 uint64_t NumElements = AT->getNumElements();
429 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000430
Chris Lattner941db492008-01-14 02:09:12 +0000431 // Check to make sure that index falls within the array. If not,
432 // something funny is going on, so we won't do the optimization.
433 //
434 if (Idx->getZExtValue() >= NumElements)
435 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000436
Chris Lattner941db492008-01-14 02:09:12 +0000437 // We cannot scalar repl this level of the array unless any array
438 // sub-indices are in-range constants. In particular, consider:
439 // A[0][i]. We cannot know that the user isn't doing invalid things like
440 // allowing i to index an out-of-range subscript that accesses A[1].
441 //
442 // Scalar replacing *just* the outer index of the array is probably not
443 // going to be a win anyway, so just give up.
444 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000445 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000446 ++GEPI) {
447 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000448 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000449 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000450 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000451 NumElements = SubVectorTy->getNumElements();
452 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000453 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000454 "Indexed GEP type is not array, vector, or struct!");
455 continue;
456 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000457
Chris Lattner941db492008-01-14 02:09:12 +0000458 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
459 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
460 return false;
461 }
462 }
463
464 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
465 if (!isSafeSROAElementUse(*I))
466 return false;
467 return true;
468}
469
470/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
471/// is safe for us to perform this transformation.
472///
473static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
474 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
475 UI != E; ++UI) {
476 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
477 return false;
478 }
479 return true;
480}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000481
Chris Lattner941db492008-01-14 02:09:12 +0000482
Chris Lattner670c8892004-10-08 17:32:09 +0000483/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
484/// variable. This opens the door for other optimizations by exposing the
485/// behavior of the program in a more fine-grained way. We have determined that
486/// this transformation is safe already. We return the first global variable we
487/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000488static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000489 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000490 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000491 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000492
Rafael Espindolabb46f522009-01-15 20:18:42 +0000493 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000494 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000495 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000496
Chris Lattner670c8892004-10-08 17:32:09 +0000497 std::vector<GlobalVariable*> NewGlobals;
498 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
499
Chris Lattner998182b2008-04-26 07:40:11 +0000500 // Get the alignment of the global, either explicit or target-specific.
501 unsigned StartAlignment = GV->getAlignment();
502 if (StartAlignment == 0)
503 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000504
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000505 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000506 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000507 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000508 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000509 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000510 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000511 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000512 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000513 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000514 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000515 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000516 Globals.insert(GV, NGV);
517 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000518
Chris Lattner998182b2008-04-26 07:40:11 +0000519 // Calculate the known alignment of the field. If the original aggregate
520 // had 256 byte alignment for example, something might depend on that:
521 // propagate info to each field.
522 uint64_t FieldOffset = Layout.getElementOffset(i);
523 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
524 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
525 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000526 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000527 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000528 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000529 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000530 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000531 else
Chris Lattner998182b2008-04-26 07:40:11 +0000532 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000533
Chris Lattner1f21ef12005-02-23 16:53:04 +0000534 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000535 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000536 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000537
Duncan Sands777d2302009-05-09 07:06:46 +0000538 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000539 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000540 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000541 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000542 assert(In && "Couldn't get element of initializer?");
543
Chris Lattner7b550cc2009-11-06 04:27:31 +0000544 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000545 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000546 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000547 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000548 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000549 Globals.insert(GV, NGV);
550 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000551
Chris Lattner998182b2008-04-26 07:40:11 +0000552 // Calculate the known alignment of the field. If the original aggregate
553 // had 256 byte alignment for example, something might depend on that:
554 // propagate info to each field.
555 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
556 if (NewAlign > EltAlign)
557 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000558 }
559 }
560
561 if (NewGlobals.empty())
562 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000563
David Greene3215b0e2010-01-05 01:28:05 +0000564 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000565
Chris Lattner7b550cc2009-11-06 04:27:31 +0000566 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000567
568 // Loop over all of the uses of the global, replacing the constantexpr geps,
569 // with smaller constantexpr geps or direct references.
570 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000571 User *GEP = GV->use_back();
572 assert(((isa<ConstantExpr>(GEP) &&
573 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
574 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000575
Chris Lattner670c8892004-10-08 17:32:09 +0000576 // Ignore the 1th operand, which has to be zero or else the program is quite
577 // broken (undefined). Get the 2nd operand, which is the structure or array
578 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000579 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000580 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
581
Chris Lattner30ba5692004-10-11 05:54:41 +0000582 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000583
584 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000585 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000586 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000587 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000588 Idxs.push_back(NullInt);
589 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
590 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000591 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000592 } else {
593 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000594 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000595 Idxs.push_back(NullInt);
596 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
597 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000598 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000599 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000600 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000601 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000602 GEP->replaceAllUsesWith(NewPtr);
603
604 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000605 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000606 else
607 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000608 }
609
Chris Lattnere40e2d12004-10-08 20:25:55 +0000610 // Delete the old global, now that it is dead.
611 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000612 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000613
614 // Loop over the new globals array deleting any globals that are obviously
615 // dead. This can arise due to scalarization of a structure or an array that
616 // has elements that are dead.
617 unsigned FirstGlobal = 0;
618 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
619 if (NewGlobals[i]->use_empty()) {
620 Globals.erase(NewGlobals[i]);
621 if (FirstGlobal == i) ++FirstGlobal;
622 }
623
624 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000625}
626
Chris Lattner9b34a612004-10-09 21:48:45 +0000627/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000628/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000629/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000630static bool AllUsesOfValueWillTrapIfNull(const Value *V,
631 SmallPtrSet<const PHINode*, 8> &PHIs) {
632 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000633 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000634 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000635
636 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000637 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000638 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000639 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000640 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000641 return false; // Storing the value.
642 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000643 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000644 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000645 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000646 return false; // Not calling the ptr
647 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000648 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000649 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000650 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000651 return false; // Not calling the ptr
652 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000653 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000654 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000655 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000656 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000657 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000658 // If we've already seen this phi node, ignore it, it has already been
659 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000660 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
661 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000662 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000663 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000664 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000665 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000666 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000667 return false;
668 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000669 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000670 return true;
671}
672
673/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000674/// from GV will trap if the loaded value is null. Note that this also permits
675/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000676static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
677 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000678 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000679 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000680
Gabor Greif6ce02b52010-04-06 19:24:18 +0000681 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
682 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000683 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000684 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000685 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000686 // Ignore stores to the global.
687 } else {
688 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000689 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000690 return false;
691 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000692 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000693 return true;
694}
695
Chris Lattner7b550cc2009-11-06 04:27:31 +0000696static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000697 bool Changed = false;
698 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
699 Instruction *I = cast<Instruction>(*UI++);
700 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
701 LI->setOperand(0, NewV);
702 Changed = true;
703 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
704 if (SI->getOperand(1) == V) {
705 SI->setOperand(1, NewV);
706 Changed = true;
707 }
708 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000709 CallSite CS(I);
710 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000711 // Calling through the pointer! Turn into a direct call, but be careful
712 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000713 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000714 Changed = true;
715 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000716 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
717 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000718 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000719 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000720 }
721
722 if (PassedAsArg) {
723 // Being passed as an argument also. Be careful to not invalidate UI!
724 UI = V->use_begin();
725 }
726 }
727 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
728 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000729 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000730 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000731 if (CI->use_empty()) {
732 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000733 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000734 }
735 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
736 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000737 SmallVector<Constant*, 8> Idxs;
738 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000739 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
740 i != e; ++i)
741 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000742 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000743 else
744 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000745 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000746 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000747 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000748 if (GEPI->use_empty()) {
749 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000750 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000751 }
752 }
753 }
754
755 return Changed;
756}
757
758
759/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
760/// value stored into it. If there are uses of the loaded value that would trap
761/// if the loaded value is dynamically null, then we know that they cannot be
762/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000763static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
764 TargetData *TD,
765 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000766 bool Changed = false;
767
Chris Lattner92c6bd22009-01-14 00:12:58 +0000768 // Keep track of whether we are able to remove all the uses of the global
769 // other than the store that defines it.
770 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000771
Chris Lattner708148e2004-10-10 23:14:11 +0000772 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000773 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
774 User *GlobalUser = *GUI++;
775 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000776 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000777 // If we were able to delete all uses of the loads
778 if (LI->use_empty()) {
779 LI->eraseFromParent();
780 Changed = true;
781 } else {
782 AllNonStoreUsesGone = false;
783 }
784 } else if (isa<StoreInst>(GlobalUser)) {
785 // Ignore the store that stores "LV" to the global.
786 assert(GlobalUser->getOperand(1) == GV &&
787 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000788 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000789 AllNonStoreUsesGone = false;
790
791 // If we get here we could have other crazy uses that are transitively
792 // loaded.
793 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000794 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
795 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000796 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000797 }
Chris Lattner708148e2004-10-10 23:14:11 +0000798
799 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000800 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000801 ++NumGlobUses;
802 }
803
Chris Lattner708148e2004-10-10 23:14:11 +0000804 // If we nuked all of the loads, then none of the stores are needed either,
805 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000806 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000807 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Nick Lewycky6a577f82012-02-12 01:13:18 +0000808 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
Chris Lattner708148e2004-10-10 23:14:11 +0000809 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000810 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000811 ++NumDeleted;
812 }
813 Changed = true;
814 }
815 return Changed;
816}
817
Chris Lattner30ba5692004-10-11 05:54:41 +0000818/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
819/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000820static void ConstantPropUsersOf(Value *V,
821 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000822 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
823 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +0000824 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000825 I->replaceAllUsesWith(NewC);
826
Chris Lattnerd514d822005-02-01 01:23:31 +0000827 // Advance UI to the next non-I use to avoid invalidating it!
828 // Instructions could multiply use V.
829 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000830 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000831 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000832 }
833}
834
835/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
836/// variable, and transforms the program as if it always contained the result of
837/// the specified malloc. Because it is always the result of the specified
838/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000839/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000840static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000841 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000842 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000843 ConstantInt *NElements,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000844 TargetData *TD,
845 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +0000846 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000847
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000848 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +0000849 if (NElements->getZExtValue() == 1)
850 GlobalType = AllocTy;
851 else
852 // If we have an array allocation, the global variable is of an array.
853 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000854
855 // Create the new global variable. The contents of the malloc'd memory is
856 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000857 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000858 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000859 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000860 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000861 GV->getName()+".body",
862 GV,
863 GV->isThreadLocal());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000864
Chris Lattnera6874652010-02-25 22:33:52 +0000865 // If there are bitcast users of the malloc (which is typical, usually we have
866 // a malloc + bitcast) then replace them with uses of the new global. Update
867 // other users to use the global as well.
868 BitCastInst *TheBC = 0;
869 while (!CI->use_empty()) {
870 Instruction *User = cast<Instruction>(CI->use_back());
871 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
872 if (BCI->getType() == NewGV->getType()) {
873 BCI->replaceAllUsesWith(NewGV);
874 BCI->eraseFromParent();
875 } else {
876 BCI->setOperand(0, NewGV);
877 }
878 } else {
879 if (TheBC == 0)
880 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
881 User->replaceUsesOfWith(CI, TheBC);
882 }
883 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000884
Victor Hernandez83d63912009-09-18 22:35:49 +0000885 Constant *RepValue = NewGV;
886 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000887 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000888 GV->getType()->getElementType());
889
890 // If there is a comparison against null, we will insert a global bool to
891 // keep track of whether the global was initialized yet or not.
892 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000893 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000894 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000895 ConstantInt::getFalse(GV->getContext()),
896 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000897 bool InitBoolUsed = false;
898
899 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000900 while (!GV->use_empty()) {
901 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000902 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000903 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
904 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000905 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000906 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000907 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000908
Chris Lattnera6874652010-02-25 22:33:52 +0000909 LoadInst *LI = cast<LoadInst>(GV->use_back());
910 while (!LI->use_empty()) {
911 Use &LoadUse = LI->use_begin().getUse();
912 if (!isa<ICmpInst>(LoadUse.getUser())) {
913 LoadUse = RepValue;
914 continue;
915 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000916
Chris Lattnera6874652010-02-25 22:33:52 +0000917 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
918 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000919 // Sink the load to where the compare was, if atomic rules allow us to.
920 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
921 LI->getOrdering(), LI->getSynchScope(),
922 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +0000923 InitBoolUsed = true;
924 switch (ICI->getPredicate()) {
925 default: llvm_unreachable("Unknown ICmp Predicate!");
926 case ICmpInst::ICMP_ULT:
927 case ICmpInst::ICMP_SLT: // X < null -> always false
928 LV = ConstantInt::getFalse(GV->getContext());
929 break;
930 case ICmpInst::ICMP_ULE:
931 case ICmpInst::ICMP_SLE:
932 case ICmpInst::ICMP_EQ:
933 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
934 break;
935 case ICmpInst::ICMP_NE:
936 case ICmpInst::ICMP_UGE:
937 case ICmpInst::ICMP_SGE:
938 case ICmpInst::ICMP_UGT:
939 case ICmpInst::ICMP_SGT:
940 break; // no change.
941 }
942 ICI->replaceAllUsesWith(LV);
943 ICI->eraseFromParent();
944 }
945 LI->eraseFromParent();
946 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000947
948 // If the initialization boolean was used, insert it, otherwise delete it.
949 if (!InitBoolUsed) {
950 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000951 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000952 delete InitBool;
953 } else
954 GV->getParent()->getGlobalList().insert(GV, InitBool);
955
Chris Lattnera6874652010-02-25 22:33:52 +0000956 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000957 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000958 CI->eraseFromParent();
959
960 // To further other optimizations, loop over all users of NewGV and try to
961 // constant prop them. This will promote GEP instructions with constant
962 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000963 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000964 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +0000965 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000966
967 return NewGV;
968}
969
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000970/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
971/// to make sure that there are no complex uses of V. We permit simple things
972/// like dereferencing the pointer, but not storing through the address, unless
973/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000974static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
975 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000976 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000977 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000978 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000979 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000980
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000981 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
982 continue; // Fine, ignore.
983 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000984
Gabor Greif0b520db2010-04-06 18:58:22 +0000985 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000986 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
987 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000988 continue; // Otherwise, storing through it, or storing into GV... fine.
989 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000990
Chris Lattnera2fb2342010-04-10 18:19:22 +0000991 // Must index into the array and into the struct.
992 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000993 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000994 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000995 continue;
996 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000997
Gabor Greif0b520db2010-04-06 18:58:22 +0000998 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000999 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1000 // cycles.
1001 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001002 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1003 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001004 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001005 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001006
Gabor Greif0b520db2010-04-06 18:58:22 +00001007 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001008 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1009 return false;
1010 continue;
1011 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001012
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001013 return false;
1014 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001015 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001016}
1017
Chris Lattner86395032006-09-30 23:32:09 +00001018/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1019/// somewhere. Transform all uses of the allocation into loads from the
1020/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001021/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001022/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001023static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001024 GlobalVariable *GV) {
1025 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001026 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1027 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001028 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1029 // If this is the store of the allocation into the global, remove it.
1030 if (SI->getOperand(1) == GV) {
1031 SI->eraseFromParent();
1032 continue;
1033 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001034 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1035 // Insert the load in the corresponding predecessor, not right before the
1036 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001037 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001038 } else if (isa<BitCastInst>(U)) {
1039 // Must be bitcast between the malloc and store to initialize the global.
1040 ReplaceUsesOfMallocWithGlobal(U, GV);
1041 U->eraseFromParent();
1042 continue;
1043 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1044 // If this is a "GEP bitcast" and the user is a store to the global, then
1045 // just process it as a bitcast.
1046 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1047 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1048 if (SI->getOperand(1) == GV) {
1049 // Must be bitcast GEP between the malloc and store to initialize
1050 // the global.
1051 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1052 GEPI->eraseFromParent();
1053 continue;
1054 }
Chris Lattner86395032006-09-30 23:32:09 +00001055 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001056
Chris Lattner86395032006-09-30 23:32:09 +00001057 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001058 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001059 U->replaceUsesOfWith(Alloc, NL);
1060 }
1061}
1062
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001063/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1064/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1065/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001066static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001067 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1068 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001069 // We permit two users of the load: setcc comparing against the null
1070 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001071 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1072 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001073 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001074
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001075 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001076 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001077 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1078 return false;
1079 continue;
1080 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001081
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001082 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001083 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001084 // Must index into the array and into the struct.
1085 if (GEPI->getNumOperands() < 3)
1086 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001087
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001088 // Otherwise the GEP is ok.
1089 continue;
1090 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001091
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001092 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001093 if (!LoadUsingPHIsPerLoad.insert(PN))
1094 // This means some phi nodes are dependent on each other.
1095 // Avoid infinite looping!
1096 return false;
1097 if (!LoadUsingPHIs.insert(PN))
1098 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001099 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001100
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001101 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001102 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1103 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001104 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001105
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001106 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001107 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001108
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001109 // Otherwise we don't know what this is, not ok.
1110 return false;
1111 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001112
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001113 return true;
1114}
1115
1116
1117/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1118/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001119static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001120 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001121 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1122 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001123 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1124 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001125 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001126 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1127 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001128 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001129 LoadUsingPHIsPerLoad.clear();
1130 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001131
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001132 // If we reach here, we know that all uses of the loads and transitive uses
1133 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001134 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001135 // Check to verify that all operands of the PHIs are either PHIS that can be
1136 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001137 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1138 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001139 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001140 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1141 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001142
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001143 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001144 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001145
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001146 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001147 // One of the PHIs in our set is (optimistically) ok.
1148 if (LoadUsingPHIs.count(InPN))
1149 continue;
1150 return false;
1151 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001152
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001153 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001154 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001155 if (LI->getOperand(0) == GV)
1156 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001157
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001158 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001159
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001160 // Anything else is rejected.
1161 return false;
1162 }
1163 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001164
Chris Lattner86395032006-09-30 23:32:09 +00001165 return true;
1166}
1167
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001168static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1169 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001170 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001171 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001172
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001173 if (FieldNo >= FieldVals.size())
1174 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001175
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001176 // If we already have this value, just reuse the previously scalarized
1177 // version.
1178 if (Value *FieldVal = FieldVals[FieldNo])
1179 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001180
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001181 // Depending on what instruction this is, we have several cases.
1182 Value *Result;
1183 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1184 // This is a scalarized version of the load from the global. Just create
1185 // a new Load of the scalarized global.
1186 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1187 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001188 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001189 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001190 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1191 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1192 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001193 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001194 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001195
Jay Foadd8b4fb42011-03-30 11:19:20 +00001196 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001197 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001198 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001199 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001200 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001201 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1202 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001203 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001204 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001205
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001206 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001207}
1208
Chris Lattner330245e2007-09-13 17:29:05 +00001209/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1210/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001211static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001212 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001213 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001214 // If this is a comparison against null, handle it.
1215 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1216 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1217 // If we have a setcc of the loaded pointer, we can use a setcc of any
1218 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001219 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001220 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001221
Owen Anderson333c4002009-07-09 23:48:35 +00001222 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001223 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001224 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001225 SCI->replaceAllUsesWith(New);
1226 SCI->eraseFromParent();
1227 return;
1228 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001229
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001230 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001231 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1232 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1233 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001234
Chris Lattnera637a8b2007-09-13 18:00:31 +00001235 // Load the pointer for this field.
1236 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001237 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001238 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001239
Chris Lattnera637a8b2007-09-13 18:00:31 +00001240 // Create the new GEP idx vector.
1241 SmallVector<Value*, 8> GEPIdx;
1242 GEPIdx.push_back(GEPI->getOperand(1));
1243 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001244
Jay Foada9203102011-07-25 09:48:08 +00001245 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001246 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001247 GEPI->replaceAllUsesWith(NGEPI);
1248 GEPI->eraseFromParent();
1249 return;
1250 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001251
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001252 // Recursively transform the users of PHI nodes. This will lazily create the
1253 // PHIs that are needed for individual elements. Keep track of what PHIs we
1254 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1255 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1256 // already been seen first by another load, so its uses have already been
1257 // processed.
1258 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001259 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1260 std::vector<Value*>())).second)
1261 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001262
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001263 // If this is the first time we've seen this PHI, recursively process all
1264 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001265 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1266 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001267 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001268 }
Chris Lattner330245e2007-09-13 17:29:05 +00001269}
1270
Chris Lattner86395032006-09-30 23:32:09 +00001271/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1272/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1273/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001274/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001275static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001276 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001277 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001278 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001279 UI != E; ) {
1280 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001281 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001282 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001283
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001284 if (Load->use_empty()) {
1285 Load->eraseFromParent();
1286 InsertedScalarizedValues.erase(Load);
1287 }
Chris Lattner86395032006-09-30 23:32:09 +00001288}
1289
Victor Hernandez83d63912009-09-18 22:35:49 +00001290/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1291/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001292static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Nick Lewyckybc384a12012-02-05 19:48:37 +00001293 Value *NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001294 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Nick Lewyckybc384a12012-02-05 19:48:37 +00001295 Type *MAT = getMallocAllocatedType(CI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001296 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001297
1298 // There is guaranteed to be at least one use of the malloc (storing
1299 // it into GV). If there are other uses, change them to be uses of
1300 // the global to simplify later code. This also deletes the store
1301 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001302 ReplaceUsesOfMallocWithGlobal(CI, GV);
1303
Victor Hernandez83d63912009-09-18 22:35:49 +00001304 // Okay, at this point, there are no users of the malloc. Insert N
1305 // new mallocs at the same place as CI, and N globals.
1306 std::vector<Value*> FieldGlobals;
1307 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001308
Victor Hernandez83d63912009-09-18 22:35:49 +00001309 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001310 Type *FieldTy = STy->getElementType(FieldNo);
1311 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001312
Victor Hernandez83d63912009-09-18 22:35:49 +00001313 GlobalVariable *NGV =
1314 new GlobalVariable(*GV->getParent(),
1315 PFieldTy, false, GlobalValue::InternalLinkage,
1316 Constant::getNullValue(PFieldTy),
1317 GV->getName() + ".f" + Twine(FieldNo), GV,
1318 GV->isThreadLocal());
1319 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001320
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001321 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001322 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001323 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001324 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001325 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1326 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001327 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001328 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001329 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001330 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001331 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001332
Victor Hernandez83d63912009-09-18 22:35:49 +00001333 // The tricky aspect of this transformation is handling the case when malloc
1334 // fails. In the original code, malloc failing would set the result pointer
1335 // of malloc to null. In this case, some mallocs could succeed and others
1336 // could fail. As such, we emit code that looks like this:
1337 // F0 = malloc(field0)
1338 // F1 = malloc(field1)
1339 // F2 = malloc(field2)
1340 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1341 // if (F0) { free(F0); F0 = 0; }
1342 // if (F1) { free(F1); F1 = 0; }
1343 // if (F2) { free(F2); F2 = 0; }
1344 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001345 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001346 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1347 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001348 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001349 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001350 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1351 Constant::getNullValue(FieldMallocs[i]->getType()),
1352 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001353 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001354 }
1355
1356 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001357 BasicBlock *OrigBB = CI->getParent();
1358 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001359
Victor Hernandez83d63912009-09-18 22:35:49 +00001360 // Create the block to check the first condition. Put all these blocks at the
1361 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001362 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1363 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001364 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001365
Victor Hernandez83d63912009-09-18 22:35:49 +00001366 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1367 // branch on RunningOr.
1368 OrigBB->getTerminator()->eraseFromParent();
1369 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001370
Victor Hernandez83d63912009-09-18 22:35:49 +00001371 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1372 // pointer, because some may be null while others are not.
1373 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1374 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001375 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001376 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001377 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001378 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001379 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001380 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001381 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1382 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001383
1384 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001385 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001386 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1387 FreeBlock);
1388 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001389
Victor Hernandez83d63912009-09-18 22:35:49 +00001390 NullPtrBlock = NextBlock;
1391 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001392
Victor Hernandez83d63912009-09-18 22:35:49 +00001393 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001394
1395 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001396 CI->eraseFromParent();
1397
1398 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1399 /// update all uses of the load, keep track of what scalarized loads are
1400 /// inserted for a given load.
1401 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1402 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001403
Victor Hernandez83d63912009-09-18 22:35:49 +00001404 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001405
Victor Hernandez83d63912009-09-18 22:35:49 +00001406 // Okay, the malloc site is completely handled. All of the uses of GV are now
1407 // loads, and all uses of those loads are simple. Rewrite them to use loads
1408 // of the per-field globals instead.
1409 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1410 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001411
Victor Hernandez83d63912009-09-18 22:35:49 +00001412 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001413 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001414 continue;
1415 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001416
Victor Hernandez83d63912009-09-18 22:35:49 +00001417 // Must be a store of null.
1418 StoreInst *SI = cast<StoreInst>(User);
1419 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1420 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001421
Victor Hernandez83d63912009-09-18 22:35:49 +00001422 // Insert a store of null into each global.
1423 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001424 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001425 Constant *Null = Constant::getNullValue(PT->getElementType());
1426 new StoreInst(Null, FieldGlobals[i], SI);
1427 }
1428 // Erase the original store.
1429 SI->eraseFromParent();
1430 }
1431
1432 // While we have PHIs that are interesting to rewrite, do it.
1433 while (!PHIsToRewrite.empty()) {
1434 PHINode *PN = PHIsToRewrite.back().first;
1435 unsigned FieldNo = PHIsToRewrite.back().second;
1436 PHIsToRewrite.pop_back();
1437 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1438 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1439
1440 // Add all the incoming values. This can materialize more phis.
1441 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1442 Value *InVal = PN->getIncomingValue(i);
1443 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001444 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001445 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1446 }
1447 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001448
Victor Hernandez83d63912009-09-18 22:35:49 +00001449 // Drop all inter-phi links and any loads that made it this far.
1450 for (DenseMap<Value*, std::vector<Value*> >::iterator
1451 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1452 I != E; ++I) {
1453 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1454 PN->dropAllReferences();
1455 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1456 LI->dropAllReferences();
1457 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001458
Victor Hernandez83d63912009-09-18 22:35:49 +00001459 // Delete all the phis and loads now that inter-references are dead.
1460 for (DenseMap<Value*, std::vector<Value*> >::iterator
1461 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1462 I != E; ++I) {
1463 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1464 PN->eraseFromParent();
1465 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1466 LI->eraseFromParent();
1467 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001468
Victor Hernandez83d63912009-09-18 22:35:49 +00001469 // The old global is now dead, remove it.
1470 GV->eraseFromParent();
1471
1472 ++NumHeapSRA;
1473 return cast<GlobalVariable>(FieldGlobals[0]);
1474}
1475
Chris Lattnere61d0a62008-12-15 21:02:25 +00001476/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1477/// pointer global variable with a single value stored it that is a malloc or
1478/// cast of malloc.
1479static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001480 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001481 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001482 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001483 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001484 TargetData *TD,
1485 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001486 if (!TD)
1487 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001488
Victor Hernandez83d63912009-09-18 22:35:49 +00001489 // If this is a malloc of an abstract type, don't touch it.
1490 if (!AllocTy->isSized())
1491 return false;
1492
1493 // We can't optimize this global unless all uses of it are *known* to be
1494 // of the malloc value, not of the null initializer value (consider a use
1495 // that compares the global's value against zero to see if the malloc has
1496 // been reached). To do this, we check to see if all uses of the global
1497 // would trap if the global were null: this proves that they must all
1498 // happen after the malloc.
1499 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1500 return false;
1501
1502 // We can't optimize this if the malloc itself is used in a complex way,
1503 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001504 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001505 // GEP'd. These are all things we could transform to using the global
1506 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001507 SmallPtrSet<const PHINode*, 8> PHIs;
1508 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1509 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001510
1511 // If we have a global that is only initialized with a fixed size malloc,
1512 // transform the program to use global memory instead of malloc'd memory.
1513 // This eliminates dynamic allocation, avoids an indirection accessing the
1514 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001515 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001516 Value *NElems = getMallocArraySize(CI, TD, true);
1517 if (!NElems)
1518 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001519
Evan Cheng86cd4452010-04-14 20:52:55 +00001520 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1521 // Restrict this transformation to only working on small allocations
1522 // (2048 bytes currently), as we don't want to introduce a 16M global or
1523 // something.
1524 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001525 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001526 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001527 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001528
Evan Cheng86cd4452010-04-14 20:52:55 +00001529 // If the allocation is an array of structures, consider transforming this
1530 // into multiple malloc'd arrays, one for each field. This is basically
1531 // SRoA for malloc'd memory.
1532
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001533 if (Ordering != NotAtomic)
1534 return false;
1535
Evan Cheng86cd4452010-04-14 20:52:55 +00001536 // If this is an allocation of a fixed size array of structs, analyze as a
1537 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001538 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001539 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001540 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001541
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001542 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001543 if (!AllocSTy)
1544 return false;
1545
1546 // This the structure has an unreasonable number of fields, leave it
1547 // alone.
1548 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1549 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1550
1551 // If this is a fixed size array, transform the Malloc to be an alloc of
1552 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001553 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1554 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001555 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1556 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1557 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1558 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1559 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001560 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001561 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1562 CI->replaceAllUsesWith(Cast);
1563 CI->eraseFromParent();
1564 CI = dyn_cast<BitCastInst>(Malloc) ?
1565 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1566 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001567
Nick Lewyckybc384a12012-02-05 19:48:37 +00001568 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true), TD);
Evan Cheng86cd4452010-04-14 20:52:55 +00001569 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001570 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001571
Victor Hernandez83d63912009-09-18 22:35:49 +00001572 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001573}
Victor Hernandez83d63912009-09-18 22:35:49 +00001574
Chris Lattner9b34a612004-10-09 21:48:45 +00001575// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1576// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001577static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001578 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001579 Module::global_iterator &GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001580 TargetData *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001581 // Ignore no-op GEPs and bitcasts.
1582 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001583
Chris Lattner708148e2004-10-10 23:14:11 +00001584 // If we are dealing with a pointer global that is initialized to null and
1585 // only has one (non-null) value stored into it, then we can optimize any
1586 // users of the loaded value (often calls and loads) that would trap if the
1587 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001588 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001589 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001590 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1591 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001592 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001593
Chris Lattner708148e2004-10-10 23:14:11 +00001594 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001595 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001596 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001597 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Nick Lewyckybc384a12012-02-05 19:48:37 +00001598 Type *MallocType = getMallocAllocatedType(CI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001599 if (MallocType &&
1600 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1601 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001602 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001603 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001604 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001605
Chris Lattner9b34a612004-10-09 21:48:45 +00001606 return false;
1607}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001608
Chris Lattner58e44f42008-01-14 01:17:44 +00001609/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1610/// two values ever stored into GV are its initializer and OtherVal. See if we
1611/// can shrink the global into a boolean and select between the two values
1612/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001613static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001614 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001615
Chris Lattner58e44f42008-01-14 01:17:44 +00001616 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001617 // an FP value, pointer or vector, don't do this optimization because a select
1618 // between them is very expensive and unlikely to lead to later
1619 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1620 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001621 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001622 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001623 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001624 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001625
Chris Lattner58e44f42008-01-14 01:17:44 +00001626 // Walk the use list of the global seeing if all the uses are load or store.
1627 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001628 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1629 User *U = *I;
1630 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001631 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001632 }
1633
David Greene3215b0e2010-01-05 01:28:05 +00001634 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001635
Chris Lattner96a86b22004-12-12 05:53:50 +00001636 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001637 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1638 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001639 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001640 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001641 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001642 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001643 GV->getParent()->getGlobalList().insert(GV, NewGV);
1644
1645 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001646 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001647 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001648
1649 // If initialized to zero and storing one into the global, we can use a cast
1650 // instead of a select to synthesize the desired value.
1651 bool IsOneZero = false;
1652 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001653 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001654
1655 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001656 Instruction *UI = cast<Instruction>(GV->use_back());
1657 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001658 // Change the store into a boolean store.
1659 bool StoringOther = SI->getOperand(0) == OtherVal;
1660 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001661 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001662 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001663 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1664 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001665 else {
1666 // Otherwise, we are storing a previously loaded copy. To do this,
1667 // change the copy from copying the original value to just copying the
1668 // bool.
1669 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1670
Gabor Greif9e4f2432010-06-24 14:42:01 +00001671 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001672 // select instruction. If not, it will be a load of the original
1673 // global.
1674 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1675 assert(LI->getOperand(0) == GV && "Not a copy!");
1676 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001677 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1678 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001679 } else {
1680 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1681 "This is not a form that we understand!");
1682 StoreVal = StoredVal->getOperand(0);
1683 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1684 }
1685 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001686 new StoreInst(StoreVal, NewGV, false, 0,
1687 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001688 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001689 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001690 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001691 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1692 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001693 Value *NSI;
1694 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001695 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001696 else
Gabor Greif051a9502008-04-06 20:25:17 +00001697 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001698 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001699 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001700 }
1701 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001702 }
1703
1704 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001705 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001706}
1707
1708
Nick Lewyckydb292a62012-02-12 00:52:26 +00001709/// ProcessGlobal - Analyze the specified global variable and optimize it if
1710/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001711bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1712 Module::global_iterator &GVI) {
1713 if (!GV->hasLocalLinkage())
1714 return false;
1715
1716 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001717 GV->removeDeadConstantUsers();
1718
1719 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001720 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001721 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001722 ++NumDeleted;
1723 return true;
1724 }
1725
Rafael Espindolac4440e32011-01-19 16:32:21 +00001726 SmallPtrSet<const PHINode*, 16> PHIUsers;
1727 GlobalStatus GS;
1728
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001729 if (AnalyzeGlobal(GV, GS, PHIUsers))
1730 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001731
Rafael Espindolac4440e32011-01-19 16:32:21 +00001732 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1733 GV->setUnnamedAddr(true);
1734 NumUnnamed++;
1735 }
1736
1737 if (GV->isConstant() || !GV->hasInitializer())
1738 return false;
1739
1740 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1741}
1742
1743/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1744/// it if possible. If we make a change, return true.
1745bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1746 Module::global_iterator &GVI,
Nick Lewyckydb292a62012-02-12 00:52:26 +00001747 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001748 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001749 // If this is a first class global and has only one accessing function
1750 // and this function is main (which we know is not recursive we can make
1751 // this global a local variable) we replace the global with a local alloca
1752 // in this function.
1753 //
1754 // NOTE: It doesn't make sense to promote non single-value types since we
1755 // are just replacing static memory to stack memory.
1756 //
1757 // If the global is in different address space, don't bring it to stack.
1758 if (!GS.HasMultipleAccessingFunctions &&
1759 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1760 GV->getType()->getElementType()->isSingleValueType() &&
1761 GS.AccessingFunction->getName() == "main" &&
1762 GS.AccessingFunction->hasExternalLinkage() &&
1763 GV->getType()->getAddressSpace() == 0) {
1764 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
Nick Lewyckybc384a12012-02-05 19:48:37 +00001765 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001766 ->getEntryBlock().begin());
Nick Lewyckybc384a12012-02-05 19:48:37 +00001767 Type *ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001768 // FIXME: Pass Global's alignment when globals have alignment
Nick Lewyckybc384a12012-02-05 19:48:37 +00001769 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001770 if (!isa<UndefValue>(GV->getInitializer()))
1771 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001772
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001773 GV->replaceAllUsesWith(Alloca);
1774 GV->eraseFromParent();
1775 ++NumLocalized;
1776 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001777 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001778
1779 // If the global is never loaded (but may be stored to), it is dead.
1780 // Delete it now.
1781 if (!GS.isLoaded) {
1782 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1783
1784 // Delete any stores we can find to the global. We may not be able to
1785 // make it completely dead though.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001786 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1787 TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001788
1789 // If the global is dead now, delete it.
1790 if (GV->use_empty()) {
1791 GV->eraseFromParent();
1792 ++NumDeleted;
1793 Changed = true;
1794 }
1795 return Changed;
1796
1797 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1798 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1799 GV->setConstant(true);
1800
1801 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001802 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001803
1804 // If the global is dead now, just nuke it.
1805 if (GV->use_empty()) {
1806 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1807 << "all users and delete global!\n");
1808 GV->eraseFromParent();
1809 ++NumDeleted;
1810 }
1811
1812 ++NumMarked;
1813 return true;
1814 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1815 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1816 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1817 GVI = FirstNewGV; // Don't skip the newly produced globals!
1818 return true;
1819 }
1820 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1821 // If the initial value for the global was an undef value, and if only
1822 // one other value was stored into it, we can just change the
1823 // initializer to be the stored value, then delete all stores to the
1824 // global. This allows us to mark it constant.
1825 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1826 if (isa<UndefValue>(GV->getInitializer())) {
1827 // Change the initial value here.
1828 GV->setInitializer(SOVConstant);
1829
1830 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001831 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001832
1833 if (GV->use_empty()) {
1834 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1835 << "simplify all users and delete global!\n");
1836 GV->eraseFromParent();
1837 ++NumDeleted;
1838 } else {
1839 GVI = GV;
1840 }
1841 ++NumSubstitute;
1842 return true;
1843 }
1844
1845 // Try to optimize globals based on the knowledge that only one value
1846 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001847 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001848 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001849 return true;
1850
1851 // Otherwise, if the global was not a boolean, we can shrink it to be a
1852 // boolean.
1853 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1854 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1855 ++NumShrunkToBool;
1856 return true;
1857 }
1858 }
1859
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001860 return false;
1861}
1862
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001863/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1864/// function, changing them to FastCC.
1865static void ChangeCalleesToFastCall(Function *F) {
1866 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001867 CallSite User(cast<Instruction>(*UI));
1868 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001869 }
1870}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001871
Devang Patel05988662008-09-25 21:00:45 +00001872static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001873 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001874 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001875 continue;
1876
Duncan Sands548448a2008-02-18 17:32:13 +00001877 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001878 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001879 }
1880
1881 return Attrs;
1882}
1883
1884static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001885 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001886 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001887 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001888 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001889 }
1890}
1891
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001892bool GlobalOpt::OptimizeFunctions(Module &M) {
1893 bool Changed = false;
1894 // Optimize functions.
1895 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1896 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001897 // Functions without names cannot be referenced outside this module.
1898 if (!F->hasName() && !F->isDeclaration())
1899 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001900 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00001901 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001902 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001903 Changed = true;
1904 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001905 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001906 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001907 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001908 // If this function has C calling conventions, is not a varargs
1909 // function, and is only called directly, promote it to use the Fast
1910 // calling convention.
1911 F->setCallingConv(CallingConv::Fast);
1912 ChangeCalleesToFastCall(F);
1913 ++NumFastCallFns;
1914 Changed = true;
1915 }
1916
Devang Patel05988662008-09-25 21:00:45 +00001917 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001918 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001919 // The function is not used by a trampoline intrinsic, so it is safe
1920 // to remove the 'nest' attribute.
1921 RemoveNestAttribute(F);
1922 ++NumNestRemoved;
1923 Changed = true;
1924 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001925 }
1926 }
1927 return Changed;
1928}
1929
1930bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1931 bool Changed = false;
1932 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1933 GVI != E; ) {
1934 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001935 // Global variables without names cannot be referenced outside this module.
1936 if (!GV->hasName() && !GV->isDeclaration())
1937 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001938 // Simplify the initializer.
1939 if (GV->hasInitializer())
1940 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00001941 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001942 if (New && New != CE)
1943 GV->setInitializer(New);
1944 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001945
1946 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001947 }
1948 return Changed;
1949}
1950
Nick Lewycky2c44a802011-04-08 07:30:21 +00001951/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001952/// initializers have an init priority of 65535.
1953GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001954 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1955 if (GV == 0) return 0;
1956
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001957 // Verify that the initializer is simple enough for us to handle. We are
1958 // only allowed to optimize the initializer if it is unique.
1959 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001960
1961 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1962 return GV;
1963 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00001964
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001965 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001966 if (isa<ConstantAggregateZero>(*i))
1967 continue;
1968 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001969 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1970 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001971
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001972 // Must have a function or null ptr.
1973 if (!isa<Function>(CS->getOperand(1)))
1974 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001975
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001976 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001977 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1978 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001979 return 0;
1980 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001981
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001982 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001983}
1984
Chris Lattnerdb973e62005-09-26 02:31:18 +00001985/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1986/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001987static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001988 if (GV->getInitializer()->isNullValue())
1989 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001990 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1991 std::vector<Function*> Result;
1992 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001993 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1994 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001995 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1996 }
1997 return Result;
1998}
1999
Chris Lattnerdb973e62005-09-26 02:31:18 +00002000/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2001/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002002static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002003 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002004 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002005 Constant *CSVals[2];
2006 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2007 CSVals[1] = 0;
2008
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002009 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002010 cast <StructType>(
2011 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002012
Chris Lattnerdb973e62005-09-26 02:31:18 +00002013 // Create the new init list.
2014 std::vector<Constant*> CAList;
2015 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002016 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002017 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002018 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002019 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002020 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002021 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002022 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002023 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002024 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002025 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002026 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002027 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002028
Chris Lattnerdb973e62005-09-26 02:31:18 +00002029 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002030 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002031 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002032
Chris Lattnerdb973e62005-09-26 02:31:18 +00002033 // If we didn't change the number of elements, don't create a new GV.
2034 if (CA->getType() == GCL->getInitializer()->getType()) {
2035 GCL->setInitializer(CA);
2036 return GCL;
2037 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002038
Chris Lattnerdb973e62005-09-26 02:31:18 +00002039 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002040 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002041 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002042 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002043 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002044 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002045
Chris Lattnerdb973e62005-09-26 02:31:18 +00002046 // Nuke the old list, replacing any uses with the new one.
2047 if (!GCL->use_empty()) {
2048 Constant *V = NGV;
2049 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002050 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002051 GCL->replaceAllUsesWith(V);
2052 }
2053 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002054
Chris Lattnerdb973e62005-09-26 02:31:18 +00002055 if (Ctors.size())
2056 return NGV;
2057 else
2058 return 0;
2059}
Chris Lattner79c11012005-09-26 04:44:35 +00002060
2061
Chris Lattner1945d582010-12-07 04:33:29 +00002062static inline bool
2063isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002064 SmallPtrSet<Constant*, 8> &SimpleConstants,
2065 const TargetData *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002066
2067
2068/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2069/// handled by the code generator. We don't want to generate something like:
2070/// void *X = &X/42;
2071/// because the code generator doesn't have a relocation that can handle that.
2072///
2073/// This function should be called if C was not found (but just got inserted)
2074/// in SimpleConstants to avoid having to rescan the same constants all the
2075/// time.
2076static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002077 SmallPtrSet<Constant*, 8> &SimpleConstants,
2078 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002079 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2080 // all supported.
2081 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2082 isa<GlobalValue>(C))
2083 return true;
2084
2085 // Aggregate values are safe if all their elements are.
2086 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2087 isa<ConstantVector>(C)) {
2088 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2089 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002090 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002091 return false;
2092 }
2093 return true;
2094 }
2095
2096 // We don't know exactly what relocations are allowed in constant expressions,
2097 // so we allow &global+constantoffset, which is safe and uniformly supported
2098 // across targets.
2099 ConstantExpr *CE = cast<ConstantExpr>(C);
2100 switch (CE->getOpcode()) {
2101 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002102 // Bitcast is fine if the casted value is fine.
2103 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2104
Chris Lattner1945d582010-12-07 04:33:29 +00002105 case Instruction::IntToPtr:
2106 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002107 // int <=> ptr is fine if the int type is the same size as the
2108 // pointer type.
2109 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2110 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2111 return false;
2112 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002113
2114 // GEP is fine if it is simple + constant offset.
2115 case Instruction::GetElementPtr:
2116 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2117 if (!isa<ConstantInt>(CE->getOperand(i)))
2118 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002119 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002120
2121 case Instruction::Add:
2122 // We allow simple+cst.
2123 if (!isa<ConstantInt>(CE->getOperand(1)))
2124 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002125 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002126 }
2127 return false;
2128}
2129
2130static inline bool
2131isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002132 SmallPtrSet<Constant*, 8> &SimpleConstants,
2133 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002134 // If we already checked this constant, we win.
2135 if (!SimpleConstants.insert(C)) return true;
2136 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002137 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002138}
2139
2140
Chris Lattner79c11012005-09-26 04:44:35 +00002141/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002142/// enough for us to understand. In particular, if it is a cast to anything
2143/// other than from one pointer type to another pointer type, we punt.
2144/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002145/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002146static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002147 // Conservatively, avoid aggregate types. This is because we don't
2148 // want to worry about them partially overlapping other stores.
2149 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2150 return false;
2151
Dan Gohmanfd54a892009-09-07 22:31:26 +00002152 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002153 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002154 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002155 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002156
Owen Andersone95a32c2011-01-14 22:31:13 +00002157 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002158 // Handle a constantexpr gep.
2159 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002160 isa<GlobalVariable>(CE->getOperand(0)) &&
2161 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002162 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002163 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002164 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002165 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002166 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002167
Dan Gohman80bdc962009-09-07 22:44:55 +00002168 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002169 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002170 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002171
2172 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002173 // notional bounds of the corresponding static array types.
2174 if (!CE->isGEPWithNoNotionalOverIndexing())
2175 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002176
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002177 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002178
2179 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2180 // and we know how to evaluate it by moving the bitcast from the pointer
2181 // operand to the value operand.
2182 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002183 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002184 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2185 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002186 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002187 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002188 }
2189
Chris Lattner79c11012005-09-26 04:44:35 +00002190 return false;
2191}
2192
Chris Lattner798b4d52005-09-26 06:52:44 +00002193/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2194/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2195/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2196static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002197 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002198 // Base case of the recursion.
2199 if (OpNo == Addr->getNumOperands()) {
2200 assert(Val->getType() == Init->getType() && "Type mismatch!");
2201 return Val;
2202 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002203
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002204 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002205 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002206 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002207 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2208 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002209
Chris Lattner798b4d52005-09-26 06:52:44 +00002210 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002211 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2212 unsigned Idx = CU->getZExtValue();
2213 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002214 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002215
Chris Lattner798b4d52005-09-26 06:52:44 +00002216 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002217 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002218 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002219
2220 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002221 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002222
2223 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002224 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002225 NumElts = ATy->getNumElements();
2226 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002227 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002228
2229 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002230 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2231 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002232
2233 assert(CI->getZExtValue() < NumElts);
2234 Elts[CI->getZExtValue()] =
2235 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2236
2237 if (Init->getType()->isArrayTy())
2238 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2239 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002240}
2241
Chris Lattner79c11012005-09-26 04:44:35 +00002242/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2243/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002244static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002245 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2246 assert(GV->hasInitializer());
2247 GV->setInitializer(Val);
2248 return;
2249 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002250
Chris Lattner798b4d52005-09-26 06:52:44 +00002251 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2252 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002253 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002254}
2255
Nick Lewycky7fa76772012-02-20 03:25:59 +00002256namespace {
2257
2258/// Evaluator - This class evaluates LLVM IR, producing the Constant
2259/// representing each SSA instruction. Changes to global variables are stored
2260/// in a mapping that can be iterated over after the evaluation is complete.
2261/// Once an evaluation call fails, the evaluation object should not be reused.
2262class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002263public:
Nick Lewycky7fa76772012-02-20 03:25:59 +00002264 Evaluator(const TargetData *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002265 : TD(TD), TLI(TLI) {
2266 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2267 }
2268
Nick Lewycky7fa76772012-02-20 03:25:59 +00002269 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002270 DeleteContainerPointers(ValueStack);
2271 while (!AllocaTmps.empty()) {
2272 GlobalVariable *Tmp = AllocaTmps.back();
2273 AllocaTmps.pop_back();
2274
2275 // If there are still users of the alloca, the program is doing something
2276 // silly, e.g. storing the address of the alloca somewhere and using it
2277 // later. Since this is undefined, we'll just make it be null.
2278 if (!Tmp->use_empty())
2279 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2280 delete Tmp;
2281 }
2282 }
2283
2284 /// EvaluateFunction - Evaluate a call to function F, returning true if
2285 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2286 /// arguments for the function.
2287 bool EvaluateFunction(Function *F, Constant *&RetVal,
2288 const SmallVectorImpl<Constant*> &ActualArgs);
2289
2290 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2291 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2292 /// control flows into, or null upon return.
2293 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2294
2295 Constant *getVal(Value *V) {
2296 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2297 Constant *R = ValueStack.back()->lookup(V);
2298 assert(R && "Reference to an uncomputed value!");
2299 return R;
2300 }
2301
2302 void setVal(Value *V, Constant *C) {
2303 ValueStack.back()->operator[](V) = C;
2304 }
2305
2306 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2307 return MutatedMemory;
2308 }
2309
2310 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2311 return Invariants;
2312 }
2313
2314private:
2315 Constant *ComputeLoadResult(Constant *P);
2316
2317 /// ValueStack - As we compute SSA register values, we store their contents
2318 /// here. The back of the vector contains the current function and the stack
2319 /// contains the values in the calling frames.
2320 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2321
2322 /// CallStack - This is used to detect recursion. In pathological situations
2323 /// we could hit exponential behavior, but at least there is nothing
2324 /// unbounded.
2325 SmallVector<Function*, 4> CallStack;
2326
2327 /// MutatedMemory - For each store we execute, we update this map. Loads
2328 /// check this to get the most up-to-date value. If evaluation is successful,
2329 /// this state is committed to the process.
2330 DenseMap<Constant*, Constant*> MutatedMemory;
2331
2332 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2333 /// to represent its body. This vector is needed so we can delete the
2334 /// temporary globals when we are done.
2335 SmallVector<GlobalVariable*, 32> AllocaTmps;
2336
2337 /// Invariants - These global variables have been marked invariant by the
2338 /// static constructor.
2339 SmallPtrSet<GlobalVariable*, 8> Invariants;
2340
2341 /// SimpleConstants - These are constants we have checked and know to be
2342 /// simple enough to live in a static initializer of a global.
2343 SmallPtrSet<Constant*, 8> SimpleConstants;
2344
2345 const TargetData *TD;
2346 const TargetLibraryInfo *TLI;
2347};
2348
Nick Lewycky7fa76772012-02-20 03:25:59 +00002349} // anonymous namespace
2350
Chris Lattner562a0552005-09-26 05:16:34 +00002351/// ComputeLoadResult - Return the value that would be computed by a load from
2352/// P after the stores reflected by 'memory' have been performed. If we can't
2353/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002354Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002355 // If this memory location has been recently stored, use the stored value: it
2356 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002357 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2358 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002359
Chris Lattner04de1cf2005-09-26 05:15:37 +00002360 // Access it.
2361 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002362 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002363 return GV->getInitializer();
2364 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002365 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002366
Chris Lattner798b4d52005-09-26 06:52:44 +00002367 // Handle a constantexpr getelementptr.
2368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2369 if (CE->getOpcode() == Instruction::GetElementPtr &&
2370 isa<GlobalVariable>(CE->getOperand(0))) {
2371 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002372 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002373 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002374 }
2375
2376 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002377}
2378
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002379/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2380/// successful, false if we can't evaluate it. NewBB returns the next BB that
2381/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002382bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2383 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002384 // This is the main evaluation loop.
2385 while (1) {
2386 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002387
Chris Lattner79c11012005-09-26 04:44:35 +00002388 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002389 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002390 Constant *Ptr = getVal(SI->getOperand(1));
Nick Lewyckya641c072012-02-21 22:08:06 +00002391 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2392 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002393 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002394 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002395 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002396
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002397 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002398
2399 // If this might be too difficult for the backend to handle (e.g. the addr
2400 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002401 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002402 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002403
2404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2405 if (CE->getOpcode() == Instruction::BitCast) {
2406 // If we're evaluating a store through a bitcast, then we need
2407 // to pull the bitcast off the pointer type and push it onto the
2408 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002409 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002410
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002411 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002412
Owen Anderson66f708f2011-01-16 04:33:33 +00002413 // In order to push the bitcast onto the stored value, a bitcast
2414 // from NewTy to Val's type must be legal. If it's not, we can try
2415 // introspecting NewTy to find a legal conversion.
2416 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2417 // If NewTy is a struct, we can convert the pointer to the struct
2418 // into a pointer to its first member.
2419 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002420 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002421 NewTy = STy->getTypeAtIndex(0U);
2422
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002423 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002424 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2425 Constant * const IdxList[] = {IdxZero, IdxZero};
2426
Jay Foadb4263a62011-07-22 08:52:50 +00002427 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2429 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2430
Owen Anderson66f708f2011-01-16 04:33:33 +00002431 // If we can't improve the situation by introspecting NewTy,
2432 // we have to give up.
2433 } else {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002434 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002435 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002436 }
2437
Owen Anderson66f708f2011-01-16 04:33:33 +00002438 // If we found compatible types, go ahead and push the bitcast
2439 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002440 Val = ConstantExpr::getBitCast(Val, NewTy);
2441 }
2442
Chris Lattner79c11012005-09-26 04:44:35 +00002443 MutatedMemory[Ptr] = Val;
2444 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002445 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002446 getVal(BO->getOperand(0)),
2447 getVal(BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002448 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002449 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002450 getVal(CI->getOperand(0)),
2451 getVal(CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002452 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002453 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002454 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002455 CI->getType());
2456 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002457 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2458 getVal(SI->getOperand(1)),
2459 getVal(SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002460 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002461 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002462 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002463 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2464 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002465 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002466 InstResult =
2467 ConstantExpr::getGetElementPtr(P, GEPOps,
2468 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002469 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002470 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Nick Lewyckya641c072012-02-21 22:08:06 +00002471 Constant *Ptr = getVal(LI->getOperand(0));
2472 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2473 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2474 InstResult = ComputeLoadResult(Ptr);
Chris Lattnercd271422005-09-27 04:45:34 +00002475 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002476 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002477 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002478 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002479 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002480 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002481 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002482 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002483 InstResult = AllocaTmps.back();
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002484 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2485 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002486
2487 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002488 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Devang Patel412a4462009-03-09 23:04:12 +00002489 ++CurInst;
2490 continue;
2491 }
2492
Chris Lattner7cd580f2006-07-07 21:37:01 +00002493 // Cannot handle inline asm.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002494 if (isa<InlineAsm>(CS.getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002495
Nick Lewycky81266c52012-02-17 06:59:21 +00002496 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2497 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2498 if (MSI->isVolatile()) return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002499 Constant *Ptr = getVal(MSI->getDest());
2500 Constant *Val = getVal(MSI->getValue());
2501 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002502 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2503 // This memset is a no-op.
2504 ++CurInst;
2505 continue;
2506 }
2507 }
2508
2509 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2510 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2511 ++CurInst;
2512 continue;
2513 }
2514
2515 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2516 // We don't insert an entry into Values, as it doesn't have a
2517 // meaningful return value.
2518 if (!II->use_empty())
2519 return false;
2520 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002521 Value *PtrArg = getVal(II->getArgOperand(1));
2522 Value *Ptr = PtrArg->stripPointerCasts();
2523 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2524 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2525 if (!Size->isAllOnesValue() &&
2526 Size->getValue().getLimitedValue() >=
2527 TD->getTypeStoreSize(ElemTy))
Nick Lewycky81266c52012-02-17 06:59:21 +00002528 Invariants.insert(GV);
2529 }
2530 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002531 ++CurInst;
2532 continue;
2533 }
2534 return false;
2535 }
2536
Chris Lattnercd271422005-09-27 04:45:34 +00002537 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002538 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002539 if (!Callee || Callee->mayBeOverridden())
2540 return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002541
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002542 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002543 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002544 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002545
Reid Spencer5cbf9852007-01-30 20:08:39 +00002546 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002547 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002548 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002549 InstResult = C;
2550 } else {
2551 return false;
2552 }
2553 } else {
2554 if (Callee->getFunctionType()->isVarArg())
2555 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002556
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002557 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002558 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002559 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2560 if (!EvaluateFunction(Callee, RetVal, Formals))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002561 return false;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002562 ValueStack.pop_back();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002563 InstResult = RetVal;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002564
2565 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2566 NextBB = II->getNormalDest();
2567 return true;
2568 }
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002569 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002570 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002571 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2572 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002573 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002574 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002575 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002576 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002577 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002578
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002579 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002580 }
2581 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2582 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002583 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002584 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002585 unsigned ValTISucc = SI->resolveSuccessorIndex(SI->findCaseValue(Val));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002586 NextBB = SI->getSuccessor(ValTISucc);
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002587 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002588 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002589 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002590 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002591 else
2592 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002593 } else if (isa<ReturnInst>(CurInst)) {
2594 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002595 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002596 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002597 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002598 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002599
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002600 // We succeeded at evaluating this block!
2601 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002602 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002603 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002604 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002605 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002606
Chris Lattner1945d582010-12-07 04:33:29 +00002607 if (!CurInst->use_empty()) {
2608 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002609 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002610
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002611 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002612 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002613
Chris Lattner79c11012005-09-26 04:44:35 +00002614 // Advance program counter.
2615 ++CurInst;
2616 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002617}
2618
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002619/// EvaluateFunction - Evaluate a call to function F, returning true if
2620/// successful, false if we can't evaluate it. ActualArgs contains the formal
2621/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002622bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2623 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002624 // Check to see if this function is already executing (recursion). If so,
2625 // bail out. TODO: we might want to accept limited recursion.
2626 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2627 return false;
2628
2629 CallStack.push_back(F);
2630
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002631 // Initialize arguments to the incoming values specified.
2632 unsigned ArgNo = 0;
2633 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2634 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002635 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002636
2637 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2638 // we can only evaluate any one basic block at most once. This set keeps
2639 // track of what we have executed so we can detect recursive cases etc.
2640 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2641
2642 // CurBB - The current basic block we're evaluating.
2643 BasicBlock *CurBB = F->begin();
2644
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002645 BasicBlock::iterator CurInst = CurBB->begin();
2646
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002647 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002648 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002649 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002650 return false;
2651
2652 if (NextBB == 0) {
2653 // Successfully running until there's no next block means that we found
2654 // the return. Fill it the return value and pop the call stack.
2655 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2656 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002657 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002658 CallStack.pop_back();
2659 return true;
2660 }
2661
2662 // Okay, we succeeded in evaluating this control flow. See if we have
2663 // executed the new block before. If so, we have a looping function,
2664 // which we cannot evaluate in reasonable time.
2665 if (!ExecutedBlocks.insert(NextBB))
2666 return false; // looped!
2667
2668 // Okay, we have never been in this block before. Check to see if there
2669 // are any PHI nodes. If so, evaluate them with information about where
2670 // we came from.
2671 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002672 for (CurInst = NextBB->begin();
2673 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002674 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002675
2676 // Advance to the next block.
2677 CurBB = NextBB;
2678 }
2679}
2680
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002681/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2682/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002683static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2684 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002685 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002686 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002687 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002688 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2689 SmallVector<Constant*, 0>());
Chris Lattner1945d582010-12-07 04:33:29 +00002690
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002691 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002692 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002693 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002694 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002695 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002696 for (DenseMap<Constant*, Constant*>::const_iterator I =
2697 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
2698 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002699 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002700 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2701 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2702 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002703 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002704 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002705
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002706 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002707}
2708
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002709/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2710/// Return true if anything changed.
2711bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2712 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2713 bool MadeChange = false;
2714 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002715
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002716 // Loop over global ctors, optimizing them when we can.
2717 for (unsigned i = 0; i != Ctors.size(); ++i) {
2718 Function *F = Ctors[i];
2719 // Found a null terminator in the middle of the list, prune off the rest of
2720 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002721 if (F == 0) {
2722 if (i != Ctors.size()-1) {
2723 Ctors.resize(i+1);
2724 MadeChange = true;
2725 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002726 break;
2727 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002728
Chris Lattner79c11012005-09-26 04:44:35 +00002729 // We cannot simplify external ctor functions.
2730 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002731
Chris Lattner79c11012005-09-26 04:44:35 +00002732 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002733 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002734 Ctors.erase(Ctors.begin()+i);
2735 MadeChange = true;
2736 --i;
2737 ++NumCtorsEvaluated;
2738 continue;
2739 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002740 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002741
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002742 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002743
Chris Lattner7b550cc2009-11-06 04:27:31 +00002744 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002745 return true;
2746}
2747
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002748bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002749 bool Changed = false;
2750
Duncan Sands177d84e2009-01-07 20:01:06 +00002751 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002752 I != E;) {
2753 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002754 // Aliases without names cannot be referenced outside this module.
2755 if (!J->hasName() && !J->isDeclaration())
2756 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002757 // If the aliasee may change at link time, nothing can be done - bail out.
2758 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002759 continue;
2760
Duncan Sands4782b302009-02-15 09:56:08 +00002761 Constant *Aliasee = J->getAliasee();
2762 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002763 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002764 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2765
2766 // Make all users of the alias use the aliasee instead.
2767 if (!J->use_empty()) {
2768 J->replaceAllUsesWith(Aliasee);
2769 ++NumAliasesResolved;
2770 Changed = true;
2771 }
2772
Duncan Sands7a154cf2009-12-08 10:10:20 +00002773 // If the alias is externally visible, we may still be able to simplify it.
2774 if (!J->hasLocalLinkage()) {
2775 // If the aliasee has internal linkage, give it the name and linkage
2776 // of the alias, and delete the alias. This turns:
2777 // define internal ... @f(...)
2778 // @a = alias ... @f
2779 // into:
2780 // define ... @a(...)
2781 if (!Target->hasLocalLinkage())
2782 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002783
Duncan Sands7a154cf2009-12-08 10:10:20 +00002784 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002785 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002786 // and other attributes of the aliasee with those of the alias.
2787 if (!hasOneUse)
2788 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002789
Duncan Sands7a154cf2009-12-08 10:10:20 +00002790 // Give the aliasee the name, linkage and other attributes of the alias.
2791 Target->takeName(J);
2792 Target->setLinkage(J->getLinkage());
2793 Target->GlobalValue::copyAttributesFrom(J);
2794 }
Duncan Sands4782b302009-02-15 09:56:08 +00002795
2796 // Delete the alias.
2797 M.getAliasList().erase(J);
2798 ++NumAliasesRemoved;
2799 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002800 }
2801
2802 return Changed;
2803}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002804
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002805static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2806 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00002807 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002808
2809 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Anders Carlssona201c4c2011-03-20 17:59:11 +00002810
2811 if (!Fn)
2812 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002813
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002814 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00002815
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002816 // Checking that the function has the right return type, the right number of
2817 // parameters and that they all have pointer types should be enough.
2818 if (!FTy->getReturnType()->isIntegerTy() ||
2819 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00002820 !FTy->getParamType(0)->isPointerTy() ||
2821 !FTy->getParamType(1)->isPointerTy() ||
2822 !FTy->getParamType(2)->isPointerTy())
2823 return 0;
2824
2825 return Fn;
2826}
2827
2828/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
2829/// destructor and can therefore be eliminated.
2830/// Note that we assume that other optimization passes have already simplified
2831/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00002832/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
2833/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002834static bool cxxDtorIsEmpty(const Function &Fn,
2835 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002836 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002837 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002838 if (Fn.isDeclaration())
2839 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00002840
2841 if (++Fn.begin() != Fn.end())
2842 return false;
2843
2844 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2845 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2846 I != E; ++I) {
2847 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00002848 // Ignore debug intrinsics.
2849 if (isa<DbgInfoIntrinsic>(CI))
2850 continue;
2851
Anders Carlssona201c4c2011-03-20 17:59:11 +00002852 const Function *CalledFn = CI->getCalledFunction();
2853
2854 if (!CalledFn)
2855 return false;
2856
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002857 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2858
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002859 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002860 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002861 return false;
2862
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002863 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002864 return false;
2865 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00002866 return true; // We're done.
2867 else if (I->mayHaveSideEffects())
2868 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002869 }
2870
2871 return false;
2872}
2873
2874bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2875 /// Itanium C++ ABI p3.3.5:
2876 ///
2877 /// After constructing a global (or local static) object, that will require
2878 /// destruction on exit, a termination function is registered as follows:
2879 ///
2880 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2881 ///
2882 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2883 /// call f(p) when DSO d is unloaded, before all such termination calls
2884 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002885 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002886
2887 // This pass will look for calls to __cxa_atexit where the function is trivial
2888 // and remove them.
2889 bool Changed = false;
2890
2891 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
2892 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002893 // We're only interested in calls. Theoretically, we could handle invoke
2894 // instructions as well, but neither llvm-gcc nor clang generate invokes
2895 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002896 CallInst *CI = dyn_cast<CallInst>(*I++);
2897 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002898 continue;
2899
Anders Carlssona201c4c2011-03-20 17:59:11 +00002900 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00002901 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00002902 if (!DtorFn)
2903 continue;
2904
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002905 SmallPtrSet<const Function *, 8> CalledFunctions;
2906 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002907 continue;
2908
2909 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002910 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
2911 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002912
Anders Carlssona201c4c2011-03-20 17:59:11 +00002913 ++NumCXXDtorsRemoved;
2914
2915 Changed |= true;
2916 }
2917
2918 return Changed;
2919}
2920
Chris Lattner7a90b682004-10-07 04:16:33 +00002921bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002922 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002923
Nick Lewycky6a577f82012-02-12 01:13:18 +00002924 TD = getAnalysisIfAvailable<TargetData>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002925 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00002926
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002927 // Try to find the llvm.globalctors list.
2928 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002929
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00002930 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002931
Chris Lattner7a90b682004-10-07 04:16:33 +00002932 bool LocalChange = true;
2933 while (LocalChange) {
2934 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002935
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002936 // Delete functions that are trivially dead, ccc -> fastcc
2937 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002938
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002939 // Optimize global_ctors list.
2940 if (GlobalCtors)
2941 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002942
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002943 // Optimize non-address-taken globals.
2944 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002945
2946 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002947 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002948
2949 // Try to remove trivial global destructors.
2950 if (CXAAtExitFn)
2951 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
2952
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002953 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002954 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002955
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002956 // TODO: Move all global ctors functions to the end of the module for code
2957 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002958
Chris Lattner079236d2004-02-25 21:34:36 +00002959 return Changed;
2960}