blob: 80b11ed792b53f7433ff02a8ea28aca6a425a977 [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"
Duncan Sands548448a2008-02-18 17:32:13 +000029#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000030#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000033#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000035#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000036#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000037#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000039#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000040#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000041using namespace llvm;
42
Chris Lattner86453c52006-12-19 22:09:18 +000043STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000044STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000045STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
46STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
47STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
48STATISTIC(NumDeleted , "Number of globals deleted");
49STATISTIC(NumFnDeleted , "Number of functions deleted");
50STATISTIC(NumGlobUses , "Number of global uses devirtualized");
51STATISTIC(NumLocalized , "Number of globals localized");
52STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
53STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
54STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000055STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000056STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
57STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000058STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000059
Chris Lattner86453c52006-12-19 22:09:18 +000060namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000061 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000062 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000063 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner30ba5692004-10-11 05:54:41 +000064 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000065 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000066 GlobalOpt() : ModulePass(ID) {
67 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
68 }
Misha Brukmanfd939082005-04-21 23:48:37 +000069
Chris Lattnerb12914b2004-09-20 04:48:05 +000070 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000071
72 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000073 GlobalVariable *FindGlobalCtors(Module &M);
74 bool OptimizeFunctions(Module &M);
75 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000076 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000077 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000078 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
79 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
80 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
81 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000082 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Chris Lattner079236d2004-02-25 21:34:36 +000083 };
Chris Lattner079236d2004-02-25 21:34:36 +000084}
85
Dan Gohman844731a2008-05-13 00:00:25 +000086char GlobalOpt::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000087INITIALIZE_PASS(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000088 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000089
Chris Lattner7a90b682004-10-07 04:16:33 +000090ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000091
Dan Gohman844731a2008-05-13 00:00:25 +000092namespace {
93
Chris Lattner7a90b682004-10-07 04:16:33 +000094/// GlobalStatus - As we analyze each global, keep track of some information
95/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000096/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000097struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +000098 /// isCompared - True if the global's address is used in a comparison.
99 bool isCompared;
100
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000101 /// isLoaded - True if the global is ever loaded. If the global isn't ever
102 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000103 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000104
105 /// StoredType - Keep track of what stores to the global look like.
106 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000107 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000108 /// NotStored - There is no store to this global. It can thus be marked
109 /// constant.
110 NotStored,
111
112 /// isInitializerStored - This global is stored to, but the only thing
113 /// stored is the constant it was initialized with. This is only tracked
114 /// for scalar globals.
115 isInitializerStored,
116
117 /// isStoredOnce - This global is stored to, but only its initializer and
118 /// one other value is ever stored to it. If this global isStoredOnce, we
119 /// track the value stored to it in StoredOnceValue below. This is only
120 /// tracked for scalar globals.
121 isStoredOnce,
122
123 /// isStored - This global is stored to by multiple values or something else
124 /// that we cannot track.
125 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000126 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000127
128 /// StoredOnceValue - If only one value (besides the initializer constant) is
129 /// ever stored to this global, keep track of what value it is.
130 Value *StoredOnceValue;
131
Chris Lattner25de4e52006-11-01 18:03:33 +0000132 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
133 /// null/false. When the first accessing function is noticed, it is recorded.
134 /// When a second different accessing function is noticed,
135 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000136 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000137 bool HasMultipleAccessingFunctions;
138
Chris Lattner25de4e52006-11-01 18:03:33 +0000139 /// HasNonInstructionUser - Set to true if this global has a user that is not
140 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000141 bool HasNonInstructionUser;
142
Chris Lattner25de4e52006-11-01 18:03:33 +0000143 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
144 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000145
Rafael Espindolac4440e32011-01-19 16:32:21 +0000146 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
147 StoredOnceValue(0), AccessingFunction(0),
148 HasMultipleAccessingFunctions(false), HasNonInstructionUser(false),
149 HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000150};
Chris Lattnere47ba742004-10-06 20:57:02 +0000151
Dan Gohman844731a2008-05-13 00:00:25 +0000152}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000153
Jay Foade3acf152009-06-09 21:37:11 +0000154// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
155// by constants itself. Note that constants cannot be cyclic, so this test is
156// pretty easy to implement recursively.
157//
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000158static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000159 if (isa<GlobalValue>(C)) return false;
160
Gabor Greif27236912010-04-07 18:59:26 +0000161 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
162 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000163 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000164 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000165 } else
166 return false;
167 return true;
168}
169
170
Chris Lattner7a90b682004-10-07 04:16:33 +0000171/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
172/// structure. If the global has its address taken, return true to indicate we
173/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000174///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000175static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
176 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000177 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000178 ++UI) {
179 const User *U = *UI;
180 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000181 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000182
183 // If the result of the constantexpr isn't pointer type, then we won't
184 // know to expect it in various places. Just reject early.
185 if (!isa<PointerType>(CE->getType())) return true;
186
Chris Lattner7a90b682004-10-07 04:16:33 +0000187 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000188 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000189 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000190 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000191 if (GS.AccessingFunction == 0)
192 GS.AccessingFunction = F;
193 else if (GS.AccessingFunction != F)
194 GS.HasMultipleAccessingFunctions = true;
195 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000196 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000197 GS.isLoaded = true;
Eli Friedman33cb4452011-08-16 00:20:11 +0000198 // Don't hack on volatile/atomic loads.
199 if (!LI->isSimple()) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000200 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000201 // Don't allow a store OF the address, only stores TO the address.
202 if (SI->getOperand(0) == V) return true;
203
Eli Friedman33cb4452011-08-16 00:20:11 +0000204 // Don't hack on volatile/atomic stores.
205 if (!SI->isSimple()) return true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000206
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000207 // If this is a direct store to the global (i.e., the global is a scalar
208 // value, not an aggregate), keep more specific information about
209 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000210 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000211 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
212 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000213 Value *StoredVal = SI->getOperand(0);
214 if (StoredVal == GV->getInitializer()) {
215 if (GS.StoredType < GlobalStatus::isInitializerStored)
216 GS.StoredType = GlobalStatus::isInitializerStored;
217 } else if (isa<LoadInst>(StoredVal) &&
218 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000219 if (GS.StoredType < GlobalStatus::isInitializerStored)
220 GS.StoredType = GlobalStatus::isInitializerStored;
221 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
222 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000223 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000224 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000225 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000226 // noop.
227 } else {
228 GS.StoredType = GlobalStatus::isStored;
229 }
230 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000231 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000232 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000233 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000234 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000235 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000236 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000237 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000238 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000239 // PHI nodes we can check just like select or GEP instructions, but we
240 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000241 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000242 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000243 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000244 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000245 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000246 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
247 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000248 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000249 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000250 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000251 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000252 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
253 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
254 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000255 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000256 } else {
257 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000258 }
Gabor Greife6642672010-07-09 16:51:20 +0000259 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000260 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000261 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000262 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000263 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000264 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000265 GS.HasNonInstructionUser = true;
266 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000267 return true;
268 }
Gabor Greife6642672010-07-09 16:51:20 +0000269 }
Chris Lattner079236d2004-02-25 21:34:36 +0000270
271 return false;
272}
273
Chris Lattner7b550cc2009-11-06 04:27:31 +0000274static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
Chris Lattner670c8892004-10-08 17:32:09 +0000275 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
276 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000277 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000278
Chris Lattner670c8892004-10-08 17:32:09 +0000279 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
280 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
281 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
282 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000283 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000284 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000285 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000286 if (StructType *STy = dyn_cast<StructType>(Agg->getType())) {
Chris Lattner670c8892004-10-08 17:32:09 +0000287 if (IdxV < STy->getNumElements())
Owen Andersona7235ea2009-07-31 20:28:14 +0000288 return Constant::getNullValue(STy->getElementType(IdxV));
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000289 } else if (SequentialType *STy =
Chris Lattner670c8892004-10-08 17:32:09 +0000290 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000291 return Constant::getNullValue(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000292 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000293 } else if (isa<UndefValue>(Agg)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000294 if (StructType *STy = dyn_cast<StructType>(Agg->getType())) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000295 if (IdxV < STy->getNumElements())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000296 return UndefValue::get(STy->getElementType(IdxV));
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000297 } else if (SequentialType *STy =
Chris Lattner7a7ed022004-10-16 18:09:00 +0000298 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000299 return UndefValue::get(STy->getElementType());
Chris Lattner7a7ed022004-10-16 18:09:00 +0000300 }
Chris Lattner670c8892004-10-08 17:32:09 +0000301 }
302 return 0;
303}
Chris Lattner7a90b682004-10-07 04:16:33 +0000304
Chris Lattner7a90b682004-10-07 04:16:33 +0000305
Chris Lattnere47ba742004-10-06 20:57:02 +0000306/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
307/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000308/// quick scan over the use list to clean up the easy and obvious cruft. This
309/// returns true if it made a change.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000310static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000311 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000312 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
313 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000314
Chris Lattner7a90b682004-10-07 04:16:33 +0000315 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000316 if (Init) {
317 // Replace the load with the initializer.
318 LI->replaceAllUsesWith(Init);
319 LI->eraseFromParent();
320 Changed = true;
321 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000322 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000323 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000324 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000325 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000326 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
327 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000328 Constant *SubInit = 0;
329 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000330 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000331 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000332 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000333 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000334 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000335 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000336 }
337
338 if (CE->use_empty()) {
339 CE->destroyConstant();
340 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000341 }
342 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000343 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
344 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
345 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000346 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000347 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000348 ConstantExpr *CE =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000349 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000350 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000351 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000352 }
Chris Lattner7b550cc2009-11-06 04:27:31 +0000353 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000354
Chris Lattner031955d2004-10-10 16:43:46 +0000355 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000356 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000357 Changed = true;
358 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000359 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
360 if (MI->getRawDest() == V) {
361 MI->eraseFromParent();
362 Changed = true;
363 }
364
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000365 } else if (Constant *C = dyn_cast<Constant>(U)) {
366 // If we have a chain of dead constantexprs or other things dangling from
367 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000368 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000369 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000370 // This could have invalidated UI, start over from scratch.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000371 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000372 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000373 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000374 }
375 }
Chris Lattner031955d2004-10-10 16:43:46 +0000376 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000377}
378
Chris Lattner941db492008-01-14 02:09:12 +0000379/// isSafeSROAElementUse - Return true if the specified instruction is a safe
380/// user of a derived expression from a global that we want to SROA.
381static bool isSafeSROAElementUse(Value *V) {
382 // We might have a dead and dangling constant hanging off of here.
383 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000384 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000385
Chris Lattner941db492008-01-14 02:09:12 +0000386 Instruction *I = dyn_cast<Instruction>(V);
387 if (!I) return false;
388
389 // Loads are ok.
390 if (isa<LoadInst>(I)) return true;
391
392 // Stores *to* the pointer are ok.
393 if (StoreInst *SI = dyn_cast<StoreInst>(I))
394 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000395
Chris Lattner941db492008-01-14 02:09:12 +0000396 // Otherwise, it must be a GEP.
397 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
398 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000399
Chris Lattner941db492008-01-14 02:09:12 +0000400 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
401 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
402 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000403
Chris Lattner941db492008-01-14 02:09:12 +0000404 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
405 I != E; ++I)
406 if (!isSafeSROAElementUse(*I))
407 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000408 return true;
409}
410
Chris Lattner941db492008-01-14 02:09:12 +0000411
412/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
413/// Look at it and its uses and decide whether it is safe to SROA this global.
414///
415static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
416 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000417 if (!isa<GetElementPtrInst>(U) &&
418 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000419 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
420 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000421
Chris Lattner941db492008-01-14 02:09:12 +0000422 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
423 // don't like < 3 operand CE's, and we don't like non-constant integer
424 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
425 // value of C.
426 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
427 !cast<Constant>(U->getOperand(1))->isNullValue() ||
428 !isa<ConstantInt>(U->getOperand(2)))
429 return false;
430
431 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
432 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000433
Chris Lattner941db492008-01-14 02:09:12 +0000434 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000435 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000436 uint64_t NumElements = AT->getNumElements();
437 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000438
Chris Lattner941db492008-01-14 02:09:12 +0000439 // Check to make sure that index falls within the array. If not,
440 // something funny is going on, so we won't do the optimization.
441 //
442 if (Idx->getZExtValue() >= NumElements)
443 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000444
Chris Lattner941db492008-01-14 02:09:12 +0000445 // We cannot scalar repl this level of the array unless any array
446 // sub-indices are in-range constants. In particular, consider:
447 // A[0][i]. We cannot know that the user isn't doing invalid things like
448 // allowing i to index an out-of-range subscript that accesses A[1].
449 //
450 // Scalar replacing *just* the outer index of the array is probably not
451 // going to be a win anyway, so just give up.
452 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000453 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000454 ++GEPI) {
455 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000456 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000457 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000458 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000459 NumElements = SubVectorTy->getNumElements();
460 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000461 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000462 "Indexed GEP type is not array, vector, or struct!");
463 continue;
464 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000465
Chris Lattner941db492008-01-14 02:09:12 +0000466 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
467 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
468 return false;
469 }
470 }
471
472 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
473 if (!isSafeSROAElementUse(*I))
474 return false;
475 return true;
476}
477
478/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
479/// is safe for us to perform this transformation.
480///
481static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
482 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
483 UI != E; ++UI) {
484 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
485 return false;
486 }
487 return true;
488}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000489
Chris Lattner941db492008-01-14 02:09:12 +0000490
Chris Lattner670c8892004-10-08 17:32:09 +0000491/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
492/// variable. This opens the door for other optimizations by exposing the
493/// behavior of the program in a more fine-grained way. We have determined that
494/// this transformation is safe already. We return the first global variable we
495/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000496static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000497 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000498 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000499 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000500
Rafael Espindolabb46f522009-01-15 20:18:42 +0000501 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000502 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000503 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000504
Chris Lattner670c8892004-10-08 17:32:09 +0000505 std::vector<GlobalVariable*> NewGlobals;
506 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
507
Chris Lattner998182b2008-04-26 07:40:11 +0000508 // Get the alignment of the global, either explicit or target-specific.
509 unsigned StartAlignment = GV->getAlignment();
510 if (StartAlignment == 0)
511 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000512
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000513 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000514 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000515 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000516 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
517 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000518 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000519 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000520 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000521 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000522 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000523 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000524 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000525 Globals.insert(GV, NGV);
526 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000527
Chris Lattner998182b2008-04-26 07:40:11 +0000528 // Calculate the known alignment of the field. If the original aggregate
529 // had 256 byte alignment for example, something might depend on that:
530 // propagate info to each field.
531 uint64_t FieldOffset = Layout.getElementOffset(i);
532 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
533 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
534 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000535 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000536 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000537 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000538 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000539 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000540 else
Chris Lattner998182b2008-04-26 07:40:11 +0000541 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000542
Chris Lattner1f21ef12005-02-23 16:53:04 +0000543 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000544 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000545 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000546
Duncan Sands777d2302009-05-09 07:06:46 +0000547 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000548 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000549 for (unsigned i = 0, e = NumElements; i != e; ++i) {
550 Constant *In = getAggregateConstantElement(Init,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000551 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
Chris Lattner670c8892004-10-08 17:32:09 +0000552 assert(In && "Couldn't get element of initializer?");
553
Chris Lattner7b550cc2009-11-06 04:27:31 +0000554 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000555 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000556 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000557 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000558 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000559 Globals.insert(GV, NGV);
560 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000561
Chris Lattner998182b2008-04-26 07:40:11 +0000562 // Calculate the known alignment of the field. If the original aggregate
563 // had 256 byte alignment for example, something might depend on that:
564 // propagate info to each field.
565 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
566 if (NewAlign > EltAlign)
567 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000568 }
569 }
570
571 if (NewGlobals.empty())
572 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000573
David Greene3215b0e2010-01-05 01:28:05 +0000574 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000575
Chris Lattner7b550cc2009-11-06 04:27:31 +0000576 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000577
578 // Loop over all of the uses of the global, replacing the constantexpr geps,
579 // with smaller constantexpr geps or direct references.
580 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000581 User *GEP = GV->use_back();
582 assert(((isa<ConstantExpr>(GEP) &&
583 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
584 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000585
Chris Lattner670c8892004-10-08 17:32:09 +0000586 // Ignore the 1th operand, which has to be zero or else the program is quite
587 // broken (undefined). Get the 2nd operand, which is the structure or array
588 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000589 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000590 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
591
Chris Lattner30ba5692004-10-11 05:54:41 +0000592 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000593
594 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000595 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000596 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000597 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000598 Idxs.push_back(NullInt);
599 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
600 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000601 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000602 } else {
603 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000604 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000605 Idxs.push_back(NullInt);
606 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
607 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000608 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000609 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000610 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000611 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000612 GEP->replaceAllUsesWith(NewPtr);
613
614 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000615 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000616 else
617 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000618 }
619
Chris Lattnere40e2d12004-10-08 20:25:55 +0000620 // Delete the old global, now that it is dead.
621 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000622 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000623
624 // Loop over the new globals array deleting any globals that are obviously
625 // dead. This can arise due to scalarization of a structure or an array that
626 // has elements that are dead.
627 unsigned FirstGlobal = 0;
628 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
629 if (NewGlobals[i]->use_empty()) {
630 Globals.erase(NewGlobals[i]);
631 if (FirstGlobal == i) ++FirstGlobal;
632 }
633
634 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000635}
636
Chris Lattner9b34a612004-10-09 21:48:45 +0000637/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000638/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000639/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000640static bool AllUsesOfValueWillTrapIfNull(const Value *V,
641 SmallPtrSet<const PHINode*, 8> &PHIs) {
642 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000643 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000644 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000645
646 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000647 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000648 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000649 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000650 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000651 return false; // Storing the value.
652 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000653 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000654 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000655 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000656 return false; // Not calling the ptr
657 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000658 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000659 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000660 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000661 return false; // Not calling the ptr
662 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000663 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000664 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000665 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000666 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000667 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000668 // If we've already seen this phi node, ignore it, it has already been
669 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000670 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
671 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000672 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000673 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000674 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000675 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000676 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000677 return false;
678 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000679 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000680 return true;
681}
682
683/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000684/// from GV will trap if the loaded value is null. Note that this also permits
685/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000686static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
687 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000688 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000689 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000690
Gabor Greif6ce02b52010-04-06 19:24:18 +0000691 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
692 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000693 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000694 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000695 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000696 // Ignore stores to the global.
697 } else {
698 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000699 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000700 return false;
701 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000702 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000703 return true;
704}
705
Chris Lattner7b550cc2009-11-06 04:27:31 +0000706static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000707 bool Changed = false;
708 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
709 Instruction *I = cast<Instruction>(*UI++);
710 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
711 LI->setOperand(0, NewV);
712 Changed = true;
713 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
714 if (SI->getOperand(1) == V) {
715 SI->setOperand(1, NewV);
716 Changed = true;
717 }
718 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000719 CallSite CS(I);
720 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000721 // Calling through the pointer! Turn into a direct call, but be careful
722 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000723 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000724 Changed = true;
725 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000726 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
727 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000728 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000729 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000730 }
731
732 if (PassedAsArg) {
733 // Being passed as an argument also. Be careful to not invalidate UI!
734 UI = V->use_begin();
735 }
736 }
737 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
738 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000739 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000740 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000741 if (CI->use_empty()) {
742 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000743 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000744 }
745 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
746 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000747 SmallVector<Constant*, 8> Idxs;
748 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000749 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
750 i != e; ++i)
751 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000752 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000753 else
754 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000755 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000756 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000757 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000758 if (GEPI->use_empty()) {
759 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000760 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000761 }
762 }
763 }
764
765 return Changed;
766}
767
768
769/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
770/// value stored into it. If there are uses of the loaded value that would trap
771/// if the loaded value is dynamically null, then we know that they cannot be
772/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000773static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000774 bool Changed = false;
775
Chris Lattner92c6bd22009-01-14 00:12:58 +0000776 // Keep track of whether we are able to remove all the uses of the global
777 // other than the store that defines it.
778 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000779
Chris Lattner708148e2004-10-10 23:14:11 +0000780 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000781 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
782 User *GlobalUser = *GUI++;
783 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000784 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000785 // If we were able to delete all uses of the loads
786 if (LI->use_empty()) {
787 LI->eraseFromParent();
788 Changed = true;
789 } else {
790 AllNonStoreUsesGone = false;
791 }
792 } else if (isa<StoreInst>(GlobalUser)) {
793 // Ignore the store that stores "LV" to the global.
794 assert(GlobalUser->getOperand(1) == GV &&
795 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000796 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000797 AllNonStoreUsesGone = false;
798
799 // If we get here we could have other crazy uses that are transitively
800 // loaded.
801 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000802 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
803 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000804 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000805 }
Chris Lattner708148e2004-10-10 23:14:11 +0000806
807 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000808 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000809 ++NumGlobUses;
810 }
811
Chris Lattner708148e2004-10-10 23:14:11 +0000812 // If we nuked all of the loads, then none of the stores are needed either,
813 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000814 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000815 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000816 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000817 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000818 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000819 ++NumDeleted;
820 }
821 Changed = true;
822 }
823 return Changed;
824}
825
Chris Lattner30ba5692004-10-11 05:54:41 +0000826/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
827/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000828static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000829 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
830 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chris Lattner7b550cc2009-11-06 04:27:31 +0000831 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000832 I->replaceAllUsesWith(NewC);
833
Chris Lattnerd514d822005-02-01 01:23:31 +0000834 // Advance UI to the next non-I use to avoid invalidating it!
835 // Instructions could multiply use V.
836 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000837 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000838 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000839 }
840}
841
842/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
843/// variable, and transforms the program as if it always contained the result of
844/// the specified malloc. Because it is always the result of the specified
845/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000846/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000847static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000848 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000849 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000850 ConstantInt *NElements,
Victor Hernandez83d63912009-09-18 22:35:49 +0000851 TargetData* TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000852 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000853
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000854 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +0000855 if (NElements->getZExtValue() == 1)
856 GlobalType = AllocTy;
857 else
858 // If we have an array allocation, the global variable is of an array.
859 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000860
861 // Create the new global variable. The contents of the malloc'd memory is
862 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000863 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000864 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000865 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000866 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000867 GV->getName()+".body",
868 GV,
869 GV->isThreadLocal());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000870
Chris Lattnera6874652010-02-25 22:33:52 +0000871 // If there are bitcast users of the malloc (which is typical, usually we have
872 // a malloc + bitcast) then replace them with uses of the new global. Update
873 // other users to use the global as well.
874 BitCastInst *TheBC = 0;
875 while (!CI->use_empty()) {
876 Instruction *User = cast<Instruction>(CI->use_back());
877 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
878 if (BCI->getType() == NewGV->getType()) {
879 BCI->replaceAllUsesWith(NewGV);
880 BCI->eraseFromParent();
881 } else {
882 BCI->setOperand(0, NewGV);
883 }
884 } else {
885 if (TheBC == 0)
886 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
887 User->replaceUsesOfWith(CI, TheBC);
888 }
889 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000890
Victor Hernandez83d63912009-09-18 22:35:49 +0000891 Constant *RepValue = NewGV;
892 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000893 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000894 GV->getType()->getElementType());
895
896 // If there is a comparison against null, we will insert a global bool to
897 // keep track of whether the global was initialized yet or not.
898 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000899 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000900 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000901 ConstantInt::getFalse(GV->getContext()),
902 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000903 bool InitBoolUsed = false;
904
905 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000906 while (!GV->use_empty()) {
907 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000908 // The global is initialized when the store to it occurs.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000909 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000910 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000911 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000912 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000913
Chris Lattnera6874652010-02-25 22:33:52 +0000914 LoadInst *LI = cast<LoadInst>(GV->use_back());
915 while (!LI->use_empty()) {
916 Use &LoadUse = LI->use_begin().getUse();
917 if (!isa<ICmpInst>(LoadUse.getUser())) {
918 LoadUse = RepValue;
919 continue;
920 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000921
Chris Lattnera6874652010-02-25 22:33:52 +0000922 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
923 // Replace the cmp X, 0 with a use of the bool value.
924 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
925 InitBoolUsed = true;
926 switch (ICI->getPredicate()) {
927 default: llvm_unreachable("Unknown ICmp Predicate!");
928 case ICmpInst::ICMP_ULT:
929 case ICmpInst::ICMP_SLT: // X < null -> always false
930 LV = ConstantInt::getFalse(GV->getContext());
931 break;
932 case ICmpInst::ICMP_ULE:
933 case ICmpInst::ICMP_SLE:
934 case ICmpInst::ICMP_EQ:
935 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
936 break;
937 case ICmpInst::ICMP_NE:
938 case ICmpInst::ICMP_UGE:
939 case ICmpInst::ICMP_SGE:
940 case ICmpInst::ICMP_UGT:
941 case ICmpInst::ICMP_SGT:
942 break; // no change.
943 }
944 ICI->replaceAllUsesWith(LV);
945 ICI->eraseFromParent();
946 }
947 LI->eraseFromParent();
948 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000949
950 // If the initialization boolean was used, insert it, otherwise delete it.
951 if (!InitBoolUsed) {
952 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000953 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000954 delete InitBool;
955 } else
956 GV->getParent()->getGlobalList().insert(GV, InitBool);
957
Chris Lattnera6874652010-02-25 22:33:52 +0000958 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000959 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000960 CI->eraseFromParent();
961
962 // To further other optimizations, loop over all users of NewGV and try to
963 // constant prop them. This will promote GEP instructions with constant
964 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000965 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000966 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000967 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000968
969 return NewGV;
970}
971
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000972/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
973/// to make sure that there are no complex uses of V. We permit simple things
974/// like dereferencing the pointer, but not storing through the address, unless
975/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000976static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
977 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000978 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000979 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000980 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000981 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000982
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000983 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
984 continue; // Fine, ignore.
985 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000986
Gabor Greif0b520db2010-04-06 18:58:22 +0000987 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000988 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
989 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000990 continue; // Otherwise, storing through it, or storing into GV... fine.
991 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000992
Chris Lattnera2fb2342010-04-10 18:19:22 +0000993 // Must index into the array and into the struct.
994 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000995 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000996 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000997 continue;
998 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000999
Gabor Greif0b520db2010-04-06 18:58:22 +00001000 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001001 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1002 // cycles.
1003 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +00001004 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1005 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001006 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001007 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001008
Gabor Greif0b520db2010-04-06 18:58:22 +00001009 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001010 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1011 return false;
1012 continue;
1013 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001014
Chris Lattner49b6d4a2008-12-15 21:08:54 +00001015 return false;
1016 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001017 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001018}
1019
Chris Lattner86395032006-09-30 23:32:09 +00001020/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1021/// somewhere. Transform all uses of the allocation into loads from the
1022/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001023/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001024/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001025static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001026 GlobalVariable *GV) {
1027 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001028 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1029 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001030 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1031 // If this is the store of the allocation into the global, remove it.
1032 if (SI->getOperand(1) == GV) {
1033 SI->eraseFromParent();
1034 continue;
1035 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001036 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1037 // Insert the load in the corresponding predecessor, not right before the
1038 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001039 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001040 } else if (isa<BitCastInst>(U)) {
1041 // Must be bitcast between the malloc and store to initialize the global.
1042 ReplaceUsesOfMallocWithGlobal(U, GV);
1043 U->eraseFromParent();
1044 continue;
1045 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1046 // If this is a "GEP bitcast" and the user is a store to the global, then
1047 // just process it as a bitcast.
1048 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1049 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1050 if (SI->getOperand(1) == GV) {
1051 // Must be bitcast GEP between the malloc and store to initialize
1052 // the global.
1053 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1054 GEPI->eraseFromParent();
1055 continue;
1056 }
Chris Lattner86395032006-09-30 23:32:09 +00001057 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001058
Chris Lattner86395032006-09-30 23:32:09 +00001059 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001060 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001061 U->replaceUsesOfWith(Alloc, NL);
1062 }
1063}
1064
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001065/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1066/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1067/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001068static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001069 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1070 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001071 // We permit two users of the load: setcc comparing against the null
1072 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001073 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1074 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001075 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001076
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001077 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001078 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001079 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1080 return false;
1081 continue;
1082 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001083
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001084 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001085 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001086 // Must index into the array and into the struct.
1087 if (GEPI->getNumOperands() < 3)
1088 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001089
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001090 // Otherwise the GEP is ok.
1091 continue;
1092 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001093
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001094 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001095 if (!LoadUsingPHIsPerLoad.insert(PN))
1096 // This means some phi nodes are dependent on each other.
1097 // Avoid infinite looping!
1098 return false;
1099 if (!LoadUsingPHIs.insert(PN))
1100 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001101 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001102
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001103 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001104 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1105 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001106 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001107
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001108 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001109 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001110
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001111 // Otherwise we don't know what this is, not ok.
1112 return false;
1113 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001114
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001115 return true;
1116}
1117
1118
1119/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1120/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001121static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001122 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001123 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1124 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001125 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1126 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001127 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001128 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1129 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001130 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001131 LoadUsingPHIsPerLoad.clear();
1132 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001133
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001134 // If we reach here, we know that all uses of the loads and transitive uses
1135 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001136 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001137 // Check to verify that all operands of the PHIs are either PHIS that can be
1138 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001139 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1140 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001141 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001142 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1143 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001144
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001145 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001146 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001147
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001148 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001149 // One of the PHIs in our set is (optimistically) ok.
1150 if (LoadUsingPHIs.count(InPN))
1151 continue;
1152 return false;
1153 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001154
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001155 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001156 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001157 if (LI->getOperand(0) == GV)
1158 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001159
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001160 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001161
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001162 // Anything else is rejected.
1163 return false;
1164 }
1165 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001166
Chris Lattner86395032006-09-30 23:32:09 +00001167 return true;
1168}
1169
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001170static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1171 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001172 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001173 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001174
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001175 if (FieldNo >= FieldVals.size())
1176 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001177
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001178 // If we already have this value, just reuse the previously scalarized
1179 // version.
1180 if (Value *FieldVal = FieldVals[FieldNo])
1181 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001182
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001183 // Depending on what instruction this is, we have several cases.
1184 Value *Result;
1185 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1186 // This is a scalarized version of the load from the global. Just create
1187 // a new Load of the scalarized global.
1188 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1189 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001190 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001191 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001192 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1193 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1194 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001195 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001196 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001197
Jay Foadd8b4fb42011-03-30 11:19:20 +00001198 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001199 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001200 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001201 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001202 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001203 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1204 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001205 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001206 Result = 0;
1207 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001208
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001209 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001210}
1211
Chris Lattner330245e2007-09-13 17:29:05 +00001212/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1213/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001214static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001215 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001216 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001217 // If this is a comparison against null, handle it.
1218 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1219 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1220 // If we have a setcc of the loaded pointer, we can use a setcc of any
1221 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001222 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001223 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001224
Owen Anderson333c4002009-07-09 23:48:35 +00001225 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001226 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001227 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001228 SCI->replaceAllUsesWith(New);
1229 SCI->eraseFromParent();
1230 return;
1231 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001232
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001233 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001234 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1235 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1236 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001237
Chris Lattnera637a8b2007-09-13 18:00:31 +00001238 // Load the pointer for this field.
1239 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001240 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001241 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001242
Chris Lattnera637a8b2007-09-13 18:00:31 +00001243 // Create the new GEP idx vector.
1244 SmallVector<Value*, 8> GEPIdx;
1245 GEPIdx.push_back(GEPI->getOperand(1));
1246 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001247
Jay Foada9203102011-07-25 09:48:08 +00001248 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001249 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001250 GEPI->replaceAllUsesWith(NGEPI);
1251 GEPI->eraseFromParent();
1252 return;
1253 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001254
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001255 // Recursively transform the users of PHI nodes. This will lazily create the
1256 // PHIs that are needed for individual elements. Keep track of what PHIs we
1257 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1258 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1259 // already been seen first by another load, so its uses have already been
1260 // processed.
1261 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001262 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1263 std::vector<Value*>())).second)
1264 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001265
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001266 // If this is the first time we've seen this PHI, recursively process all
1267 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001268 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1269 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001270 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001271 }
Chris Lattner330245e2007-09-13 17:29:05 +00001272}
1273
Chris Lattner86395032006-09-30 23:32:09 +00001274/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1275/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1276/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001277/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001278static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001279 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001280 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001281 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001282 UI != E; ) {
1283 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001284 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001285 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001286
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001287 if (Load->use_empty()) {
1288 Load->eraseFromParent();
1289 InsertedScalarizedValues.erase(Load);
1290 }
Chris Lattner86395032006-09-30 23:32:09 +00001291}
1292
Victor Hernandez83d63912009-09-18 22:35:49 +00001293/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1294/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001295static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1296 Value* NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001297 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001298 Type* MAT = getMallocAllocatedType(CI);
1299 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001300
1301 // There is guaranteed to be at least one use of the malloc (storing
1302 // it into GV). If there are other uses, change them to be uses of
1303 // the global to simplify later code. This also deletes the store
1304 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001305 ReplaceUsesOfMallocWithGlobal(CI, GV);
1306
Victor Hernandez83d63912009-09-18 22:35:49 +00001307 // Okay, at this point, there are no users of the malloc. Insert N
1308 // new mallocs at the same place as CI, and N globals.
1309 std::vector<Value*> FieldGlobals;
1310 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001311
Victor Hernandez83d63912009-09-18 22:35:49 +00001312 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001313 Type *FieldTy = STy->getElementType(FieldNo);
1314 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001315
Victor Hernandez83d63912009-09-18 22:35:49 +00001316 GlobalVariable *NGV =
1317 new GlobalVariable(*GV->getParent(),
1318 PFieldTy, false, GlobalValue::InternalLinkage,
1319 Constant::getNullValue(PFieldTy),
1320 GV->getName() + ".f" + Twine(FieldNo), GV,
1321 GV->isThreadLocal());
1322 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001323
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001324 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001325 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001326 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001327 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001328 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1329 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001330 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001331 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001332 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001333 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001334 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001335
Victor Hernandez83d63912009-09-18 22:35:49 +00001336 // The tricky aspect of this transformation is handling the case when malloc
1337 // fails. In the original code, malloc failing would set the result pointer
1338 // of malloc to null. In this case, some mallocs could succeed and others
1339 // could fail. As such, we emit code that looks like this:
1340 // F0 = malloc(field0)
1341 // F1 = malloc(field1)
1342 // F2 = malloc(field2)
1343 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1344 // if (F0) { free(F0); F0 = 0; }
1345 // if (F1) { free(F1); F1 = 0; }
1346 // if (F2) { free(F2); F2 = 0; }
1347 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001348 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001349 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1350 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001351 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001352 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001353 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1354 Constant::getNullValue(FieldMallocs[i]->getType()),
1355 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001356 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001357 }
1358
1359 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001360 BasicBlock *OrigBB = CI->getParent();
1361 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001362
Victor Hernandez83d63912009-09-18 22:35:49 +00001363 // Create the block to check the first condition. Put all these blocks at the
1364 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001365 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1366 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001367 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001368
Victor Hernandez83d63912009-09-18 22:35:49 +00001369 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1370 // branch on RunningOr.
1371 OrigBB->getTerminator()->eraseFromParent();
1372 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001373
Victor Hernandez83d63912009-09-18 22:35:49 +00001374 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1375 // pointer, because some may be null while others are not.
1376 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1377 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001378 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Victor Hernandez83d63912009-09-18 22:35:49 +00001379 Constant::getNullValue(GVVal->getType()),
1380 "tmp");
Chris Lattner7b550cc2009-11-06 04:27:31 +00001381 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001382 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001383 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001384 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001385 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1386 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001387
1388 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001389 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001390 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1391 FreeBlock);
1392 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001393
Victor Hernandez83d63912009-09-18 22:35:49 +00001394 NullPtrBlock = NextBlock;
1395 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001396
Victor Hernandez83d63912009-09-18 22:35:49 +00001397 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001398
1399 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001400 CI->eraseFromParent();
1401
1402 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1403 /// update all uses of the load, keep track of what scalarized loads are
1404 /// inserted for a given load.
1405 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1406 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001407
Victor Hernandez83d63912009-09-18 22:35:49 +00001408 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001409
Victor Hernandez83d63912009-09-18 22:35:49 +00001410 // Okay, the malloc site is completely handled. All of the uses of GV are now
1411 // loads, and all uses of those loads are simple. Rewrite them to use loads
1412 // of the per-field globals instead.
1413 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1414 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001415
Victor Hernandez83d63912009-09-18 22:35:49 +00001416 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001417 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001418 continue;
1419 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001420
Victor Hernandez83d63912009-09-18 22:35:49 +00001421 // Must be a store of null.
1422 StoreInst *SI = cast<StoreInst>(User);
1423 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1424 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001425
Victor Hernandez83d63912009-09-18 22:35:49 +00001426 // Insert a store of null into each global.
1427 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001428 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001429 Constant *Null = Constant::getNullValue(PT->getElementType());
1430 new StoreInst(Null, FieldGlobals[i], SI);
1431 }
1432 // Erase the original store.
1433 SI->eraseFromParent();
1434 }
1435
1436 // While we have PHIs that are interesting to rewrite, do it.
1437 while (!PHIsToRewrite.empty()) {
1438 PHINode *PN = PHIsToRewrite.back().first;
1439 unsigned FieldNo = PHIsToRewrite.back().second;
1440 PHIsToRewrite.pop_back();
1441 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1442 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1443
1444 // Add all the incoming values. This can materialize more phis.
1445 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1446 Value *InVal = PN->getIncomingValue(i);
1447 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001448 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001449 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1450 }
1451 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001452
Victor Hernandez83d63912009-09-18 22:35:49 +00001453 // Drop all inter-phi links and any loads that made it this far.
1454 for (DenseMap<Value*, std::vector<Value*> >::iterator
1455 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1456 I != E; ++I) {
1457 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1458 PN->dropAllReferences();
1459 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1460 LI->dropAllReferences();
1461 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001462
Victor Hernandez83d63912009-09-18 22:35:49 +00001463 // Delete all the phis and loads now that inter-references are dead.
1464 for (DenseMap<Value*, std::vector<Value*> >::iterator
1465 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1466 I != E; ++I) {
1467 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1468 PN->eraseFromParent();
1469 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1470 LI->eraseFromParent();
1471 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001472
Victor Hernandez83d63912009-09-18 22:35:49 +00001473 // The old global is now dead, remove it.
1474 GV->eraseFromParent();
1475
1476 ++NumHeapSRA;
1477 return cast<GlobalVariable>(FieldGlobals[0]);
1478}
1479
Chris Lattnere61d0a62008-12-15 21:02:25 +00001480/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1481/// pointer global variable with a single value stored it that is a malloc or
1482/// cast of malloc.
1483static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001484 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001485 Type *AllocTy,
Victor Hernandez83d63912009-09-18 22:35:49 +00001486 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001487 TargetData *TD) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001488 if (!TD)
1489 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001490
Victor Hernandez83d63912009-09-18 22:35:49 +00001491 // If this is a malloc of an abstract type, don't touch it.
1492 if (!AllocTy->isSized())
1493 return false;
1494
1495 // We can't optimize this global unless all uses of it are *known* to be
1496 // of the malloc value, not of the null initializer value (consider a use
1497 // that compares the global's value against zero to see if the malloc has
1498 // been reached). To do this, we check to see if all uses of the global
1499 // would trap if the global were null: this proves that they must all
1500 // happen after the malloc.
1501 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1502 return false;
1503
1504 // We can't optimize this if the malloc itself is used in a complex way,
1505 // for example, being stored into multiple globals. This allows the
1506 // malloc to be stored into the specified global, loaded setcc'd, and
1507 // GEP'd. These are all things we could transform to using the global
1508 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001509 SmallPtrSet<const PHINode*, 8> PHIs;
1510 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1511 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001512
1513 // If we have a global that is only initialized with a fixed size malloc,
1514 // transform the program to use global memory instead of malloc'd memory.
1515 // This eliminates dynamic allocation, avoids an indirection accessing the
1516 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001517 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001518 Value *NElems = getMallocArraySize(CI, TD, true);
1519 if (!NElems)
1520 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001521
Evan Cheng86cd4452010-04-14 20:52:55 +00001522 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1523 // Restrict this transformation to only working on small allocations
1524 // (2048 bytes currently), as we don't want to introduce a 16M global or
1525 // something.
1526 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1527 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1528 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001529 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001530
Evan Cheng86cd4452010-04-14 20:52:55 +00001531 // If the allocation is an array of structures, consider transforming this
1532 // into multiple malloc'd arrays, one for each field. This is basically
1533 // SRoA for malloc'd memory.
1534
1535 // If this is an allocation of a fixed size array of structs, analyze as a
1536 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001537 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001538 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001539 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001540
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001541 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001542 if (!AllocSTy)
1543 return false;
1544
1545 // This the structure has an unreasonable number of fields, leave it
1546 // alone.
1547 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1548 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1549
1550 // If this is a fixed size array, transform the Malloc to be an alloc of
1551 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001552 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1553 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001554 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1555 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1556 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1557 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1558 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001559 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001560 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1561 CI->replaceAllUsesWith(Cast);
1562 CI->eraseFromParent();
1563 CI = dyn_cast<BitCastInst>(Malloc) ?
1564 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1565 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001566
Evan Cheng86cd4452010-04-14 20:52:55 +00001567 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1568 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001569 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001570
Victor Hernandez83d63912009-09-18 22:35:49 +00001571 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001572}
Victor Hernandez83d63912009-09-18 22:35:49 +00001573
Chris Lattner9b34a612004-10-09 21:48:45 +00001574// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1575// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001576static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001577 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001578 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001579 // Ignore no-op GEPs and bitcasts.
1580 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001581
Chris Lattner708148e2004-10-10 23:14:11 +00001582 // If we are dealing with a pointer global that is initialized to null and
1583 // only has one (non-null) value stored into it, then we can optimize any
1584 // users of the loaded value (often calls and loads) that would trap if the
1585 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001586 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001587 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001588 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1589 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001590 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001591
Chris Lattner708148e2004-10-10 23:14:11 +00001592 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001593 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001594 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001595 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001596 Type* MallocType = getMallocAllocatedType(CI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001597 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001598 GVI, TD))
1599 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001600 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001601 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001602
Chris Lattner9b34a612004-10-09 21:48:45 +00001603 return false;
1604}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001605
Chris Lattner58e44f42008-01-14 01:17:44 +00001606/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1607/// two values ever stored into GV are its initializer and OtherVal. See if we
1608/// can shrink the global into a boolean and select between the two values
1609/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001610static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001611 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001612
Chris Lattner58e44f42008-01-14 01:17:44 +00001613 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001614 // an FP value, pointer or vector, don't do this optimization because a select
1615 // between them is very expensive and unlikely to lead to later
1616 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1617 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001618 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001619 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001620 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001621 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001622
Chris Lattner58e44f42008-01-14 01:17:44 +00001623 // Walk the use list of the global seeing if all the uses are load or store.
1624 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001625 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1626 User *U = *I;
1627 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001628 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001629 }
1630
David Greene3215b0e2010-01-05 01:28:05 +00001631 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001632
Chris Lattner96a86b22004-12-12 05:53:50 +00001633 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001634 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1635 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001636 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001637 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001638 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001639 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001640 GV->getParent()->getGlobalList().insert(GV, NewGV);
1641
1642 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001643 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001644 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001645
1646 // If initialized to zero and storing one into the global, we can use a cast
1647 // instead of a select to synthesize the desired value.
1648 bool IsOneZero = false;
1649 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001650 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001651
1652 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001653 Instruction *UI = cast<Instruction>(GV->use_back());
1654 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001655 // Change the store into a boolean store.
1656 bool StoringOther = SI->getOperand(0) == OtherVal;
1657 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001658 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001659 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001660 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1661 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001662 else {
1663 // Otherwise, we are storing a previously loaded copy. To do this,
1664 // change the copy from copying the original value to just copying the
1665 // bool.
1666 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1667
Gabor Greif9e4f2432010-06-24 14:42:01 +00001668 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001669 // select instruction. If not, it will be a load of the original
1670 // global.
1671 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1672 assert(LI->getOperand(0) == GV && "Not a copy!");
1673 // Insert a new load, to preserve the saved value.
1674 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1675 } else {
1676 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1677 "This is not a form that we understand!");
1678 StoreVal = StoredVal->getOperand(0);
1679 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1680 }
1681 }
1682 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001683 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001684 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001685 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001686 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001687 Value *NSI;
1688 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001689 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001690 else
Gabor Greif051a9502008-04-06 20:25:17 +00001691 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001692 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001693 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001694 }
1695 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001696 }
1697
1698 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001699 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001700}
1701
1702
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001703/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1704/// it if possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001705bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1706 Module::global_iterator &GVI) {
1707 if (!GV->hasLocalLinkage())
1708 return false;
1709
1710 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001711 GV->removeDeadConstantUsers();
1712
1713 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001714 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001715 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001716 ++NumDeleted;
1717 return true;
1718 }
1719
Rafael Espindolac4440e32011-01-19 16:32:21 +00001720 SmallPtrSet<const PHINode*, 16> PHIUsers;
1721 GlobalStatus GS;
1722
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001723 if (AnalyzeGlobal(GV, GS, PHIUsers))
1724 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001725
Rafael Espindolac4440e32011-01-19 16:32:21 +00001726 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1727 GV->setUnnamedAddr(true);
1728 NumUnnamed++;
1729 }
1730
1731 if (GV->isConstant() || !GV->hasInitializer())
1732 return false;
1733
1734 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1735}
1736
1737/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1738/// it if possible. If we make a change, return true.
1739bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1740 Module::global_iterator &GVI,
1741 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
1742 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001743 // If this is a first class global and has only one accessing function
1744 // and this function is main (which we know is not recursive we can make
1745 // this global a local variable) we replace the global with a local alloca
1746 // in this function.
1747 //
1748 // NOTE: It doesn't make sense to promote non single-value types since we
1749 // are just replacing static memory to stack memory.
1750 //
1751 // If the global is in different address space, don't bring it to stack.
1752 if (!GS.HasMultipleAccessingFunctions &&
1753 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1754 GV->getType()->getElementType()->isSingleValueType() &&
1755 GS.AccessingFunction->getName() == "main" &&
1756 GS.AccessingFunction->hasExternalLinkage() &&
1757 GV->getType()->getAddressSpace() == 0) {
1758 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1759 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1760 ->getEntryBlock().begin());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001761 Type* ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001762 // FIXME: Pass Global's alignment when globals have alignment
1763 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1764 if (!isa<UndefValue>(GV->getInitializer()))
1765 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001766
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001767 GV->replaceAllUsesWith(Alloca);
1768 GV->eraseFromParent();
1769 ++NumLocalized;
1770 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001771 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001772
1773 // If the global is never loaded (but may be stored to), it is dead.
1774 // Delete it now.
1775 if (!GS.isLoaded) {
1776 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1777
1778 // Delete any stores we can find to the global. We may not be able to
1779 // make it completely dead though.
1780 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1781
1782 // If the global is dead now, delete it.
1783 if (GV->use_empty()) {
1784 GV->eraseFromParent();
1785 ++NumDeleted;
1786 Changed = true;
1787 }
1788 return Changed;
1789
1790 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1791 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1792 GV->setConstant(true);
1793
1794 // Clean up any obviously simplifiable users now.
1795 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1796
1797 // If the global is dead now, just nuke it.
1798 if (GV->use_empty()) {
1799 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1800 << "all users and delete global!\n");
1801 GV->eraseFromParent();
1802 ++NumDeleted;
1803 }
1804
1805 ++NumMarked;
1806 return true;
1807 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1808 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1809 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1810 GVI = FirstNewGV; // Don't skip the newly produced globals!
1811 return true;
1812 }
1813 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1814 // If the initial value for the global was an undef value, and if only
1815 // one other value was stored into it, we can just change the
1816 // initializer to be the stored value, then delete all stores to the
1817 // global. This allows us to mark it constant.
1818 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1819 if (isa<UndefValue>(GV->getInitializer())) {
1820 // Change the initial value here.
1821 GV->setInitializer(SOVConstant);
1822
1823 // Clean up any obviously simplifiable users now.
1824 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1825
1826 if (GV->use_empty()) {
1827 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1828 << "simplify all users and delete global!\n");
1829 GV->eraseFromParent();
1830 ++NumDeleted;
1831 } else {
1832 GVI = GV;
1833 }
1834 ++NumSubstitute;
1835 return true;
1836 }
1837
1838 // Try to optimize globals based on the knowledge that only one value
1839 // (besides its initializer) is ever stored to the global.
1840 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1841 getAnalysisIfAvailable<TargetData>()))
1842 return true;
1843
1844 // Otherwise, if the global was not a boolean, we can shrink it to be a
1845 // boolean.
1846 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1847 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1848 ++NumShrunkToBool;
1849 return true;
1850 }
1851 }
1852
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001853 return false;
1854}
1855
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001856/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1857/// function, changing them to FastCC.
1858static void ChangeCalleesToFastCall(Function *F) {
1859 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001860 CallSite User(cast<Instruction>(*UI));
1861 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001862 }
1863}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001864
Devang Patel05988662008-09-25 21:00:45 +00001865static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001866 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001867 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001868 continue;
1869
Duncan Sands548448a2008-02-18 17:32:13 +00001870 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001871 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001872 }
1873
1874 return Attrs;
1875}
1876
1877static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001878 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001879 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001880 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001881 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001882 }
1883}
1884
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001885bool GlobalOpt::OptimizeFunctions(Module &M) {
1886 bool Changed = false;
1887 // Optimize functions.
1888 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1889 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001890 // Functions without names cannot be referenced outside this module.
1891 if (!F->hasName() && !F->isDeclaration())
1892 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001893 F->removeDeadConstantUsers();
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001894 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1895 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001896 Changed = true;
1897 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001898 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001899 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001900 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001901 // If this function has C calling conventions, is not a varargs
1902 // function, and is only called directly, promote it to use the Fast
1903 // calling convention.
1904 F->setCallingConv(CallingConv::Fast);
1905 ChangeCalleesToFastCall(F);
1906 ++NumFastCallFns;
1907 Changed = true;
1908 }
1909
Devang Patel05988662008-09-25 21:00:45 +00001910 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001911 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001912 // The function is not used by a trampoline intrinsic, so it is safe
1913 // to remove the 'nest' attribute.
1914 RemoveNestAttribute(F);
1915 ++NumNestRemoved;
1916 Changed = true;
1917 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001918 }
1919 }
1920 return Changed;
1921}
1922
1923bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1924 bool Changed = false;
1925 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1926 GVI != E; ) {
1927 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001928 // Global variables without names cannot be referenced outside this module.
1929 if (!GV->hasName() && !GV->isDeclaration())
1930 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001931 // Simplify the initializer.
1932 if (GV->hasInitializer())
1933 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohmanf860db22010-04-02 03:04:37 +00001934 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman01b97dd2009-11-23 16:22:21 +00001935 Constant *New = ConstantFoldConstantExpression(CE, TD);
1936 if (New && New != CE)
1937 GV->setInitializer(New);
1938 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001939
1940 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001941 }
1942 return Changed;
1943}
1944
Nick Lewycky2c44a802011-04-08 07:30:21 +00001945/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001946/// initializers have an init priority of 65535.
1947GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001948 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1949 if (GV == 0) return 0;
1950
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001951 // Verify that the initializer is simple enough for us to handle. We are
1952 // only allowed to optimize the initializer if it is unique.
1953 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001954
1955 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1956 return GV;
1957 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00001958
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001959 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001960 if (isa<ConstantAggregateZero>(*i))
1961 continue;
1962 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001963 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1964 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001965
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001966 // Must have a function or null ptr.
1967 if (!isa<Function>(CS->getOperand(1)))
1968 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001969
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001970 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001971 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1972 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001973 return 0;
1974 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001975
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001976 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001977}
1978
Chris Lattnerdb973e62005-09-26 02:31:18 +00001979/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1980/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001981static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001982 if (GV->getInitializer()->isNullValue())
1983 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001984 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1985 std::vector<Function*> Result;
1986 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001987 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1988 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001989 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1990 }
1991 return Result;
1992}
1993
Chris Lattnerdb973e62005-09-26 02:31:18 +00001994/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1995/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001996static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001997 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001998 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00001999 Constant *CSVals[2];
2000 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2001 CSVals[1] = 0;
2002
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002003 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002004 cast <StructType>(
2005 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002006
Chris Lattnerdb973e62005-09-26 02:31:18 +00002007 // Create the new init list.
2008 std::vector<Constant*> CAList;
2009 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002010 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002011 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002012 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002013 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002014 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002015 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002016 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002017 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002018 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002019 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002020 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002021 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002022
Chris Lattnerdb973e62005-09-26 02:31:18 +00002023 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002024 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002025 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002026
Chris Lattnerdb973e62005-09-26 02:31:18 +00002027 // If we didn't change the number of elements, don't create a new GV.
2028 if (CA->getType() == GCL->getInitializer()->getType()) {
2029 GCL->setInitializer(CA);
2030 return GCL;
2031 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002032
Chris Lattnerdb973e62005-09-26 02:31:18 +00002033 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002034 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002035 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002036 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002037 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002038 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002039
Chris Lattnerdb973e62005-09-26 02:31:18 +00002040 // Nuke the old list, replacing any uses with the new one.
2041 if (!GCL->use_empty()) {
2042 Constant *V = NGV;
2043 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002044 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002045 GCL->replaceAllUsesWith(V);
2046 }
2047 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002048
Chris Lattnerdb973e62005-09-26 02:31:18 +00002049 if (Ctors.size())
2050 return NGV;
2051 else
2052 return 0;
2053}
Chris Lattner79c11012005-09-26 04:44:35 +00002054
2055
Chris Lattner1945d582010-12-07 04:33:29 +00002056static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
Chris Lattner79c11012005-09-26 04:44:35 +00002057 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2058 Constant *R = ComputedValues[V];
2059 assert(R && "Reference to an uncomputed value!");
2060 return R;
2061}
2062
Chris Lattner1945d582010-12-07 04:33:29 +00002063static inline bool
2064isSimpleEnoughValueToCommit(Constant *C,
2065 SmallPtrSet<Constant*, 8> &SimpleConstants);
2066
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,
2077 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2078 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2079 // all supported.
2080 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2081 isa<GlobalValue>(C))
2082 return true;
2083
2084 // Aggregate values are safe if all their elements are.
2085 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2086 isa<ConstantVector>(C)) {
2087 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2088 Constant *Op = cast<Constant>(C->getOperand(i));
2089 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants))
2090 return false;
2091 }
2092 return true;
2093 }
2094
2095 // We don't know exactly what relocations are allowed in constant expressions,
2096 // so we allow &global+constantoffset, which is safe and uniformly supported
2097 // across targets.
2098 ConstantExpr *CE = cast<ConstantExpr>(C);
2099 switch (CE->getOpcode()) {
2100 case Instruction::BitCast:
2101 case Instruction::IntToPtr:
2102 case Instruction::PtrToInt:
2103 // These casts are always fine if the casted value is.
2104 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2105
2106 // GEP is fine if it is simple + constant offset.
2107 case Instruction::GetElementPtr:
2108 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2109 if (!isa<ConstantInt>(CE->getOperand(i)))
2110 return false;
2111 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2112
2113 case Instruction::Add:
2114 // We allow simple+cst.
2115 if (!isa<ConstantInt>(CE->getOperand(1)))
2116 return false;
2117 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2118 }
2119 return false;
2120}
2121
2122static inline bool
2123isSimpleEnoughValueToCommit(Constant *C,
2124 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2125 // If we already checked this constant, we win.
2126 if (!SimpleConstants.insert(C)) return true;
2127 // Check the constant.
2128 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants);
2129}
2130
2131
Chris Lattner79c11012005-09-26 04:44:35 +00002132/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002133/// enough for us to understand. In particular, if it is a cast to anything
2134/// other than from one pointer type to another pointer type, we punt.
2135/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002136/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002137static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002138 // Conservatively, avoid aggregate types. This is because we don't
2139 // want to worry about them partially overlapping other stores.
2140 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2141 return false;
2142
Dan Gohmanfd54a892009-09-07 22:31:26 +00002143 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002144 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002145 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002146 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002147
Owen Andersone95a32c2011-01-14 22:31:13 +00002148 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002149 // Handle a constantexpr gep.
2150 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002151 isa<GlobalVariable>(CE->getOperand(0)) &&
2152 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002153 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002154 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002155 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002156 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002157 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002158
Dan Gohman80bdc962009-09-07 22:44:55 +00002159 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002160 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002161 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002162
2163 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002164 // notional bounds of the corresponding static array types.
2165 if (!CE->isGEPWithNoNotionalOverIndexing())
2166 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002167
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002168 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002169
2170 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2171 // and we know how to evaluate it by moving the bitcast from the pointer
2172 // operand to the value operand.
2173 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002174 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002175 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2176 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002177 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002178 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002179 }
2180
Chris Lattner79c11012005-09-26 04:44:35 +00002181 return false;
2182}
2183
Chris Lattner798b4d52005-09-26 06:52:44 +00002184/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2185/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2186/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2187static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002188 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002189 // Base case of the recursion.
2190 if (OpNo == Addr->getNumOperands()) {
2191 assert(Val->getType() == Init->getType() && "Type mismatch!");
2192 return Val;
2193 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002194
Chris Lattnera0e9a242010-01-07 01:16:21 +00002195 std::vector<Constant*> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002196 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002197
2198 // Break up the constant into its elements.
2199 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002200 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2201 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002202 } else if (isa<ConstantAggregateZero>(Init)) {
2203 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002204 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002205 } else if (isa<UndefValue>(Init)) {
2206 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002207 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002208 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002209 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002210 " ConstantFoldLoadThroughGEPConstantExpr");
2211 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002212
Chris Lattner798b4d52005-09-26 06:52:44 +00002213 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002214 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2215 unsigned Idx = CU->getZExtValue();
2216 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002217 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002218
Chris Lattner798b4d52005-09-26 06:52:44 +00002219 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002220 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002221 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002222
2223 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002224 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002225
2226 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002227 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002228 NumElts = ATy->getNumElements();
2229 else
2230 NumElts = cast<VectorType>(InitTy)->getNumElements();
2231
2232 // Break up the array into elements.
2233 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2234 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2235 Elts.push_back(cast<Constant>(*i));
2236 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2237 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2238 Elts.push_back(cast<Constant>(*i));
2239 } else if (isa<ConstantAggregateZero>(Init)) {
2240 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
2241 } else {
2242 assert(isa<UndefValue>(Init) && "This code is out of sync with "
2243 " ConstantFoldLoadThroughGEPConstantExpr");
2244 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
2245 }
2246
2247 assert(CI->getZExtValue() < NumElts);
2248 Elts[CI->getZExtValue()] =
2249 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2250
2251 if (Init->getType()->isArrayTy())
2252 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2253 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002254}
2255
Chris Lattner79c11012005-09-26 04:44:35 +00002256/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2257/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002258static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002259 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2260 assert(GV->hasInitializer());
2261 GV->setInitializer(Val);
2262 return;
2263 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002264
Chris Lattner798b4d52005-09-26 06:52:44 +00002265 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2266 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002267 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002268}
2269
Chris Lattner562a0552005-09-26 05:16:34 +00002270/// ComputeLoadResult - Return the value that would be computed by a load from
2271/// P after the stores reflected by 'memory' have been performed. If we can't
2272/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002273static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002274 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002275 // If this memory location has been recently stored, use the stored value: it
2276 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002277 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002278 if (I != Memory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002279
Chris Lattner04de1cf2005-09-26 05:15:37 +00002280 // Access it.
2281 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002282 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002283 return GV->getInitializer();
2284 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002285 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002286
Chris Lattner798b4d52005-09-26 06:52:44 +00002287 // Handle a constantexpr getelementptr.
2288 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2289 if (CE->getOpcode() == Instruction::GetElementPtr &&
2290 isa<GlobalVariable>(CE->getOperand(0))) {
2291 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002292 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002293 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002294 }
2295
2296 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002297}
2298
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002299/// EvaluateFunction - Evaluate a call to function F, returning true if
2300/// successful, false if we can't evaluate it. ActualArgs contains the formal
2301/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002302static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002303 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002304 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002305 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner1945d582010-12-07 04:33:29 +00002306 std::vector<GlobalVariable*> &AllocaTmps,
2307 SmallPtrSet<Constant*, 8> &SimpleConstants,
2308 const TargetData *TD) {
Chris Lattnercd271422005-09-27 04:45:34 +00002309 // Check to see if this function is already executing (recursion). If so,
2310 // bail out. TODO: we might want to accept limited recursion.
2311 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2312 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002313
Chris Lattnercd271422005-09-27 04:45:34 +00002314 CallStack.push_back(F);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002315
Chris Lattner79c11012005-09-26 04:44:35 +00002316 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002317 DenseMap<Value*, Constant*> Values;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002318
Chris Lattnercd271422005-09-27 04:45:34 +00002319 // Initialize arguments to the incoming values specified.
2320 unsigned ArgNo = 0;
2321 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2322 ++AI, ++ArgNo)
2323 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002324
Chris Lattnercdf98be2005-09-26 04:57:38 +00002325 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2326 /// we can only evaluate any one basic block at most once. This set keeps
2327 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002328 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002329
Chris Lattner79c11012005-09-26 04:44:35 +00002330 // CurInst - The current instruction we're evaluating.
2331 BasicBlock::iterator CurInst = F->begin()->begin();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002332
Chris Lattner79c11012005-09-26 04:44:35 +00002333 // This is the main evaluation loop.
2334 while (1) {
2335 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002336
Chris Lattner79c11012005-09-26 04:44:35 +00002337 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002338 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002339 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002340 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002341 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002342 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002343
Chris Lattner79c11012005-09-26 04:44:35 +00002344 Constant *Val = getVal(Values, SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002345
2346 // If this might be too difficult for the backend to handle (e.g. the addr
2347 // of one global variable divided by another) then we can't commit it.
2348 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants))
2349 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002350
2351 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2352 if (CE->getOpcode() == Instruction::BitCast) {
2353 // If we're evaluating a store through a bitcast, then we need
2354 // to pull the bitcast off the pointer type and push it onto the
2355 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002356 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002357
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002358 Type *NewTy=cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002359
Owen Anderson66f708f2011-01-16 04:33:33 +00002360 // In order to push the bitcast onto the stored value, a bitcast
2361 // from NewTy to Val's type must be legal. If it's not, we can try
2362 // introspecting NewTy to find a legal conversion.
2363 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2364 // If NewTy is a struct, we can convert the pointer to the struct
2365 // into a pointer to its first member.
2366 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002367 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002368 NewTy = STy->getTypeAtIndex(0U);
2369
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002370 IntegerType *IdxTy =IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002371 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2372 Constant * const IdxList[] = {IdxZero, IdxZero};
2373
Jay Foadb4263a62011-07-22 08:52:50 +00002374 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Owen Andersoncff6b372011-01-14 22:19:20 +00002375
Owen Anderson66f708f2011-01-16 04:33:33 +00002376 // If we can't improve the situation by introspecting NewTy,
2377 // we have to give up.
2378 } else {
2379 return 0;
2380 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002381 }
2382
Owen Anderson66f708f2011-01-16 04:33:33 +00002383 // If we found compatible types, go ahead and push the bitcast
2384 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002385 Val = ConstantExpr::getBitCast(Val, NewTy);
2386 }
2387
Chris Lattner79c11012005-09-26 04:44:35 +00002388 MutatedMemory[Ptr] = Val;
2389 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002390 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002391 getVal(Values, BO->getOperand(0)),
2392 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002393 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002394 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002395 getVal(Values, CI->getOperand(0)),
2396 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002397 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002398 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002399 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002400 CI->getType());
2401 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +00002402 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Eric Christopher551754c2010-04-16 23:37:20 +00002403 getVal(Values, SI->getOperand(1)),
2404 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002405 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2406 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002407 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002408 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2409 i != e; ++i)
2410 GEPOps.push_back(getVal(Values, *i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002411 InstResult =
2412 ConstantExpr::getGetElementPtr(P, GEPOps,
2413 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002414 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002415 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002416 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002417 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002418 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002419 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002420 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002421 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002422 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002423 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002424 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002425 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002426 InstResult = AllocaTmps.back();
Chris Lattnercd271422005-09-27 04:45:34 +00002427 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002428
2429 // Debug info can safely be ignored here.
2430 if (isa<DbgInfoIntrinsic>(CI)) {
2431 ++CurInst;
2432 continue;
2433 }
2434
Chris Lattner7cd580f2006-07-07 21:37:01 +00002435 // Cannot handle inline asm.
Gabor Greifa9b23132010-04-20 13:13:04 +00002436 if (isa<InlineAsm>(CI->getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002437
Nick Lewycky1f237b02011-05-29 18:41:56 +00002438 if (MemSetInst *MSI = dyn_cast<MemSetInst>(CI)) {
2439 if (MSI->isVolatile()) return false;
2440 Constant *Ptr = getVal(Values, MSI->getDest());
2441 Constant *Val = getVal(Values, MSI->getValue());
2442 Constant *DestVal = ComputeLoadResult(getVal(Values, Ptr),
2443 MutatedMemory);
Nick Lewyckybcb85082011-05-29 19:33:36 +00002444 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
Nick Lewycky1f237b02011-05-29 18:41:56 +00002445 // This memset is a no-op.
2446 ++CurInst;
2447 continue;
2448 }
2449 return false;
2450 }
2451
Chris Lattnercd271422005-09-27 04:45:34 +00002452 // Resolve function pointers.
Gabor Greifa3997812010-07-22 10:37:47 +00002453 Function *Callee = dyn_cast<Function>(getVal(Values,
2454 CI->getCalledValue()));
Chris Lattnercd271422005-09-27 04:45:34 +00002455 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002456
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002457 SmallVector<Constant*, 8> Formals;
Gabor Greif9e4f2432010-06-24 14:42:01 +00002458 CallSite CS(CI);
2459 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
Gabor Greif5e463212008-05-29 01:59:18 +00002460 i != e; ++i)
2461 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002462
Reid Spencer5cbf9852007-01-30 20:08:39 +00002463 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002464 // If this is a function we can constant fold, do it.
Jay Foad1d2f5692011-07-19 13:32:40 +00002465 if (Constant *C = ConstantFoldCall(Callee, Formals)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002466 InstResult = C;
2467 } else {
2468 return false;
2469 }
2470 } else {
2471 if (Callee->getFunctionType()->isVarArg())
2472 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002473
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002474 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002475 // Execute the call, if successful, use the return value.
2476 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002477 MutatedMemory, AllocaTmps, SimpleConstants, TD))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002478 return false;
2479 InstResult = RetVal;
2480 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002481 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002482 BasicBlock *NewBB = 0;
2483 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2484 if (BI->isUnconditional()) {
2485 NewBB = BI->getSuccessor(0);
2486 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002487 ConstantInt *Cond =
2488 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002489 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002490
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002491 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002492 }
2493 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2494 ConstantInt *Val =
2495 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002496 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002497 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002498 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2499 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2500 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2501 NewBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002502 else
2503 return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002504 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002505 if (RI->getNumOperands())
2506 RetVal = getVal(Values, RI->getOperand(0));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002507
Chris Lattnercd271422005-09-27 04:45:34 +00002508 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002509 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002510 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002511 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002512 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002513 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002514
Chris Lattnercdf98be2005-09-26 04:57:38 +00002515 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002516 // executed the new block before. If so, we have a looping function,
2517 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002518 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002519 return false; // looped!
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002520
Chris Lattnercdf98be2005-09-26 04:57:38 +00002521 // Okay, we have never been in this block before. Check to see if there
2522 // are any PHI nodes. If so, evaluate them with information about where
2523 // we came from.
2524 BasicBlock *OldBB = CurInst->getParent();
2525 CurInst = NewBB->begin();
2526 PHINode *PN;
2527 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2528 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2529
2530 // Do NOT increment CurInst. We know that the terminator had no value.
2531 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002532 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002533 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002534 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002535 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002536
Chris Lattner1945d582010-12-07 04:33:29 +00002537 if (!CurInst->use_empty()) {
2538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2539 InstResult = ConstantFoldConstantExpression(CE, TD);
2540
Chris Lattner79c11012005-09-26 04:44:35 +00002541 Values[CurInst] = InstResult;
Chris Lattner1945d582010-12-07 04:33:29 +00002542 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002543
Chris Lattner79c11012005-09-26 04:44:35 +00002544 // Advance program counter.
2545 ++CurInst;
2546 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002547}
2548
2549/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2550/// we can. Return true if we can, false otherwise.
Chris Lattner1945d582010-12-07 04:33:29 +00002551static bool EvaluateStaticConstructor(Function *F, const TargetData *TD) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002552 /// MutatedMemory - For each store we execute, we update this map. Loads
2553 /// check this to get the most up-to-date value. If evaluation is successful,
2554 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002555 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002556
2557 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2558 /// to represent its body. This vector is needed so we can delete the
2559 /// temporary globals when we are done.
2560 std::vector<GlobalVariable*> AllocaTmps;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002561
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002562 /// CallStack - This is used to detect recursion. In pathological situations
2563 /// we could hit exponential behavior, but at least there is nothing
2564 /// unbounded.
2565 std::vector<Function*> CallStack;
2566
Chris Lattner1945d582010-12-07 04:33:29 +00002567 /// SimpleConstants - These are constants we have checked and know to be
2568 /// simple enough to live in a static initializer of a global.
2569 SmallPtrSet<Constant*, 8> SimpleConstants;
2570
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002571 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002572 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002573 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2574 SmallVector<Constant*, 0>(), CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002575 MutatedMemory, AllocaTmps,
2576 SimpleConstants, TD);
2577
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002578 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002579 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002580 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002581 << F->getName() << "' to " << MutatedMemory.size()
2582 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002583 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002584 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002585 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002586 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002587
Chris Lattnera22fdb02005-09-26 17:07:09 +00002588 // At this point, we are done interpreting. If we created any 'alloca'
2589 // temporaries, release them now.
2590 while (!AllocaTmps.empty()) {
2591 GlobalVariable *Tmp = AllocaTmps.back();
2592 AllocaTmps.pop_back();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002593
Chris Lattnera22fdb02005-09-26 17:07:09 +00002594 // If there are still users of the alloca, the program is doing something
2595 // silly, e.g. storing the address of the alloca somewhere and using it
2596 // later. Since this is undefined, we'll just make it be null.
2597 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002598 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002599 delete Tmp;
2600 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002601
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002602 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002603}
2604
Chris Lattnerdb973e62005-09-26 02:31:18 +00002605
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002606
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002607/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2608/// Return true if anything changed.
2609bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2610 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2611 bool MadeChange = false;
2612 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002613
Chris Lattner1945d582010-12-07 04:33:29 +00002614 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002615 // Loop over global ctors, optimizing them when we can.
2616 for (unsigned i = 0; i != Ctors.size(); ++i) {
2617 Function *F = Ctors[i];
2618 // Found a null terminator in the middle of the list, prune off the rest of
2619 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002620 if (F == 0) {
2621 if (i != Ctors.size()-1) {
2622 Ctors.resize(i+1);
2623 MadeChange = true;
2624 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002625 break;
2626 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002627
Chris Lattner79c11012005-09-26 04:44:35 +00002628 // We cannot simplify external ctor functions.
2629 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002630
Chris Lattner79c11012005-09-26 04:44:35 +00002631 // If we can evaluate the ctor at compile time, do.
Chris Lattner1945d582010-12-07 04:33:29 +00002632 if (EvaluateStaticConstructor(F, TD)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002633 Ctors.erase(Ctors.begin()+i);
2634 MadeChange = true;
2635 --i;
2636 ++NumCtorsEvaluated;
2637 continue;
2638 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002639 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002640
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002641 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002642
Chris Lattner7b550cc2009-11-06 04:27:31 +00002643 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002644 return true;
2645}
2646
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002647bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002648 bool Changed = false;
2649
Duncan Sands177d84e2009-01-07 20:01:06 +00002650 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002651 I != E;) {
2652 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002653 // Aliases without names cannot be referenced outside this module.
2654 if (!J->hasName() && !J->isDeclaration())
2655 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002656 // If the aliasee may change at link time, nothing can be done - bail out.
2657 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002658 continue;
2659
Duncan Sands4782b302009-02-15 09:56:08 +00002660 Constant *Aliasee = J->getAliasee();
2661 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002662 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002663 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2664
2665 // Make all users of the alias use the aliasee instead.
2666 if (!J->use_empty()) {
2667 J->replaceAllUsesWith(Aliasee);
2668 ++NumAliasesResolved;
2669 Changed = true;
2670 }
2671
Duncan Sands7a154cf2009-12-08 10:10:20 +00002672 // If the alias is externally visible, we may still be able to simplify it.
2673 if (!J->hasLocalLinkage()) {
2674 // If the aliasee has internal linkage, give it the name and linkage
2675 // of the alias, and delete the alias. This turns:
2676 // define internal ... @f(...)
2677 // @a = alias ... @f
2678 // into:
2679 // define ... @a(...)
2680 if (!Target->hasLocalLinkage())
2681 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002682
Duncan Sands7a154cf2009-12-08 10:10:20 +00002683 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002684 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002685 // and other attributes of the aliasee with those of the alias.
2686 if (!hasOneUse)
2687 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002688
Duncan Sands7a154cf2009-12-08 10:10:20 +00002689 // Give the aliasee the name, linkage and other attributes of the alias.
2690 Target->takeName(J);
2691 Target->setLinkage(J->getLinkage());
2692 Target->GlobalValue::copyAttributesFrom(J);
2693 }
Duncan Sands4782b302009-02-15 09:56:08 +00002694
2695 // Delete the alias.
2696 M.getAliasList().erase(J);
2697 ++NumAliasesRemoved;
2698 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002699 }
2700
2701 return Changed;
2702}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002703
Anders Carlssona201c4c2011-03-20 17:59:11 +00002704static Function *FindCXAAtExit(Module &M) {
2705 Function *Fn = M.getFunction("__cxa_atexit");
2706
2707 if (!Fn)
2708 return 0;
2709
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002710 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00002711
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002712 // Checking that the function has the right return type, the right number of
2713 // parameters and that they all have pointer types should be enough.
2714 if (!FTy->getReturnType()->isIntegerTy() ||
2715 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00002716 !FTy->getParamType(0)->isPointerTy() ||
2717 !FTy->getParamType(1)->isPointerTy() ||
2718 !FTy->getParamType(2)->isPointerTy())
2719 return 0;
2720
2721 return Fn;
2722}
2723
2724/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
2725/// destructor and can therefore be eliminated.
2726/// Note that we assume that other optimization passes have already simplified
2727/// the code so we only look for a function with a single basic block, where
2728/// the only allowed instructions are 'ret' or 'call' to empty C++ dtor.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002729static bool cxxDtorIsEmpty(const Function &Fn,
2730 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002731 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002732 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002733 if (Fn.isDeclaration())
2734 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00002735
2736 if (++Fn.begin() != Fn.end())
2737 return false;
2738
2739 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2740 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2741 I != E; ++I) {
2742 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00002743 // Ignore debug intrinsics.
2744 if (isa<DbgInfoIntrinsic>(CI))
2745 continue;
2746
Anders Carlssona201c4c2011-03-20 17:59:11 +00002747 const Function *CalledFn = CI->getCalledFunction();
2748
2749 if (!CalledFn)
2750 return false;
2751
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002752 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2753
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002754 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002755 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002756 return false;
2757
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002758 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002759 return false;
2760 } else if (isa<ReturnInst>(*I))
2761 return true;
2762 else
2763 return false;
2764 }
2765
2766 return false;
2767}
2768
2769bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2770 /// Itanium C++ ABI p3.3.5:
2771 ///
2772 /// After constructing a global (or local static) object, that will require
2773 /// destruction on exit, a termination function is registered as follows:
2774 ///
2775 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2776 ///
2777 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2778 /// call f(p) when DSO d is unloaded, before all such termination calls
2779 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002780 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002781
2782 // This pass will look for calls to __cxa_atexit where the function is trivial
2783 // and remove them.
2784 bool Changed = false;
2785
2786 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
2787 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002788 // We're only interested in calls. Theoretically, we could handle invoke
2789 // instructions as well, but neither llvm-gcc nor clang generate invokes
2790 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002791 CallInst *CI = dyn_cast<CallInst>(*I++);
2792 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002793 continue;
2794
Anders Carlssona201c4c2011-03-20 17:59:11 +00002795 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00002796 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00002797 if (!DtorFn)
2798 continue;
2799
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002800 SmallPtrSet<const Function *, 8> CalledFunctions;
2801 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002802 continue;
2803
2804 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002805 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
2806 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002807
Anders Carlssona201c4c2011-03-20 17:59:11 +00002808 ++NumCXXDtorsRemoved;
2809
2810 Changed |= true;
2811 }
2812
2813 return Changed;
2814}
2815
Chris Lattner7a90b682004-10-07 04:16:33 +00002816bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002817 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002818
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002819 // Try to find the llvm.globalctors list.
2820 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002821
Anders Carlssona201c4c2011-03-20 17:59:11 +00002822 Function *CXAAtExitFn = FindCXAAtExit(M);
2823
Chris Lattner7a90b682004-10-07 04:16:33 +00002824 bool LocalChange = true;
2825 while (LocalChange) {
2826 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002827
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002828 // Delete functions that are trivially dead, ccc -> fastcc
2829 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002830
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002831 // Optimize global_ctors list.
2832 if (GlobalCtors)
2833 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002834
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002835 // Optimize non-address-taken globals.
2836 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002837
2838 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002839 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002840
2841 // Try to remove trivial global destructors.
2842 if (CXAAtExitFn)
2843 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
2844
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002845 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002846 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002847
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002848 // TODO: Move all global ctors functions to the end of the module for code
2849 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002850
Chris Lattner079236d2004-02-25 21:34:36 +00002851 return Changed;
2852}