blob: a10485c12411fcff4550c4b1c303e93bcd729a87 [file] [log] [blame]
Chris Lattner25db5802004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner25db5802004-10-07 04:16:33 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner25db5802004-10-07 04:16:33 +00008//===----------------------------------------------------------------------===//
9//
10// 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.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "globalopt"
17#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/ConstantFolding.h"
24#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Operator.h"
Chris Lattner25db5802004-10-07 04:16:33 +000033#include "llvm/Pass.h"
Duncan Sands85fab3a2008-02-18 17:32:13 +000034#include "llvm/Support/CallSite.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000035#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000036#include "llvm/Support/ErrorHandling.h"
Chris Lattner26fe7eb2008-01-14 02:09:12 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner67ca6f632008-04-26 07:40:11 +000038#include "llvm/Support/MathExtras.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000039#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Target/TargetLibraryInfo.h"
Rafael Espindola3d7fc252013-10-21 17:14:55 +000041#include "llvm/Transforms/Utils/GlobalStatus.h"
Rafael Espindola17600e22013-07-25 03:23:25 +000042#include "llvm/Transforms/Utils/ModuleUtils.h"
Chris Lattner25db5802004-10-07 04:16:33 +000043#include <algorithm>
44using namespace llvm;
45
Chris Lattner1631bcb2006-12-19 22:09:18 +000046STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolafc355bc2011-01-19 16:32:21 +000047STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner1631bcb2006-12-19 22:09:18 +000048STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
49STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
50STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
51STATISTIC(NumDeleted , "Number of globals deleted");
52STATISTIC(NumFnDeleted , "Number of functions deleted");
53STATISTIC(NumGlobUses , "Number of global uses devirtualized");
Alexey Samsonova1944e62013-10-07 19:03:24 +000054STATISTIC(NumLocalized , "Number of globals localized");
Chris Lattner1631bcb2006-12-19 22:09:18 +000055STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
56STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
57STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands573b3f82008-02-16 20:56:04 +000058STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sandsb3f27882009-02-15 09:56:08 +000059STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
60STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssonee6bc702011-03-20 17:59:11 +000061STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner25db5802004-10-07 04:16:33 +000062
Chris Lattner1631bcb2006-12-19 22:09:18 +000063namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000064 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000065 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosiere6de63d2011-12-01 21:29:16 +000066 AU.addRequired<TargetLibraryInfo>();
Chris Lattner004e2502004-10-11 05:54:41 +000067 }
Nick Lewyckye7da2d62007-05-06 13:37:16 +000068 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000069 GlobalOpt() : ModulePass(ID) {
70 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
71 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000072
Chris Lattner25db5802004-10-07 04:16:33 +000073 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000074
75 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000076 GlobalVariable *FindGlobalCtors(Module &M);
77 bool OptimizeFunctions(Module &M);
78 bool OptimizeGlobalVars(Module &M);
Duncan Sandsed722832009-03-06 10:21:56 +000079 bool OptimizeGlobalAliases(Module &M);
Chris Lattner41b6a5a2005-09-26 01:43:45 +000080 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolafc355bc2011-01-19 16:32:21 +000081 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
82 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +000083 const GlobalStatus &GS);
Anders Carlssonee6bc702011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewyckycf6aae62012-02-12 01:13:18 +000085
Micah Villmowcdfe20b2012-10-08 16:38:25 +000086 DataLayout *TD;
Nick Lewyckycf6aae62012-02-12 01:13:18 +000087 TargetLibraryInfo *TLI;
Chris Lattner25db5802004-10-07 04:16:33 +000088 };
Chris Lattner25db5802004-10-07 04:16:33 +000089}
90
Dan Gohmand78c4002008-05-13 00:00:25 +000091char GlobalOpt::ID = 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +000092INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
93 "Global Variable Optimizer", false, false)
94INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
95INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersondf7a4f22010-10-07 22:25:06 +000096 "Global Variable Optimizer", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000097
Chris Lattner25db5802004-10-07 04:16:33 +000098ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
99
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000100/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
101/// as a root? If so, we might not really want to eliminate the stores to it.
102static bool isLeakCheckerRoot(GlobalVariable *GV) {
103 // A global variable is a root if it is a pointer, or could plausibly contain
104 // a pointer. There are two challenges; one is that we could have a struct
105 // the has an inner member which is a pointer. We recurse through the type to
106 // detect these (up to a point). The other is that we may actually be a union
107 // of a pointer and another type, and so our LLVM type is an integer which
108 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
109 // potentially contained here.
110
111 if (GV->hasPrivateLinkage())
112 return false;
113
114 SmallVector<Type *, 4> Types;
115 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
116
117 unsigned Limit = 20;
118 do {
119 Type *Ty = Types.pop_back_val();
120 switch (Ty->getTypeID()) {
121 default: break;
122 case Type::PointerTyID: return true;
123 case Type::ArrayTyID:
124 case Type::VectorTyID: {
125 SequentialType *STy = cast<SequentialType>(Ty);
126 Types.push_back(STy->getElementType());
127 break;
128 }
129 case Type::StructTyID: {
130 StructType *STy = cast<StructType>(Ty);
131 if (STy->isOpaque()) return true;
132 for (StructType::element_iterator I = STy->element_begin(),
133 E = STy->element_end(); I != E; ++I) {
134 Type *InnerTy = *I;
135 if (isa<PointerType>(InnerTy)) return true;
136 if (isa<CompositeType>(InnerTy))
137 Types.push_back(InnerTy);
138 }
139 break;
140 }
141 }
142 if (--Limit == 0) return true;
143 } while (!Types.empty());
144 return false;
145}
146
147/// Given a value that is stored to a global but never read, determine whether
148/// it's safe to remove the store and the chain of computation that feeds the
149/// store.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000150static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000151 do {
152 if (isa<Constant>(V))
153 return true;
154 if (!V->hasOneUse())
155 return false;
Nick Lewycky7d0f1102012-07-25 21:19:40 +0000156 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
157 isa<GlobalValue>(V))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000158 return false;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000159 if (isAllocationFn(V, TLI))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000160 return true;
161
162 Instruction *I = cast<Instruction>(V);
163 if (I->mayHaveSideEffects())
164 return false;
165 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
166 if (!GEP->hasAllConstantIndices())
167 return false;
168 } else if (I->getNumOperands() != 1) {
169 return false;
170 }
171
172 V = I->getOperand(0);
173 } while (1);
174}
175
176/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
177/// of the global and clean up any that obviously don't assign the global a
178/// value that isn't dynamically allocated.
179///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000180static bool CleanupPointerRootUsers(GlobalVariable *GV,
181 const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000182 // A brief explanation of leak checkers. The goal is to find bugs where
183 // pointers are forgotten, causing an accumulating growth in memory
184 // usage over time. The common strategy for leak checkers is to whitelist the
185 // memory pointed to by globals at exit. This is popular because it also
186 // solves another problem where the main thread of a C++ program may shut down
187 // before other threads that are still expecting to use those globals. To
188 // handle that case, we expect the program may create a singleton and never
189 // destroy it.
190
191 bool Changed = false;
192
193 // If Dead[n].first is the only use of a malloc result, we can delete its
194 // chain of computation and the store to the global in Dead[n].second.
195 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
196
197 // Constants can't be pointers to dynamically allocated memory.
198 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
199 UI != E;) {
200 User *U = *UI++;
201 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
202 Value *V = SI->getValueOperand();
203 if (isa<Constant>(V)) {
204 Changed = true;
205 SI->eraseFromParent();
206 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
207 if (I->hasOneUse())
208 Dead.push_back(std::make_pair(I, SI));
209 }
210 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
211 if (isa<Constant>(MSI->getValue())) {
212 Changed = true;
213 MSI->eraseFromParent();
214 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
215 if (I->hasOneUse())
216 Dead.push_back(std::make_pair(I, MSI));
217 }
218 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
219 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
220 if (MemSrc && MemSrc->isConstant()) {
221 Changed = true;
222 MTI->eraseFromParent();
223 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
224 if (I->hasOneUse())
225 Dead.push_back(std::make_pair(I, MTI));
226 }
227 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
228 if (CE->use_empty()) {
229 CE->destroyConstant();
230 Changed = true;
231 }
232 } else if (Constant *C = dyn_cast<Constant>(U)) {
Rafael Espindola27797ba2013-10-17 18:06:32 +0000233 if (isSafeToDestroyConstant(C)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000234 C->destroyConstant();
235 // This could have invalidated UI, start over from scratch.
236 Dead.clear();
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000237 CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000238 return true;
239 }
240 }
241 }
242
243 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000244 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000245 Dead[i].second->eraseFromParent();
246 Instruction *I = Dead[i].first;
247 do {
Michael Gottesman2a654272013-01-11 23:08:52 +0000248 if (isAllocationFn(I, TLI))
249 break;
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000250 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
251 if (!J)
252 break;
253 I->eraseFromParent();
254 I = J;
Nick Lewycky38be9312012-07-24 21:33:00 +0000255 } while (1);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000256 I->eraseFromParent();
257 }
258 }
259
260 return Changed;
261}
262
Chris Lattner25db5802004-10-07 04:16:33 +0000263/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
264/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000265/// quick scan over the use list to clean up the easy and obvious cruft. This
266/// returns true if it made a change.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000267static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000268 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattnercb9f1522004-10-10 16:43:46 +0000269 bool Changed = false;
Bill Wendling88d06c32013-04-02 08:16:45 +0000270 SmallVector<User*, 8> WorkList(V->use_begin(), V->use_end());
271 while (!WorkList.empty()) {
272 User *U = WorkList.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000273
Chris Lattner25db5802004-10-07 04:16:33 +0000274 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000275 if (Init) {
276 // Replace the load with the initializer.
277 LI->replaceAllUsesWith(Init);
278 LI->eraseFromParent();
279 Changed = true;
280 }
Chris Lattner25db5802004-10-07 04:16:33 +0000281 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
282 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000283 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000284 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000285 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
286 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner46d9ff082005-09-26 07:34:35 +0000287 Constant *SubInit = 0;
288 if (Init)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000289 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000290 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000291 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands19d0b472010-02-16 11:11:14 +0000292 CE->getType()->isPointerTy()) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000293 // Pointer cast, delete any stores and memsets to the global.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000294 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner7561ca12005-02-27 18:58:52 +0000295 }
296
297 if (CE->use_empty()) {
298 CE->destroyConstant();
299 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000300 }
301 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000302 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
303 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
304 // and will invalidate our notion of what Init is.
Chris Lattner68f04fa2007-11-13 21:46:23 +0000305 Constant *SubInit = 0;
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000306 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000307 ConstantExpr *CE =
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000308 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000309 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000310 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Krameraa9e4a52012-03-28 14:50:09 +0000311
312 // If the initializer is an all-null value and we have an inbounds GEP,
313 // we already know what the result of any load from that GEP is.
314 // TODO: Handle splats.
315 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
316 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000317 }
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000318 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000319
Chris Lattnercb9f1522004-10-10 16:43:46 +0000320 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000321 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000322 Changed = true;
323 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000324 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
325 if (MI->getRawDest() == V) {
326 MI->eraseFromParent();
327 Changed = true;
328 }
329
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000330 } else if (Constant *C = dyn_cast<Constant>(U)) {
331 // If we have a chain of dead constantexprs or other things dangling from
332 // us, and if they are all dead, nuke them without remorse.
Rafael Espindola27797ba2013-10-17 18:06:32 +0000333 if (isSafeToDestroyConstant(C)) {
Devang Pateld926aaa2009-03-06 01:37:41 +0000334 C->destroyConstant();
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000335 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000336 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000337 }
Chris Lattner25db5802004-10-07 04:16:33 +0000338 }
339 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000340 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000341}
342
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000343/// isSafeSROAElementUse - Return true if the specified instruction is a safe
344/// user of a derived expression from a global that we want to SROA.
345static bool isSafeSROAElementUse(Value *V) {
346 // We might have a dead and dangling constant hanging off of here.
347 if (Constant *C = dyn_cast<Constant>(V))
Rafael Espindola27797ba2013-10-17 18:06:32 +0000348 return isSafeToDestroyConstant(C);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000349
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000350 Instruction *I = dyn_cast<Instruction>(V);
351 if (!I) return false;
352
353 // Loads are ok.
354 if (isa<LoadInst>(I)) return true;
355
356 // Stores *to* the pointer are ok.
357 if (StoreInst *SI = dyn_cast<StoreInst>(I))
358 return SI->getOperand(0) != V;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000359
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000360 // Otherwise, it must be a GEP.
361 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
362 if (GEPI == 0) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000363
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000364 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
365 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
366 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000367
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000368 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
369 I != E; ++I)
370 if (!isSafeSROAElementUse(*I))
371 return false;
Chris Lattnerab053722008-01-14 01:31:05 +0000372 return true;
373}
374
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000375
376/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
377/// Look at it and its uses and decide whether it is safe to SROA this global.
378///
379static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
380 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000381 if (!isa<GetElementPtrInst>(U) &&
382 (!isa<ConstantExpr>(U) ||
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000383 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
384 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000385
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000386 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
387 // don't like < 3 operand CE's, and we don't like non-constant integer
388 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
389 // value of C.
390 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
391 !cast<Constant>(U->getOperand(1))->isNullValue() ||
392 !isa<ConstantInt>(U->getOperand(2)))
393 return false;
394
395 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
396 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000397
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000398 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattner229907c2011-07-18 04:54:35 +0000399 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000400 uint64_t NumElements = AT->getNumElements();
401 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000402
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000403 // Check to make sure that index falls within the array. If not,
404 // something funny is going on, so we won't do the optimization.
405 //
406 if (Idx->getZExtValue() >= NumElements)
407 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000408
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000409 // We cannot scalar repl this level of the array unless any array
410 // sub-indices are in-range constants. In particular, consider:
411 // A[0][i]. We cannot know that the user isn't doing invalid things like
412 // allowing i to index an out-of-range subscript that accesses A[1].
413 //
414 // Scalar replacing *just* the outer index of the array is probably not
415 // going to be a win anyway, so just give up.
416 for (++GEPI; // Skip array index.
Dan Gohman82ac81b2009-08-18 14:58:19 +0000417 GEPI != E;
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000418 ++GEPI) {
419 uint64_t NumElements;
Chris Lattner229907c2011-07-18 04:54:35 +0000420 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000421 NumElements = SubArrayTy->getNumElements();
Chris Lattner229907c2011-07-18 04:54:35 +0000422 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman82ac81b2009-08-18 14:58:19 +0000423 NumElements = SubVectorTy->getNumElements();
424 else {
Duncan Sands19d0b472010-02-16 11:11:14 +0000425 assert((*GEPI)->isStructTy() &&
Dan Gohman82ac81b2009-08-18 14:58:19 +0000426 "Indexed GEP type is not array, vector, or struct!");
427 continue;
428 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000429
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000430 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
431 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
432 return false;
433 }
434 }
435
436 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
437 if (!isSafeSROAElementUse(*I))
438 return false;
439 return true;
440}
441
442/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
443/// is safe for us to perform this transformation.
444///
445static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
446 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
447 UI != E; ++UI) {
448 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
449 return false;
450 }
451 return true;
452}
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000453
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000454
Chris Lattnerabab0712004-10-08 17:32:09 +0000455/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
456/// variable. This opens the door for other optimizations by exposing the
457/// behavior of the program in a more fine-grained way. We have determined that
458/// this transformation is safe already. We return the first global variable we
459/// insert so that the caller can reprocess it.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000460static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
Chris Lattnerab053722008-01-14 01:31:05 +0000461 // Make sure this global only has simple uses that we can SRA.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000462 if (!GlobalUsersSafeToSRA(GV))
Chris Lattnerab053722008-01-14 01:31:05 +0000463 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000464
Rafael Espindola6de96a12009-01-15 20:18:42 +0000465 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattnerabab0712004-10-08 17:32:09 +0000466 Constant *Init = GV->getInitializer();
Chris Lattner229907c2011-07-18 04:54:35 +0000467 Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000468
Chris Lattnerabab0712004-10-08 17:32:09 +0000469 std::vector<GlobalVariable*> NewGlobals;
470 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
471
Chris Lattner67ca6f632008-04-26 07:40:11 +0000472 // Get the alignment of the global, either explicit or target-specific.
473 unsigned StartAlignment = GV->getAlignment();
474 if (StartAlignment == 0)
475 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000476
Chris Lattner229907c2011-07-18 04:54:35 +0000477 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000478 NewGlobals.reserve(STy->getNumElements());
Chris Lattner67ca6f632008-04-26 07:40:11 +0000479 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattnerabab0712004-10-08 17:32:09 +0000480 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000481 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000482 assert(In && "Couldn't get element of initializer?");
Chris Lattner46b5c642009-11-06 04:27:31 +0000483 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000484 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000485 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000486 GV->getThreadLocalMode(),
Owen Anderson5948fdf2009-07-08 01:26:06 +0000487 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000488 Globals.insert(GV, NGV);
489 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000490
Chris Lattner67ca6f632008-04-26 07:40:11 +0000491 // Calculate the known alignment of the field. If the original aggregate
492 // had 256 byte alignment for example, something might depend on that:
493 // propagate info to each field.
494 uint64_t FieldOffset = Layout.getElementOffset(i);
495 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
496 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
497 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000498 }
Chris Lattner229907c2011-07-18 04:54:35 +0000499 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000500 unsigned NumElements = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000501 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattnerabab0712004-10-08 17:32:09 +0000502 NumElements = ATy->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000503 else
Chris Lattner67ca6f632008-04-26 07:40:11 +0000504 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000505
Chris Lattner25169ca2005-02-23 16:53:04 +0000506 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000507 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000508 NewGlobals.reserve(NumElements);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000509
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000510 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner67ca6f632008-04-26 07:40:11 +0000511 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattnerabab0712004-10-08 17:32:09 +0000512 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000513 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000514 assert(In && "Couldn't get element of initializer?");
515
Chris Lattner46b5c642009-11-06 04:27:31 +0000516 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000517 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000518 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000519 GV->getThreadLocalMode(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000520 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000521 Globals.insert(GV, NGV);
522 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000523
Chris Lattner67ca6f632008-04-26 07:40:11 +0000524 // Calculate the known alignment of the field. If the original aggregate
525 // had 256 byte alignment for example, something might depend on that:
526 // propagate info to each field.
527 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
528 if (NewAlign > EltAlign)
529 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000530 }
531 }
532
533 if (NewGlobals.empty())
534 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000535
David Greene44cb8ad2010-01-05 01:28:05 +0000536 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner004e2502004-10-11 05:54:41 +0000537
Chris Lattner46b5c642009-11-06 04:27:31 +0000538 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattnerabab0712004-10-08 17:32:09 +0000539
540 // Loop over all of the uses of the global, replacing the constantexpr geps,
541 // with smaller constantexpr geps or direct references.
542 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000543 User *GEP = GV->use_back();
544 assert(((isa<ConstantExpr>(GEP) &&
545 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
546 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000547
Chris Lattnerabab0712004-10-08 17:32:09 +0000548 // Ignore the 1th operand, which has to be zero or else the program is quite
549 // broken (undefined). Get the 2nd operand, which is the structure or array
550 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000551 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000552 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
553
Chris Lattner004e2502004-10-11 05:54:41 +0000554 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000555
556 // Form a shorter GEP if needed.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000557 if (GEP->getNumOperands() > 3) {
Chris Lattner004e2502004-10-11 05:54:41 +0000558 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000559 SmallVector<Constant*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000560 Idxs.push_back(NullInt);
561 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
562 Idxs.push_back(CE->getOperand(i));
Jay Foaded8db7d2011-07-21 14:31:17 +0000563 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner004e2502004-10-11 05:54:41 +0000564 } else {
565 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner927653f2007-01-31 19:59:55 +0000566 SmallVector<Value*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000567 Idxs.push_back(NullInt);
568 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
569 Idxs.push_back(GEPI->getOperand(i));
Jay Foadd1b78492011-07-25 09:48:08 +0000570 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000571 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner004e2502004-10-11 05:54:41 +0000572 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000573 }
Chris Lattner004e2502004-10-11 05:54:41 +0000574 GEP->replaceAllUsesWith(NewPtr);
575
576 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000577 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000578 else
579 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000580 }
581
Chris Lattner73ad73e2004-10-08 20:25:55 +0000582 // Delete the old global, now that it is dead.
583 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000584 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000585
586 // Loop over the new globals array deleting any globals that are obviously
587 // dead. This can arise due to scalarization of a structure or an array that
588 // has elements that are dead.
589 unsigned FirstGlobal = 0;
590 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
591 if (NewGlobals[i]->use_empty()) {
592 Globals.erase(NewGlobals[i]);
593 if (FirstGlobal == i) ++FirstGlobal;
594 }
595
596 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000597}
598
Chris Lattner09a52722004-10-09 21:48:45 +0000599/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000600/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner2d2892e2007-09-13 16:30:19 +0000601/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif67972872010-04-06 19:24:18 +0000602static bool AllUsesOfValueWillTrapIfNull(const Value *V,
603 SmallPtrSet<const PHINode*, 8> &PHIs) {
604 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greif08355d62010-04-06 19:14:05 +0000605 ++UI) {
Gabor Greif67972872010-04-06 19:24:18 +0000606 const User *U = *UI;
Gabor Greif08355d62010-04-06 19:14:05 +0000607
608 if (isa<LoadInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000609 // Will trap.
Gabor Greif67972872010-04-06 19:24:18 +0000610 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000611 if (SI->getOperand(0) == V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000612 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000613 return false; // Storing the value.
614 }
Gabor Greif67972872010-04-06 19:24:18 +0000615 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000616 if (CI->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000617 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000618 return false; // Not calling the ptr
619 }
Gabor Greif67972872010-04-06 19:24:18 +0000620 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000621 if (II->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000622 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000623 return false; // Not calling the ptr
624 }
Gabor Greif67972872010-04-06 19:24:18 +0000625 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000626 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000627 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000628 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000629 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000630 // If we've already seen this phi node, ignore it, it has already been
631 // checked.
Jakob Stoklund Olesene27dc722010-01-29 23:54:14 +0000632 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
633 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000634 } else if (isa<ICmpInst>(U) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000635 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewycky614fb942010-02-25 06:39:10 +0000636 // Ignore icmp X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000637 } else {
Gabor Greif08355d62010-04-06 19:14:05 +0000638 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000639 return false;
640 }
Gabor Greif08355d62010-04-06 19:14:05 +0000641 }
Chris Lattner09a52722004-10-09 21:48:45 +0000642 return true;
643}
644
645/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000646/// from GV will trap if the loaded value is null. Note that this also permits
647/// comparisons of the loaded value against null, as a special case.
Gabor Greif67972872010-04-06 19:24:18 +0000648static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
649 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greif08355d62010-04-06 19:14:05 +0000650 UI != E; ++UI) {
Gabor Greif67972872010-04-06 19:24:18 +0000651 const User *U = *UI;
Gabor Greif08355d62010-04-06 19:14:05 +0000652
Gabor Greif67972872010-04-06 19:24:18 +0000653 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
654 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner2d2892e2007-09-13 16:30:19 +0000655 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner09a52722004-10-09 21:48:45 +0000656 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000657 } else if (isa<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000658 // Ignore stores to the global.
659 } else {
660 // We don't know or understand this user, bail out.
Gabor Greif08355d62010-04-06 19:14:05 +0000661 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000662 return false;
663 }
Gabor Greif08355d62010-04-06 19:14:05 +0000664 }
Chris Lattner09a52722004-10-09 21:48:45 +0000665 return true;
666}
667
Chris Lattner46b5c642009-11-06 04:27:31 +0000668static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000669 bool Changed = false;
670 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
671 Instruction *I = cast<Instruction>(*UI++);
672 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
673 LI->setOperand(0, NewV);
674 Changed = true;
675 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
676 if (SI->getOperand(1) == V) {
677 SI->setOperand(1, NewV);
678 Changed = true;
679 }
680 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greif04397892010-04-06 18:45:08 +0000681 CallSite CS(I);
682 if (CS.getCalledValue() == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000683 // Calling through the pointer! Turn into a direct call, but be careful
684 // that the pointer is not also being passed as an argument.
Gabor Greif04397892010-04-06 18:45:08 +0000685 CS.setCalledFunction(NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000686 Changed = true;
687 bool PassedAsArg = false;
Gabor Greif04397892010-04-06 18:45:08 +0000688 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
689 if (CS.getArgument(i) == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000690 PassedAsArg = true;
Gabor Greif04397892010-04-06 18:45:08 +0000691 CS.setArgument(i, NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000692 }
693
694 if (PassedAsArg) {
695 // Being passed as an argument also. Be careful to not invalidate UI!
696 UI = V->use_begin();
697 }
698 }
699 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
700 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson487375e2009-07-29 18:55:55 +0000701 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner46b5c642009-11-06 04:27:31 +0000702 NewV, CI->getType()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000703 if (CI->use_empty()) {
704 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000705 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000706 }
707 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
708 // Should handle GEP here.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000709 SmallVector<Constant*, 8> Idxs;
710 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif3a9fba52008-05-29 01:59:18 +0000711 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
712 i != e; ++i)
713 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000714 Idxs.push_back(C);
Chris Lattnere42eb312004-10-10 23:14:11 +0000715 else
716 break;
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000717 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattnere42eb312004-10-10 23:14:11 +0000718 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaded8db7d2011-07-21 14:31:17 +0000719 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattnere42eb312004-10-10 23:14:11 +0000720 if (GEPI->use_empty()) {
721 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000722 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000723 }
724 }
725 }
726
727 return Changed;
728}
729
730
731/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
732/// value stored into it. If there are uses of the loaded value that would trap
733/// if the loaded value is dynamically null, then we know that they cannot be
734/// reachable with a null optimize away the load.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000735static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000736 DataLayout *TD,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000737 TargetLibraryInfo *TLI) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000738 bool Changed = false;
739
Chris Lattner2538eb62009-01-14 00:12:58 +0000740 // Keep track of whether we are able to remove all the uses of the global
741 // other than the store that defines it.
742 bool AllNonStoreUsesGone = true;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000743
Chris Lattnere42eb312004-10-10 23:14:11 +0000744 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner2538eb62009-01-14 00:12:58 +0000745 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
746 User *GlobalUser = *GUI++;
747 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner46b5c642009-11-06 04:27:31 +0000748 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner2538eb62009-01-14 00:12:58 +0000749 // If we were able to delete all uses of the loads
750 if (LI->use_empty()) {
751 LI->eraseFromParent();
752 Changed = true;
753 } else {
754 AllNonStoreUsesGone = false;
755 }
756 } else if (isa<StoreInst>(GlobalUser)) {
757 // Ignore the store that stores "LV" to the global.
758 assert(GlobalUser->getOperand(1) == GV &&
759 "Must be storing *to* the global");
Chris Lattnere42eb312004-10-10 23:14:11 +0000760 } else {
Chris Lattner2538eb62009-01-14 00:12:58 +0000761 AllNonStoreUsesGone = false;
762
763 // If we get here we could have other crazy uses that are transitively
764 // loaded.
765 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramered843602012-09-28 10:01:27 +0000766 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
767 isa<BitCastInst>(GlobalUser) ||
768 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner1a1acc22011-05-22 07:15:13 +0000769 "Only expect load and stores!");
Chris Lattnere42eb312004-10-10 23:14:11 +0000770 }
Chris Lattner2538eb62009-01-14 00:12:58 +0000771 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000772
773 if (Changed) {
David Greene44cb8ad2010-01-05 01:28:05 +0000774 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000775 ++NumGlobUses;
776 }
777
Chris Lattnere42eb312004-10-10 23:14:11 +0000778 // If we nuked all of the loads, then none of the stores are needed either,
779 // nor is the global.
Chris Lattner2538eb62009-01-14 00:12:58 +0000780 if (AllNonStoreUsesGone) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000781 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000782 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000783 } else {
784 Changed = true;
785 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
786 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000787 if (GV->use_empty()) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000788 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
789 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000790 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000791 ++NumDeleted;
792 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000793 }
794 return Changed;
795}
796
Chris Lattner004e2502004-10-11 05:54:41 +0000797/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
798/// instructions that are foldable.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000799static void ConstantPropUsersOf(Value *V,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000800 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner004e2502004-10-11 05:54:41 +0000801 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
802 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000803 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000804 I->replaceAllUsesWith(NewC);
805
Chris Lattnerd6a44922005-02-01 01:23:31 +0000806 // Advance UI to the next non-I use to avoid invalidating it!
807 // Instructions could multiply use V.
808 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000809 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000810 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000811 }
812}
813
814/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
815/// variable, and transforms the program as if it always contained the result of
816/// the specified malloc. Because it is always the result of the specified
817/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner3ede00b2006-11-30 17:32:29 +0000818/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner004e2502004-10-11 05:54:41 +0000819static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +0000820 CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +0000821 Type *AllocTy,
Chris Lattner7939f792010-02-25 22:33:52 +0000822 ConstantInt *NElements,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000823 DataLayout *TD,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000824 TargetLibraryInfo *TLI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000825 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000826
Chris Lattner229907c2011-07-18 04:54:35 +0000827 Type *GlobalType;
Chris Lattner7939f792010-02-25 22:33:52 +0000828 if (NElements->getZExtValue() == 1)
829 GlobalType = AllocTy;
830 else
831 // If we have an array allocation, the global variable is of an array.
832 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez5d034492009-09-18 22:35:49 +0000833
834 // Create the new global variable. The contents of the malloc'd memory is
835 // undefined, so initialize with an undef value.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000836 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000837 GlobalType, false,
Chris Lattner7939f792010-02-25 22:33:52 +0000838 GlobalValue::InternalLinkage,
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000839 UndefValue::get(GlobalType),
Victor Hernandez5d034492009-09-18 22:35:49 +0000840 GV->getName()+".body",
841 GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000842 GV->getThreadLocalMode());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000843
Chris Lattner7939f792010-02-25 22:33:52 +0000844 // If there are bitcast users of the malloc (which is typical, usually we have
845 // a malloc + bitcast) then replace them with uses of the new global. Update
846 // other users to use the global as well.
847 BitCastInst *TheBC = 0;
848 while (!CI->use_empty()) {
849 Instruction *User = cast<Instruction>(CI->use_back());
850 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
851 if (BCI->getType() == NewGV->getType()) {
852 BCI->replaceAllUsesWith(NewGV);
853 BCI->eraseFromParent();
854 } else {
855 BCI->setOperand(0, NewGV);
856 }
857 } else {
858 if (TheBC == 0)
859 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
860 User->replaceUsesOfWith(CI, TheBC);
861 }
862 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000863
Victor Hernandez5d034492009-09-18 22:35:49 +0000864 Constant *RepValue = NewGV;
865 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000866 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez5d034492009-09-18 22:35:49 +0000867 GV->getType()->getElementType());
868
869 // If there is a comparison against null, we will insert a global bool to
870 // keep track of whether the global was initialized yet or not.
871 GlobalVariable *InitBool =
Chris Lattner46b5c642009-11-06 04:27:31 +0000872 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez5d034492009-09-18 22:35:49 +0000873 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +0000874 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000875 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +0000876 bool InitBoolUsed = false;
877
878 // Loop over all uses of GV, processing them in turn.
Chris Lattner7939f792010-02-25 22:33:52 +0000879 while (!GV->use_empty()) {
880 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez5d034492009-09-18 22:35:49 +0000881 // The global is initialized when the store to it occurs.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000882 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
883 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000884 SI->eraseFromParent();
Chris Lattner7939f792010-02-25 22:33:52 +0000885 continue;
Victor Hernandez5d034492009-09-18 22:35:49 +0000886 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000887
Chris Lattner7939f792010-02-25 22:33:52 +0000888 LoadInst *LI = cast<LoadInst>(GV->use_back());
889 while (!LI->use_empty()) {
890 Use &LoadUse = LI->use_begin().getUse();
891 if (!isa<ICmpInst>(LoadUse.getUser())) {
892 LoadUse = RepValue;
893 continue;
894 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000895
Chris Lattner7939f792010-02-25 22:33:52 +0000896 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
897 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000898 // Sink the load to where the compare was, if atomic rules allow us to.
899 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
900 LI->getOrdering(), LI->getSynchScope(),
901 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattner7939f792010-02-25 22:33:52 +0000902 InitBoolUsed = true;
903 switch (ICI->getPredicate()) {
904 default: llvm_unreachable("Unknown ICmp Predicate!");
905 case ICmpInst::ICMP_ULT:
906 case ICmpInst::ICMP_SLT: // X < null -> always false
907 LV = ConstantInt::getFalse(GV->getContext());
908 break;
909 case ICmpInst::ICMP_ULE:
910 case ICmpInst::ICMP_SLE:
911 case ICmpInst::ICMP_EQ:
912 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
913 break;
914 case ICmpInst::ICMP_NE:
915 case ICmpInst::ICMP_UGE:
916 case ICmpInst::ICMP_SGE:
917 case ICmpInst::ICMP_UGT:
918 case ICmpInst::ICMP_SGT:
919 break; // no change.
920 }
921 ICI->replaceAllUsesWith(LV);
922 ICI->eraseFromParent();
923 }
924 LI->eraseFromParent();
925 }
Victor Hernandez5d034492009-09-18 22:35:49 +0000926
927 // If the initialization boolean was used, insert it, otherwise delete it.
928 if (!InitBoolUsed) {
929 while (!InitBool->use_empty()) // Delete initializations
Chris Lattner7939f792010-02-25 22:33:52 +0000930 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000931 delete InitBool;
932 } else
933 GV->getParent()->getGlobalList().insert(GV, InitBool);
934
Chris Lattner7939f792010-02-25 22:33:52 +0000935 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez5d034492009-09-18 22:35:49 +0000936 GV->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000937 CI->eraseFromParent();
938
939 // To further other optimizations, loop over all users of NewGV and try to
940 // constant prop them. This will promote GEP instructions with constant
941 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000942 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000943 if (RepValue != NewGV)
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000944 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000945
946 return NewGV;
947}
948
Chris Lattnerc0677c02004-12-02 07:11:07 +0000949/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
950/// to make sure that there are no complex uses of V. We permit simple things
951/// like dereferencing the pointer, but not storing through the address, unless
952/// it is to the specified global.
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000953static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
954 const GlobalVariable *GV,
Gabor Greif08355d62010-04-06 19:14:05 +0000955 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000956 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greif08355d62010-04-06 19:14:05 +0000957 UI != E; ++UI) {
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000958 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greif08355d62010-04-06 19:14:05 +0000959
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000960 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
961 continue; // Fine, ignore.
962 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000963
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000964 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerc0677c02004-12-02 07:11:07 +0000965 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
966 return false; // Storing the pointer itself... bad.
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000967 continue; // Otherwise, storing through it, or storing into GV... fine.
968 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000969
Chris Lattnerb9801ff2010-04-10 18:19:22 +0000970 // Must index into the array and into the struct.
971 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000972 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerc0677c02004-12-02 07:11:07 +0000973 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000974 continue;
975 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000976
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000977 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattner6eed0e72007-09-13 16:37:20 +0000978 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
979 // cycles.
980 if (PHIs.insert(PN))
Chris Lattner5d13fb532007-09-14 03:41:21 +0000981 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
982 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000983 continue;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000984 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000985
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000986 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000987 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
988 return false;
989 continue;
990 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000991
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000992 return false;
993 }
Chris Lattnerc0677c02004-12-02 07:11:07 +0000994 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000995}
996
Chris Lattner24d3d422006-09-30 23:32:09 +0000997/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
998/// somewhere. Transform all uses of the allocation into loads from the
999/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001000/// GV. This assumes that these value pass the
Chris Lattner24d3d422006-09-30 23:32:09 +00001001/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001002static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001003 GlobalVariable *GV) {
1004 while (!Alloc->use_empty()) {
Chris Lattnerba98f892007-09-13 18:00:31 +00001005 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1006 Instruction *InsertPt = U;
Chris Lattner24d3d422006-09-30 23:32:09 +00001007 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1008 // If this is the store of the allocation into the global, remove it.
1009 if (SI->getOperand(1) == GV) {
1010 SI->eraseFromParent();
1011 continue;
1012 }
Chris Lattnerba98f892007-09-13 18:00:31 +00001013 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1014 // Insert the load in the corresponding predecessor, not right before the
1015 // PHI.
Gabor Greifeb61fcf2009-01-23 19:40:15 +00001016 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001017 } else if (isa<BitCastInst>(U)) {
1018 // Must be bitcast between the malloc and store to initialize the global.
1019 ReplaceUsesOfMallocWithGlobal(U, GV);
1020 U->eraseFromParent();
1021 continue;
1022 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1023 // If this is a "GEP bitcast" and the user is a store to the global, then
1024 // just process it as a bitcast.
1025 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1026 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1027 if (SI->getOperand(1) == GV) {
1028 // Must be bitcast GEP between the malloc and store to initialize
1029 // the global.
1030 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1031 GEPI->eraseFromParent();
1032 continue;
1033 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001034 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001035
Chris Lattner24d3d422006-09-30 23:32:09 +00001036 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnerba98f892007-09-13 18:00:31 +00001037 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner24d3d422006-09-30 23:32:09 +00001038 U->replaceUsesOfWith(Alloc, NL);
1039 }
1040}
1041
Chris Lattner56b55382008-12-16 21:24:51 +00001042/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1043/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1044/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greif5d5db532010-04-01 08:21:08 +00001045static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif08d85da2010-04-07 18:59:26 +00001046 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1047 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner56b55382008-12-16 21:24:51 +00001048 // We permit two users of the load: setcc comparing against the null
1049 // pointer, and a getelementptr of a specific form.
Gabor Greif08d85da2010-04-07 18:59:26 +00001050 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1051 ++UI) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001052 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001053
Chris Lattner56b55382008-12-16 21:24:51 +00001054 // Comparison against null is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001055 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001056 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1057 return false;
1058 continue;
1059 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001060
Chris Lattner56b55382008-12-16 21:24:51 +00001061 // getelementptr is also ok, but only a simple form.
Gabor Greif5d5db532010-04-01 08:21:08 +00001062 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001063 // Must index into the array and into the struct.
1064 if (GEPI->getNumOperands() < 3)
1065 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001066
Chris Lattner56b55382008-12-16 21:24:51 +00001067 // Otherwise the GEP is ok.
1068 continue;
1069 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001070
Gabor Greif5d5db532010-04-01 08:21:08 +00001071 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng83689442009-06-02 00:56:07 +00001072 if (!LoadUsingPHIsPerLoad.insert(PN))
1073 // This means some phi nodes are dependent on each other.
1074 // Avoid infinite looping!
1075 return false;
1076 if (!LoadUsingPHIs.insert(PN))
1077 // If we have already analyzed this PHI, then it is safe.
Chris Lattner56b55382008-12-16 21:24:51 +00001078 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001079
Chris Lattner222ef4c2008-12-17 05:28:49 +00001080 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng83689442009-06-02 00:56:07 +00001081 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1082 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001083 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001084
Chris Lattner56b55382008-12-16 21:24:51 +00001085 continue;
Chris Lattner24d3d422006-09-30 23:32:09 +00001086 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001087
Chris Lattner56b55382008-12-16 21:24:51 +00001088 // Otherwise we don't know what this is, not ok.
1089 return false;
1090 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001091
Chris Lattner56b55382008-12-16 21:24:51 +00001092 return true;
1093}
1094
1095
1096/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1097/// GV are simple enough to perform HeapSRA, return true.
Gabor Greif5d5db532010-04-01 08:21:08 +00001098static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001099 Instruction *StoredVal) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001100 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1101 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif08d85da2010-04-07 18:59:26 +00001102 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1103 UI != E; ++UI)
Gabor Greif5d5db532010-04-01 08:21:08 +00001104 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng83689442009-06-02 00:56:07 +00001105 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1106 LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001107 return false;
Evan Cheng83689442009-06-02 00:56:07 +00001108 LoadUsingPHIsPerLoad.clear();
1109 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001110
Chris Lattner222ef4c2008-12-17 05:28:49 +00001111 // If we reach here, we know that all uses of the loads and transitive uses
1112 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001113 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001114 // Check to verify that all operands of the PHIs are either PHIS that can be
1115 // transformed, loads from GV, or MI itself.
Gabor Greif08d85da2010-04-07 18:59:26 +00001116 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1117 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001118 const PHINode *PN = *I;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001119 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1120 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001121
Chris Lattner222ef4c2008-12-17 05:28:49 +00001122 // PHI of the stored value itself is ok.
Victor Hernandez5d034492009-09-18 22:35:49 +00001123 if (InVal == StoredVal) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001124
Gabor Greif5d5db532010-04-01 08:21:08 +00001125 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001126 // One of the PHIs in our set is (optimistically) ok.
1127 if (LoadUsingPHIs.count(InPN))
1128 continue;
1129 return false;
1130 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001131
Chris Lattner222ef4c2008-12-17 05:28:49 +00001132 // Load from GV is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001133 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattner222ef4c2008-12-17 05:28:49 +00001134 if (LI->getOperand(0) == GV)
1135 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001136
Chris Lattner222ef4c2008-12-17 05:28:49 +00001137 // UNDEF? NULL?
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001138
Chris Lattner222ef4c2008-12-17 05:28:49 +00001139 // Anything else is rejected.
1140 return false;
1141 }
1142 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001143
Chris Lattner24d3d422006-09-30 23:32:09 +00001144 return true;
1145}
1146
Chris Lattner222ef4c2008-12-17 05:28:49 +00001147static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1148 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001149 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001150 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001151
Chris Lattner222ef4c2008-12-17 05:28:49 +00001152 if (FieldNo >= FieldVals.size())
1153 FieldVals.resize(FieldNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001154
Chris Lattner222ef4c2008-12-17 05:28:49 +00001155 // If we already have this value, just reuse the previously scalarized
1156 // version.
1157 if (Value *FieldVal = FieldVals[FieldNo])
1158 return FieldVal;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001159
Chris Lattner222ef4c2008-12-17 05:28:49 +00001160 // Depending on what instruction this is, we have several cases.
1161 Value *Result;
1162 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1163 // This is a scalarized version of the load from the global. Just create
1164 // a new Load of the scalarized global.
1165 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1166 InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001167 PHIsToRewrite),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001168 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattner222ef4c2008-12-17 05:28:49 +00001169 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1170 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1171 // field.
Matt Arsenault404c60a2013-10-21 19:43:56 +00001172 StructType *ST = cast<StructType>(PN->getType()->getPointerElementType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001173
Jay Foade0938d82011-03-30 11:19:20 +00001174 PHINode *NewPN =
Owen Anderson4056ca92009-07-29 22:17:13 +00001175 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad52131342011-03-30 11:28:46 +00001176 PN->getNumIncomingValues(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001177 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foade0938d82011-03-30 11:19:20 +00001178 Result = NewPN;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001179 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1180 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001181 llvm_unreachable("Unknown usable value");
Chris Lattner222ef4c2008-12-17 05:28:49 +00001182 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001183
Chris Lattner222ef4c2008-12-17 05:28:49 +00001184 return FieldVals[FieldNo] = Result;
Chris Lattnerba98f892007-09-13 18:00:31 +00001185}
1186
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001187/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1188/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001189static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001190 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001191 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001192 // If this is a comparison against null, handle it.
1193 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1194 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1195 // If we have a setcc of the loaded pointer, we can use a setcc of any
1196 // field.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001197 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner46b5c642009-11-06 04:27:31 +00001198 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001199
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001200 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001201 Constant::getNullValue(NPtr->getType()),
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001202 SCI->getName());
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001203 SCI->replaceAllUsesWith(New);
1204 SCI->eraseFromParent();
1205 return;
1206 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001207
Chris Lattner222ef4c2008-12-17 05:28:49 +00001208 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnerba98f892007-09-13 18:00:31 +00001209 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1210 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1211 && "Unexpected GEPI!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001212
Chris Lattnerba98f892007-09-13 18:00:31 +00001213 // Load the pointer for this field.
1214 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner222ef4c2008-12-17 05:28:49 +00001215 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner46b5c642009-11-06 04:27:31 +00001216 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001217
Chris Lattnerba98f892007-09-13 18:00:31 +00001218 // Create the new GEP idx vector.
1219 SmallVector<Value*, 8> GEPIdx;
1220 GEPIdx.push_back(GEPI->getOperand(1));
1221 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001222
Jay Foadd1b78492011-07-25 09:48:08 +00001223 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greife9ecc682008-04-06 20:25:17 +00001224 GEPI->getName(), GEPI);
Chris Lattnerba98f892007-09-13 18:00:31 +00001225 GEPI->replaceAllUsesWith(NGEPI);
1226 GEPI->eraseFromParent();
1227 return;
1228 }
Chris Lattner011f91b2007-09-13 21:31:36 +00001229
Chris Lattner222ef4c2008-12-17 05:28:49 +00001230 // Recursively transform the users of PHI nodes. This will lazily create the
1231 // PHIs that are needed for individual elements. Keep track of what PHIs we
1232 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1233 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1234 // already been seen first by another load, so its uses have already been
1235 // processed.
1236 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattner5cf753c2011-07-21 06:21:31 +00001237 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1238 std::vector<Value*>())).second)
1239 return;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001240
Chris Lattner222ef4c2008-12-17 05:28:49 +00001241 // If this is the first time we've seen this PHI, recursively process all
1242 // users.
Chris Lattner0cdf5232008-12-17 05:42:08 +00001243 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1244 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001245 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001246 }
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001247}
1248
Chris Lattner24d3d422006-09-30 23:32:09 +00001249/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1250/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1251/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner56b55382008-12-16 21:24:51 +00001252/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001253static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001254 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001255 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001256 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattner0cdf5232008-12-17 05:42:08 +00001257 UI != E; ) {
1258 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001259 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001260 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001261
Chris Lattner222ef4c2008-12-17 05:28:49 +00001262 if (Load->use_empty()) {
1263 Load->eraseFromParent();
1264 InsertedScalarizedValues.erase(Load);
1265 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001266}
1267
Victor Hernandez5d034492009-09-18 22:35:49 +00001268/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1269/// it up into multiple allocations of arrays of the fields.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001270static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001271 Value *NElems, DataLayout *TD,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001272 const TargetLibraryInfo *TLI) {
David Greene44cb8ad2010-01-05 01:28:05 +00001273 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001274 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattner229907c2011-07-18 04:54:35 +00001275 StructType *STy = cast<StructType>(MAT);
Victor Hernandez5d034492009-09-18 22:35:49 +00001276
1277 // There is guaranteed to be at least one use of the malloc (storing
1278 // it into GV). If there are other uses, change them to be uses of
1279 // the global to simplify later code. This also deletes the store
1280 // into GV.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001281 ReplaceUsesOfMallocWithGlobal(CI, GV);
1282
Victor Hernandez5d034492009-09-18 22:35:49 +00001283 // Okay, at this point, there are no users of the malloc. Insert N
1284 // new mallocs at the same place as CI, and N globals.
1285 std::vector<Value*> FieldGlobals;
1286 std::vector<Value*> FieldMallocs;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001287
Victor Hernandez5d034492009-09-18 22:35:49 +00001288 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattner229907c2011-07-18 04:54:35 +00001289 Type *FieldTy = STy->getElementType(FieldNo);
1290 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001291
Victor Hernandez5d034492009-09-18 22:35:49 +00001292 GlobalVariable *NGV =
1293 new GlobalVariable(*GV->getParent(),
1294 PFieldTy, false, GlobalValue::InternalLinkage,
1295 Constant::getNullValue(PFieldTy),
1296 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001297 GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +00001298 FieldGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001299
Victor Hernandezf3db9152009-11-07 00:16:28 +00001300 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001301 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001302 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Matt Arsenaultd3471e92013-09-11 07:29:40 +00001303 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Victor Hernandezf3db9152009-11-07 00:16:28 +00001304 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1305 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner601e390a2010-07-12 00:57:28 +00001306 NElems, 0,
Victor Hernandezf3db9152009-11-07 00:16:28 +00001307 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner0521c092010-02-26 18:23:13 +00001308 FieldMallocs.push_back(NMI);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001309 new StoreInst(NMI, NGV, CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001310 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001311
Victor Hernandez5d034492009-09-18 22:35:49 +00001312 // The tricky aspect of this transformation is handling the case when malloc
1313 // fails. In the original code, malloc failing would set the result pointer
1314 // of malloc to null. In this case, some mallocs could succeed and others
1315 // could fail. As such, we emit code that looks like this:
1316 // F0 = malloc(field0)
1317 // F1 = malloc(field1)
1318 // F2 = malloc(field2)
1319 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1320 // if (F0) { free(F0); F0 = 0; }
1321 // if (F1) { free(F1); F1 = 0; }
1322 // if (F2) { free(F2); F2 = 0; }
1323 // }
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001324 // The malloc can also fail if its argument is too large.
Gabor Greif218f5542010-06-24 14:42:01 +00001325 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1326 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001327 ConstantZero, "isneg");
Victor Hernandez5d034492009-09-18 22:35:49 +00001328 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandezf3db9152009-11-07 00:16:28 +00001329 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1330 Constant::getNullValue(FieldMallocs[i]->getType()),
1331 "isnull");
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001332 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001333 }
1334
1335 // Split the basic block at the old malloc.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001336 BasicBlock *OrigBB = CI->getParent();
1337 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001338
Victor Hernandez5d034492009-09-18 22:35:49 +00001339 // Create the block to check the first condition. Put all these blocks at the
1340 // end of the function as they are unlikely to be executed.
Chris Lattner46b5c642009-11-06 04:27:31 +00001341 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1342 "malloc_ret_null",
Victor Hernandez5d034492009-09-18 22:35:49 +00001343 OrigBB->getParent());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001344
Victor Hernandez5d034492009-09-18 22:35:49 +00001345 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1346 // branch on RunningOr.
1347 OrigBB->getTerminator()->eraseFromParent();
1348 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001349
Victor Hernandez5d034492009-09-18 22:35:49 +00001350 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1351 // pointer, because some may be null while others are not.
1352 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1353 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001354 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001355 Constant::getNullValue(GVVal->getType()));
Chris Lattner46b5c642009-11-06 04:27:31 +00001356 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez5d034492009-09-18 22:35:49 +00001357 OrigBB->getParent());
Chris Lattner46b5c642009-11-06 04:27:31 +00001358 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez5d034492009-09-18 22:35:49 +00001359 OrigBB->getParent());
Victor Hernandeze2971492009-10-24 04:23:03 +00001360 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1361 Cmp, NullPtrBlock);
Victor Hernandez5d034492009-09-18 22:35:49 +00001362
1363 // Fill in FreeBlock.
Victor Hernandeze2971492009-10-24 04:23:03 +00001364 CallInst::CreateFree(GVVal, BI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001365 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1366 FreeBlock);
1367 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001368
Victor Hernandez5d034492009-09-18 22:35:49 +00001369 NullPtrBlock = NextBlock;
1370 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001371
Victor Hernandez5d034492009-09-18 22:35:49 +00001372 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001373
1374 // CI is no longer needed, remove it.
Victor Hernandez5d034492009-09-18 22:35:49 +00001375 CI->eraseFromParent();
1376
1377 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1378 /// update all uses of the load, keep track of what scalarized loads are
1379 /// inserted for a given load.
1380 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1381 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001382
Victor Hernandez5d034492009-09-18 22:35:49 +00001383 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001384
Victor Hernandez5d034492009-09-18 22:35:49 +00001385 // Okay, the malloc site is completely handled. All of the uses of GV are now
1386 // loads, and all uses of those loads are simple. Rewrite them to use loads
1387 // of the per-field globals instead.
1388 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1389 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001390
Victor Hernandez5d034492009-09-18 22:35:49 +00001391 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001392 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001393 continue;
1394 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001395
Victor Hernandez5d034492009-09-18 22:35:49 +00001396 // Must be a store of null.
1397 StoreInst *SI = cast<StoreInst>(User);
1398 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1399 "Unexpected heap-sra user!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001400
Victor Hernandez5d034492009-09-18 22:35:49 +00001401 // Insert a store of null into each global.
1402 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00001403 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez5d034492009-09-18 22:35:49 +00001404 Constant *Null = Constant::getNullValue(PT->getElementType());
1405 new StoreInst(Null, FieldGlobals[i], SI);
1406 }
1407 // Erase the original store.
1408 SI->eraseFromParent();
1409 }
1410
1411 // While we have PHIs that are interesting to rewrite, do it.
1412 while (!PHIsToRewrite.empty()) {
1413 PHINode *PN = PHIsToRewrite.back().first;
1414 unsigned FieldNo = PHIsToRewrite.back().second;
1415 PHIsToRewrite.pop_back();
1416 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1417 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1418
1419 // Add all the incoming values. This can materialize more phis.
1420 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1421 Value *InVal = PN->getIncomingValue(i);
1422 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001423 PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001424 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1425 }
1426 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001427
Victor Hernandez5d034492009-09-18 22:35:49 +00001428 // Drop all inter-phi links and any loads that made it this far.
1429 for (DenseMap<Value*, std::vector<Value*> >::iterator
1430 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1431 I != E; ++I) {
1432 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1433 PN->dropAllReferences();
1434 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1435 LI->dropAllReferences();
1436 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001437
Victor Hernandez5d034492009-09-18 22:35:49 +00001438 // Delete all the phis and loads now that inter-references are dead.
1439 for (DenseMap<Value*, std::vector<Value*> >::iterator
1440 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1441 I != E; ++I) {
1442 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1443 PN->eraseFromParent();
1444 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1445 LI->eraseFromParent();
1446 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001447
Victor Hernandez5d034492009-09-18 22:35:49 +00001448 // The old global is now dead, remove it.
1449 GV->eraseFromParent();
1450
1451 ++NumHeapSRA;
1452 return cast<GlobalVariable>(FieldGlobals[0]);
1453}
1454
Chris Lattnerc4274a72008-12-15 21:02:25 +00001455/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1456/// pointer global variable with a single value stored it that is a malloc or
1457/// cast of malloc.
1458static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001459 CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +00001460 Type *AllocTy,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001461 AtomicOrdering Ordering,
Victor Hernandez5d034492009-09-18 22:35:49 +00001462 Module::global_iterator &GVI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001463 DataLayout *TD,
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001464 TargetLibraryInfo *TLI) {
Evan Cheng21b588b2010-04-14 20:52:55 +00001465 if (!TD)
1466 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001467
Victor Hernandez5d034492009-09-18 22:35:49 +00001468 // If this is a malloc of an abstract type, don't touch it.
1469 if (!AllocTy->isSized())
1470 return false;
1471
1472 // We can't optimize this global unless all uses of it are *known* to be
1473 // of the malloc value, not of the null initializer value (consider a use
1474 // that compares the global's value against zero to see if the malloc has
1475 // been reached). To do this, we check to see if all uses of the global
1476 // would trap if the global were null: this proves that they must all
1477 // happen after the malloc.
1478 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1479 return false;
1480
1481 // We can't optimize this if the malloc itself is used in a complex way,
1482 // for example, being stored into multiple globals. This allows the
Nick Lewyckybbd11562012-02-05 19:48:37 +00001483 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez5d034492009-09-18 22:35:49 +00001484 // GEP'd. These are all things we could transform to using the global
1485 // for.
Evan Cheng21b588b2010-04-14 20:52:55 +00001486 SmallPtrSet<const PHINode*, 8> PHIs;
1487 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1488 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001489
1490 // If we have a global that is only initialized with a fixed size malloc,
1491 // transform the program to use global memory instead of malloc'd memory.
1492 // This eliminates dynamic allocation, avoids an indirection accessing the
1493 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez264da322009-10-16 23:12:25 +00001494 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001495 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng21b588b2010-04-14 20:52:55 +00001496 if (!NElems)
1497 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001498
Evan Cheng21b588b2010-04-14 20:52:55 +00001499 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1500 // Restrict this transformation to only working on small allocations
1501 // (2048 bytes currently), as we don't want to introduce a 16M global or
1502 // something.
1503 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001504 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001505 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001506 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001507
Evan Cheng21b588b2010-04-14 20:52:55 +00001508 // If the allocation is an array of structures, consider transforming this
1509 // into multiple malloc'd arrays, one for each field. This is basically
1510 // SRoA for malloc'd memory.
1511
Nick Lewycky52da72b2012-02-05 19:56:38 +00001512 if (Ordering != NotAtomic)
1513 return false;
1514
Evan Cheng21b588b2010-04-14 20:52:55 +00001515 // If this is an allocation of a fixed size array of structs, analyze as a
1516 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif218f5542010-06-24 14:42:01 +00001517 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattner229907c2011-07-18 04:54:35 +00001518 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng21b588b2010-04-14 20:52:55 +00001519 AllocTy = AT->getElementType();
Gabor Greif218f5542010-06-24 14:42:01 +00001520
Chris Lattner229907c2011-07-18 04:54:35 +00001521 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng21b588b2010-04-14 20:52:55 +00001522 if (!AllocSTy)
1523 return false;
1524
1525 // This the structure has an unreasonable number of fields, leave it
1526 // alone.
1527 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1528 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1529
1530 // If this is a fixed size array, transform the Malloc to be an alloc of
1531 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001532 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Matt Arsenaultd3471e92013-09-11 07:29:40 +00001533 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Evan Cheng21b588b2010-04-14 20:52:55 +00001534 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1535 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1536 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1537 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1538 AllocSize, NumElements,
Chris Lattner601e390a2010-07-12 00:57:28 +00001539 0, CI->getName());
Evan Cheng21b588b2010-04-14 20:52:55 +00001540 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1541 CI->replaceAllUsesWith(Cast);
1542 CI->eraseFromParent();
Nuno Lopes9792d682012-06-22 00:25:01 +00001543 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1544 CI = cast<CallInst>(BCI->getOperand(0));
1545 else
Nuno Lopes0b60ebb2012-06-22 00:29:58 +00001546 CI = cast<CallInst>(Malloc);
Evan Cheng21b588b2010-04-14 20:52:55 +00001547 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001548
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001549 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1550 TD, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001551 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001552 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001553
Victor Hernandez5d034492009-09-18 22:35:49 +00001554 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001555}
Victor Hernandez5d034492009-09-18 22:35:49 +00001556
Chris Lattner09a52722004-10-09 21:48:45 +00001557// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1558// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001559static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001560 AtomicOrdering Ordering,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001561 Module::global_iterator &GVI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001562 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner1c731fa2008-12-15 21:20:32 +00001563 // Ignore no-op GEPs and bitcasts.
1564 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner09a52722004-10-09 21:48:45 +00001565
Chris Lattnere42eb312004-10-10 23:14:11 +00001566 // If we are dealing with a pointer global that is initialized to null and
1567 // only has one (non-null) value stored into it, then we can optimize any
1568 // users of the loaded value (often calls and loads) that would trap if the
1569 // value was null.
Duncan Sands19d0b472010-02-16 11:11:14 +00001570 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner09a52722004-10-09 21:48:45 +00001571 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001572 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1573 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner1a1acc22011-05-22 07:15:13 +00001574 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001575
Chris Lattnere42eb312004-10-10 23:14:11 +00001576 // Optimize away any trapping uses of the loaded value.
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001577 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001578 return true;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001579 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1580 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001581 if (MallocType &&
1582 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1583 TD, TLI))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001584 return true;
Chris Lattnere42eb312004-10-10 23:14:11 +00001585 }
Chris Lattner09a52722004-10-09 21:48:45 +00001586 }
Chris Lattner004e2502004-10-11 05:54:41 +00001587
Chris Lattner09a52722004-10-09 21:48:45 +00001588 return false;
1589}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001590
Chris Lattner20bbac32008-01-14 01:17:44 +00001591/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1592/// two values ever stored into GV are its initializer and OtherVal. See if we
1593/// can shrink the global into a boolean and select between the two values
1594/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner46b5c642009-11-06 04:27:31 +00001595static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00001596 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001597
Chris Lattner20bbac32008-01-14 01:17:44 +00001598 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattnere3132832009-03-07 23:32:02 +00001599 // an FP value, pointer or vector, don't do this optimization because a select
1600 // between them is very expensive and unlikely to lead to later
1601 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1602 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner46b5c642009-11-06 04:27:31 +00001603 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001604 GVElType->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001605 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner20bbac32008-01-14 01:17:44 +00001606 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001607
Chris Lattner20bbac32008-01-14 01:17:44 +00001608 // Walk the use list of the global seeing if all the uses are load or store.
1609 // If there is anything else, bail out.
Gabor Greifa75ed762010-07-12 14:13:15 +00001610 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1611 User *U = *I;
1612 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner20bbac32008-01-14 01:17:44 +00001613 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001614 }
1615
David Greene44cb8ad2010-01-05 01:28:05 +00001616 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001617
Chris Lattner40e4cec2004-12-12 05:53:50 +00001618 // Create the new global, initializing it to false.
Chris Lattner46b5c642009-11-06 04:27:31 +00001619 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1620 false,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001621 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +00001622 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky431f97e2009-05-03 03:49:08 +00001623 GV->getName()+".b",
Joey Gouly58bf9512013-01-10 10:31:11 +00001624 GV->getThreadLocalMode(),
1625 GV->getType()->getAddressSpace());
Chris Lattner40e4cec2004-12-12 05:53:50 +00001626 GV->getParent()->getGlobalList().insert(GV, NewGV);
1627
1628 Constant *InitVal = GV->getInitializer();
Chris Lattner46b5c642009-11-06 04:27:31 +00001629 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson55f1c092009-08-13 21:58:54 +00001630 "No reason to shrink to bool!");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001631
1632 // If initialized to zero and storing one into the global, we can use a cast
1633 // instead of a select to synthesize the desired value.
1634 bool IsOneZero = false;
1635 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencer2e54a152007-03-02 00:28:52 +00001636 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001637
1638 while (!GV->use_empty()) {
Devang Patelfc507a12009-03-06 01:39:36 +00001639 Instruction *UI = cast<Instruction>(GV->use_back());
1640 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001641 // Change the store into a boolean store.
1642 bool StoringOther = SI->getOperand(0) == OtherVal;
1643 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +00001644 Value *StoreVal;
Bill Wendling7297b862013-02-13 23:00:51 +00001645 if (StoringOther || SI->getOperand(0) == InitVal) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001646 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1647 StoringOther);
Bill Wendling7297b862013-02-13 23:00:51 +00001648 } else {
Chris Lattner745196a2004-12-12 19:34:41 +00001649 // Otherwise, we are storing a previously loaded copy. To do this,
1650 // change the copy from copying the original value to just copying the
1651 // bool.
1652 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1653
Gabor Greif218f5542010-06-24 14:42:01 +00001654 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner745196a2004-12-12 19:34:41 +00001655 // select instruction. If not, it will be a load of the original
1656 // global.
1657 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1658 assert(LI->getOperand(0) == GV && "Not a copy!");
1659 // Insert a new load, to preserve the saved value.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001660 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1661 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner745196a2004-12-12 19:34:41 +00001662 } else {
1663 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1664 "This is not a form that we understand!");
1665 StoreVal = StoredVal->getOperand(0);
1666 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1667 }
1668 }
Nick Lewycky52da72b2012-02-05 19:56:38 +00001669 new StoreInst(StoreVal, NewGV, false, 0,
1670 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patelfc507a12009-03-06 01:39:36 +00001671 } else {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001672 // Change the load into a load of bool then a select.
Devang Patelfc507a12009-03-06 01:39:36 +00001673 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewycky52da72b2012-02-05 19:56:38 +00001674 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1675 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001676 Value *NSI;
1677 if (IsOneZero)
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001678 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001679 else
Gabor Greife9ecc682008-04-06 20:25:17 +00001680 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001681 NSI->takeName(LI);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001682 LI->replaceAllUsesWith(NSI);
Devang Patelfc507a12009-03-06 01:39:36 +00001683 }
1684 UI->eraseFromParent();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001685 }
1686
Bill Wendling7297b862013-02-13 23:00:51 +00001687 // Retain the name of the old global variable. People who are debugging their
1688 // programs may expect these variables to be named the same.
1689 NewGV->takeName(GV);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001690 GV->eraseFromParent();
Chris Lattner20bbac32008-01-14 01:17:44 +00001691 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001692}
1693
1694
Nick Lewycky1480f1d2012-02-12 00:52:26 +00001695/// ProcessGlobal - Analyze the specified global variable and optimize it if
1696/// possible. If we make a change, return true.
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001697bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1698 Module::global_iterator &GVI) {
Rafael Espindoladef1b092012-06-14 22:48:13 +00001699 if (!GV->isDiscardableIfUnused())
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001700 return false;
1701
1702 // Do more involved optimizations if the global is internal.
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001703 GV->removeDeadConstantUsers();
1704
1705 if (GV->use_empty()) {
David Greene44cb8ad2010-01-05 01:28:05 +00001706 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001707 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001708 ++NumDeleted;
1709 return true;
1710 }
1711
Rafael Espindola1821c6c2012-06-15 18:00:24 +00001712 if (!GV->hasLocalLinkage())
1713 return false;
1714
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001715 GlobalStatus GS;
1716
Rafael Espindola3d7fc252013-10-21 17:14:55 +00001717 if (GlobalStatus::analyzeGlobal(GV, GS))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001718 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001719
Rafael Espindola045a78f2013-10-17 18:18:52 +00001720 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001721 GV->setUnnamedAddr(true);
1722 NumUnnamed++;
1723 }
1724
1725 if (GV->isConstant() || !GV->hasInitializer())
1726 return false;
1727
Rafael Espindolad21ac192013-09-05 19:15:21 +00001728 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001729}
1730
1731/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1732/// it if possible. If we make a change, return true.
1733bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1734 Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001735 const GlobalStatus &GS) {
Alexey Samsonova1944e62013-10-07 19:03:24 +00001736 // If this is a first class global and has only one accessing function
1737 // and this function is main (which we know is not recursive), we replace
1738 // the global with a local alloca in this function.
1739 //
Alp Tokerf907b892013-12-05 05:44:44 +00001740 // NOTE: It doesn't make sense to promote non-single-value types since we
Alexey Samsonova1944e62013-10-07 19:03:24 +00001741 // are just replacing static memory to stack memory.
1742 //
1743 // If the global is in different address space, don't bring it to stack.
1744 if (!GS.HasMultipleAccessingFunctions &&
1745 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1746 GV->getType()->getElementType()->isSingleValueType() &&
1747 GS.AccessingFunction->getName() == "main" &&
1748 GS.AccessingFunction->hasExternalLinkage() &&
1749 GV->getType()->getAddressSpace() == 0) {
1750 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1751 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1752 ->getEntryBlock().begin());
1753 Type *ElemTy = GV->getType()->getElementType();
1754 // FIXME: Pass Global's alignment when globals have alignment
1755 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1756 if (!isa<UndefValue>(GV->getInitializer()))
1757 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1758
1759 GV->replaceAllUsesWith(Alloca);
1760 GV->eraseFromParent();
1761 ++NumLocalized;
1762 return true;
1763 }
1764
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001765 // If the global is never loaded (but may be stored to), it is dead.
1766 // Delete it now.
Rafael Espindola045a78f2013-10-17 18:18:52 +00001767 if (!GS.IsLoaded) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001768 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1769
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001770 bool Changed;
1771 if (isLeakCheckerRoot(GV)) {
1772 // Delete any constant stores to the global.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001773 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001774 } else {
1775 // Delete any stores we can find to the global. We may not be able to
1776 // make it completely dead though.
1777 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1778 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001779
1780 // If the global is dead now, delete it.
1781 if (GV->use_empty()) {
1782 GV->eraseFromParent();
1783 ++NumDeleted;
1784 Changed = true;
1785 }
1786 return Changed;
1787
Rafael Espindola045a78f2013-10-17 18:18:52 +00001788 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00001789 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001790 GV->setConstant(true);
1791
1792 // Clean up any obviously simplifiable users now.
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001793 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001794
1795 // If the global is dead now, just nuke it.
1796 if (GV->use_empty()) {
1797 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1798 << "all users and delete global!\n");
1799 GV->eraseFromParent();
1800 ++NumDeleted;
1801 }
1802
1803 ++NumMarked;
1804 return true;
1805 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001806 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001807 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1808 GVI = FirstNewGV; // Don't skip the newly produced globals!
1809 return true;
1810 }
Rafael Espindola045a78f2013-10-17 18:18:52 +00001811 } else if (GS.StoredType == GlobalStatus::StoredOnce) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001812 // If the initial value for the global was an undef value, and if only
1813 // one other value was stored into it, we can just change the
1814 // initializer to be the stored value, then delete all stores to the
1815 // global. This allows us to mark it constant.
1816 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1817 if (isa<UndefValue>(GV->getInitializer())) {
1818 // Change the initial value here.
1819 GV->setInitializer(SOVConstant);
1820
1821 // Clean up any obviously simplifiable users now.
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001822 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001823
1824 if (GV->use_empty()) {
1825 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001826 << "simplify all users and delete global!\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001827 GV->eraseFromParent();
1828 ++NumDeleted;
1829 } else {
1830 GVI = GV;
1831 }
1832 ++NumSubstitute;
1833 return true;
1834 }
1835
1836 // Try to optimize globals based on the knowledge that only one value
1837 // (besides its initializer) is ever stored to the global.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001838 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001839 TD, TLI))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001840 return true;
1841
1842 // Otherwise, if the global was not a boolean, we can shrink it to be a
1843 // boolean.
Eli Friedman33d37002013-09-09 22:00:13 +00001844 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1845 if (GS.Ordering == NotAtomic) {
1846 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1847 ++NumShrunkToBool;
1848 return true;
1849 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001850 }
Eli Friedman33d37002013-09-09 22:00:13 +00001851 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001852 }
1853
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001854 return false;
1855}
1856
Chris Lattnera4c80222005-05-08 22:18:06 +00001857/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1858/// function, changing them to FastCC.
1859static void ChangeCalleesToFastCall(Function *F) {
1860 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadca0c4992012-05-12 08:30:16 +00001861 if (isa<BlockAddress>(*UI))
1862 continue;
Duncan Sands85fab3a2008-02-18 17:32:13 +00001863 CallSite User(cast<Instruction>(*UI));
1864 User.setCallingConv(CallingConv::Fast);
Chris Lattnera4c80222005-05-08 22:18:06 +00001865 }
1866}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001867
Bill Wendlinge94d8432012-12-07 23:16:57 +00001868static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner8a923e72008-03-12 17:45:29 +00001869 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling57625a42013-01-25 23:09:36 +00001870 unsigned Index = Attrs.getSlotIndex(i);
1871 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands85fab3a2008-02-18 17:32:13 +00001872 continue;
1873
Duncan Sands85fab3a2008-02-18 17:32:13 +00001874 // There can be only one.
Bill Wendling57625a42013-01-25 23:09:36 +00001875 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands573b3f82008-02-16 20:56:04 +00001876 }
1877
1878 return Attrs;
1879}
1880
1881static void RemoveNestAttribute(Function *F) {
Bill Wendling85a64c22012-10-14 06:39:53 +00001882 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001883 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadca0c4992012-05-12 08:30:16 +00001884 if (isa<BlockAddress>(*UI))
1885 continue;
Duncan Sands85fab3a2008-02-18 17:32:13 +00001886 CallSite User(cast<Instruction>(*UI));
Bill Wendling85a64c22012-10-14 06:39:53 +00001887 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001888 }
1889}
1890
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001891bool GlobalOpt::OptimizeFunctions(Module &M) {
1892 bool Changed = false;
1893 // Optimize functions.
1894 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1895 Function *F = FI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001896 // Functions without names cannot be referenced outside this module.
1897 if (!F->hasName() && !F->isDeclaration())
1898 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001899 F->removeDeadConstantUsers();
Eli Friedman1923a332011-10-20 05:23:42 +00001900 if (F->isDefTriviallyDead()) {
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +00001901 F->eraseFromParent();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001902 Changed = true;
1903 ++NumFnDeleted;
Rafael Espindola6de96a12009-01-15 20:18:42 +00001904 } else if (F->hasLocalLinkage()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001905 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad557169d2009-06-10 08:41:11 +00001906 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001907 // If this function has C calling conventions, is not a varargs
1908 // function, and is only called directly, promote it to use the Fast
1909 // calling convention.
1910 F->setCallingConv(CallingConv::Fast);
1911 ChangeCalleesToFastCall(F);
1912 ++NumFastCallFns;
1913 Changed = true;
1914 }
1915
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001916 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad557169d2009-06-10 08:41:11 +00001917 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001918 // The function is not used by a trampoline intrinsic, so it is safe
1919 // to remove the 'nest' attribute.
1920 RemoveNestAttribute(F);
1921 ++NumNestRemoved;
1922 Changed = true;
1923 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001924 }
1925 }
1926 return Changed;
1927}
1928
1929bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1930 bool Changed = false;
1931 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1932 GVI != E; ) {
1933 GlobalVariable *GV = GVI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001934 // Global variables without names cannot be referenced outside this module.
1935 if (!GV->hasName() && !GV->isDeclaration())
1936 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman580b80d2009-11-23 16:22:21 +00001937 // Simplify the initializer.
1938 if (GV->hasInitializer())
1939 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosier43a33062011-12-02 01:26:24 +00001940 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman580b80d2009-11-23 16:22:21 +00001941 if (New && New != CE)
1942 GV->setInitializer(New);
1943 }
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001944
1945 Changed |= ProcessGlobal(GV, GVI);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001946 }
1947 return Changed;
1948}
1949
Nick Lewycky466d0c12011-04-08 07:30:21 +00001950/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001951/// initializers have an init priority of 65535.
1952GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001953 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1954 if (GV == 0) return 0;
Jakub Staszak9525a772012-12-06 21:57:16 +00001955
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001956 // Verify that the initializer is simple enough for us to handle. We are
1957 // only allowed to optimize the initializer if it is unique.
1958 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky0f857892011-04-11 22:11:20 +00001959
1960 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1961 return GV;
1962 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman9cca0712011-04-09 09:11:09 +00001963
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001964 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky0f857892011-04-11 22:11:20 +00001965 if (isa<ConstantAggregateZero>(*i))
1966 continue;
1967 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001968 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1969 continue;
Chris Lattner838bdc12005-09-26 02:19:27 +00001970
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001971 // Must have a function or null ptr.
1972 if (!isa<Function>(CS->getOperand(1)))
1973 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001974
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001975 // Init priority must be standard.
Nick Lewycky466d0c12011-04-08 07:30:21 +00001976 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1977 if (CI->getZExtValue() != 65535)
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001978 return 0;
1979 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001980
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001981 return GV;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001982}
1983
Chris Lattner696beef2005-09-26 02:31:18 +00001984/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1985/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001986static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky0f857892011-04-11 22:11:20 +00001987 if (GV->getInitializer()->isNullValue())
1988 return std::vector<Function*>();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001989 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1990 std::vector<Function*> Result;
1991 Result.reserve(CA->getNumOperands());
Gabor Greif3a9fba52008-05-29 01:59:18 +00001992 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1993 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001994 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1995 }
1996 return Result;
1997}
1998
Chris Lattner696beef2005-09-26 02:31:18 +00001999/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2000/// specified array, returning the new global to use.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002001static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner46b5c642009-11-06 04:27:31 +00002002 const std::vector<Function*> &Ctors) {
Chris Lattner696beef2005-09-26 02:31:18 +00002003 // If we made a change, reassemble the initializer list.
Chris Lattnercc19efa2011-06-20 04:01:31 +00002004 Constant *CSVals[2];
2005 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2006 CSVals[1] = 0;
2007
Chris Lattner229907c2011-07-18 04:54:35 +00002008 StructType *StructTy =
Matt Arsenault404c60a2013-10-21 19:43:56 +00002009 cast<StructType>(GCL->getType()->getElementType()->getArrayElementType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002010
Chris Lattner696beef2005-09-26 02:31:18 +00002011 // Create the new init list.
2012 std::vector<Constant*> CAList;
2013 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002014 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00002015 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00002016 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002017 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner46b5c642009-11-06 04:27:31 +00002018 false);
Chris Lattner229907c2011-07-18 04:54:35 +00002019 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Anderson5a1acd92009-07-31 20:28:14 +00002020 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner46b5c642009-11-06 04:27:31 +00002021 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky0f857892011-04-11 22:11:20 +00002022 0x7fffffff);
Chris Lattner696beef2005-09-26 02:31:18 +00002023 }
Chris Lattnercc19efa2011-06-20 04:01:31 +00002024 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattner696beef2005-09-26 02:31:18 +00002025 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002026
Chris Lattner696beef2005-09-26 02:31:18 +00002027 // Create the array initializer.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002028 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewycky1303c0a2009-09-19 20:30:26 +00002029 CAList.size()), CAList);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002030
Chris Lattner696beef2005-09-26 02:31:18 +00002031 // If we didn't change the number of elements, don't create a new GV.
2032 if (CA->getType() == GCL->getInitializer()->getType()) {
2033 GCL->setInitializer(CA);
2034 return GCL;
2035 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002036
Chris Lattner696beef2005-09-26 02:31:18 +00002037 // Create the new global and insert it next to the existing list.
Chris Lattner46b5c642009-11-06 04:27:31 +00002038 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +00002039 GCL->getLinkage(), CA, "",
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002040 GCL->getThreadLocalMode());
Chris Lattner696beef2005-09-26 02:31:18 +00002041 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00002042 NGV->takeName(GCL);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002043
Chris Lattner696beef2005-09-26 02:31:18 +00002044 // Nuke the old list, replacing any uses with the new one.
2045 if (!GCL->use_empty()) {
2046 Constant *V = NGV;
2047 if (V->getType() != GCL->getType())
Owen Anderson487375e2009-07-29 18:55:55 +00002048 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattner696beef2005-09-26 02:31:18 +00002049 GCL->replaceAllUsesWith(V);
2050 }
2051 GCL->eraseFromParent();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002052
Chris Lattner696beef2005-09-26 02:31:18 +00002053 if (Ctors.size())
2054 return NGV;
2055 else
2056 return 0;
2057}
Chris Lattner99e23fa2005-09-26 04:44:35 +00002058
2059
Jakub Staszak9525a772012-12-06 21:57:16 +00002060static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002061isSimpleEnoughValueToCommit(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002062 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002063 const DataLayout *TD);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002064
2065
2066/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2067/// handled by the code generator. We don't want to generate something like:
2068/// void *X = &X/42;
2069/// because the code generator doesn't have a relocation that can handle that.
2070///
2071/// This function should be called if C was not found (but just got inserted)
2072/// in SimpleConstants to avoid having to rescan the same constants all the
2073/// time.
2074static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002075 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002076 const DataLayout *TD) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002077 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2078 // all supported.
2079 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2080 isa<GlobalValue>(C))
2081 return true;
Jakub Staszak9525a772012-12-06 21:57:16 +00002082
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002083 // Aggregate values are safe if all their elements are.
2084 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2085 isa<ConstantVector>(C)) {
2086 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2087 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedman55fa49f32012-01-05 23:03:32 +00002088 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002089 return false;
2090 }
2091 return true;
2092 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002093
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002094 // We don't know exactly what relocations are allowed in constant expressions,
2095 // so we allow &global+constantoffset, which is safe and uniformly supported
2096 // across targets.
2097 ConstantExpr *CE = cast<ConstantExpr>(C);
2098 switch (CE->getOpcode()) {
2099 case Instruction::BitCast:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002100 // Bitcast is fine if the casted value is fine.
2101 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2102
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002103 case Instruction::IntToPtr:
2104 case Instruction::PtrToInt:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002105 // int <=> ptr is fine if the int type is the same size as the
2106 // pointer type.
2107 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2108 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2109 return false;
2110 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak9525a772012-12-06 21:57:16 +00002111
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002112 // GEP is fine if it is simple + constant offset.
2113 case Instruction::GetElementPtr:
2114 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2115 if (!isa<ConstantInt>(CE->getOperand(i)))
2116 return false;
Eli Friedman55fa49f32012-01-05 23:03:32 +00002117 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak9525a772012-12-06 21:57:16 +00002118
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002119 case Instruction::Add:
2120 // We allow simple+cst.
2121 if (!isa<ConstantInt>(CE->getOperand(1)))
2122 return false;
Eli Friedman55fa49f32012-01-05 23:03:32 +00002123 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002124 }
2125 return false;
2126}
2127
Jakub Staszak9525a772012-12-06 21:57:16 +00002128static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002129isSimpleEnoughValueToCommit(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002130 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002131 const DataLayout *TD) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002132 // If we already checked this constant, we win.
2133 if (!SimpleConstants.insert(C)) return true;
2134 // Check the constant.
Eli Friedman55fa49f32012-01-05 23:03:32 +00002135 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002136}
2137
2138
Chris Lattner99e23fa2005-09-26 04:44:35 +00002139/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002140/// enough for us to understand. In particular, if it is a cast to anything
2141/// other than from one pointer type to another pointer type, we punt.
2142/// We basically just support direct accesses to globals and GEP's of
Chris Lattner99e23fa2005-09-26 04:44:35 +00002143/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner46b5c642009-11-06 04:27:31 +00002144static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohman82e74752009-09-07 22:42:05 +00002145 // Conservatively, avoid aggregate types. This is because we don't
2146 // want to worry about them partially overlapping other stores.
2147 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2148 return false;
2149
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002150 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002151 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002152 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002153 return GV->hasUniqueInitializer();
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002154
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002155 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002156 // Handle a constantexpr gep.
2157 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanbeee35a2009-09-07 22:40:13 +00002158 isa<GlobalVariable>(CE->getOperand(0)) &&
2159 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002160 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002161 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002162 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002163 if (!GV->hasUniqueInitializer())
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002164 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002165
Dan Gohman161429f2009-09-07 22:44:55 +00002166 // The first index must be zero.
Oscar Fuentes40b31ad2010-08-02 06:00:15 +00002167 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman161429f2009-09-07 22:44:55 +00002168 if (!CI || !CI->isZero()) return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002169
2170 // The remaining indices must be compile-time known integers within the
Dan Gohman7190d482009-09-10 23:37:55 +00002171 // notional bounds of the corresponding static array types.
2172 if (!CE->isGEPWithNoNotionalOverIndexing())
2173 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002174
Dan Gohmane525d9d2009-10-05 16:36:26 +00002175 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak9525a772012-12-06 21:57:16 +00002176
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002177 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2178 // and we know how to evaluate it by moving the bitcast from the pointer
2179 // operand to the value operand.
2180 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner8b4952f2011-01-16 02:05:10 +00002181 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002182 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2183 // external globals.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002184 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner46af55e2005-09-26 06:52:44 +00002185 }
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002186 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002187
Chris Lattner99e23fa2005-09-26 04:44:35 +00002188 return false;
2189}
2190
Chris Lattner46af55e2005-09-26 06:52:44 +00002191/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2192/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2193/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2194static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002195 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002196 // Base case of the recursion.
2197 if (OpNo == Addr->getNumOperands()) {
2198 assert(Val->getType() == Init->getType() && "Type mismatch!");
2199 return Val;
2200 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002201
Chris Lattner0256be92012-01-27 03:08:05 +00002202 SmallVector<Constant*, 32> Elts;
Chris Lattner229907c2011-07-18 04:54:35 +00002203 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002204 // Break up the constant into its elements.
Chris Lattnerfa775002012-01-26 02:32:04 +00002205 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2206 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002207
Chris Lattner46af55e2005-09-26 06:52:44 +00002208 // Replace the element that we are supposed to.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002209 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2210 unsigned Idx = CU->getZExtValue();
2211 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002212 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002213
Chris Lattner46af55e2005-09-26 06:52:44 +00002214 // Return the modified struct.
Chris Lattnercc19efa2011-06-20 04:01:31 +00002215 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002216 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002217
Chris Lattnercc19efa2011-06-20 04:01:31 +00002218 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattner229907c2011-07-18 04:54:35 +00002219 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnercc19efa2011-06-20 04:01:31 +00002220
2221 uint64_t NumElts;
Chris Lattner229907c2011-07-18 04:54:35 +00002222 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnercc19efa2011-06-20 04:01:31 +00002223 NumElts = ATy->getNumElements();
2224 else
Chris Lattnerfa775002012-01-26 02:32:04 +00002225 NumElts = InitTy->getVectorNumElements();
Chris Lattnercc19efa2011-06-20 04:01:31 +00002226
2227 // Break up the array into elements.
Chris Lattnerfa775002012-01-26 02:32:04 +00002228 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2229 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnercc19efa2011-06-20 04:01:31 +00002230
2231 assert(CI->getZExtValue() < NumElts);
2232 Elts[CI->getZExtValue()] =
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002233 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnercc19efa2011-06-20 04:01:31 +00002234
2235 if (Init->getType()->isArrayTy())
2236 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2237 return ConstantVector::get(Elts);
Chris Lattner46af55e2005-09-26 06:52:44 +00002238}
2239
Chris Lattner99e23fa2005-09-26 04:44:35 +00002240/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2241/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner46b5c642009-11-06 04:27:31 +00002242static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002243 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2244 assert(GV->hasInitializer());
2245 GV->setInitializer(Val);
2246 return;
2247 }
Chris Lattner64ecc462010-01-07 01:16:21 +00002248
Chris Lattner46af55e2005-09-26 06:52:44 +00002249 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2250 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002251 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner99e23fa2005-09-26 04:44:35 +00002252}
2253
Nick Lewycky60829a582012-02-20 03:25:59 +00002254namespace {
2255
2256/// Evaluator - This class evaluates LLVM IR, producing the Constant
2257/// representing each SSA instruction. Changes to global variables are stored
2258/// in a mapping that can be iterated over after the evaluation is complete.
2259/// Once an evaluation call fails, the evaluation object should not be reused.
2260class Evaluator {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002261public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002262 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002263 : TD(TD), TLI(TLI) {
2264 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2265 }
2266
Nick Lewycky60829a582012-02-20 03:25:59 +00002267 ~Evaluator() {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002268 DeleteContainerPointers(ValueStack);
2269 while (!AllocaTmps.empty()) {
2270 GlobalVariable *Tmp = AllocaTmps.back();
2271 AllocaTmps.pop_back();
2272
2273 // If there are still users of the alloca, the program is doing something
2274 // silly, e.g. storing the address of the alloca somewhere and using it
2275 // later. Since this is undefined, we'll just make it be null.
2276 if (!Tmp->use_empty())
2277 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2278 delete Tmp;
2279 }
2280 }
2281
2282 /// EvaluateFunction - Evaluate a call to function F, returning true if
2283 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2284 /// arguments for the function.
2285 bool EvaluateFunction(Function *F, Constant *&RetVal,
2286 const SmallVectorImpl<Constant*> &ActualArgs);
2287
2288 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2289 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2290 /// control flows into, or null upon return.
2291 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2292
2293 Constant *getVal(Value *V) {
2294 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2295 Constant *R = ValueStack.back()->lookup(V);
2296 assert(R && "Reference to an uncomputed value!");
2297 return R;
2298 }
2299
2300 void setVal(Value *V, Constant *C) {
2301 ValueStack.back()->operator[](V) = C;
2302 }
2303
2304 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2305 return MutatedMemory;
2306 }
2307
2308 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2309 return Invariants;
2310 }
2311
2312private:
2313 Constant *ComputeLoadResult(Constant *P);
2314
2315 /// ValueStack - As we compute SSA register values, we store their contents
2316 /// here. The back of the vector contains the current function and the stack
2317 /// contains the values in the calling frames.
2318 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2319
2320 /// CallStack - This is used to detect recursion. In pathological situations
2321 /// we could hit exponential behavior, but at least there is nothing
2322 /// unbounded.
2323 SmallVector<Function*, 4> CallStack;
2324
2325 /// MutatedMemory - For each store we execute, we update this map. Loads
2326 /// check this to get the most up-to-date value. If evaluation is successful,
2327 /// this state is committed to the process.
2328 DenseMap<Constant*, Constant*> MutatedMemory;
2329
2330 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2331 /// to represent its body. This vector is needed so we can delete the
2332 /// temporary globals when we are done.
2333 SmallVector<GlobalVariable*, 32> AllocaTmps;
2334
2335 /// Invariants - These global variables have been marked invariant by the
2336 /// static constructor.
2337 SmallPtrSet<GlobalVariable*, 8> Invariants;
2338
2339 /// SimpleConstants - These are constants we have checked and know to be
2340 /// simple enough to live in a static initializer of a global.
2341 SmallPtrSet<Constant*, 8> SimpleConstants;
2342
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002343 const DataLayout *TD;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002344 const TargetLibraryInfo *TLI;
2345};
2346
Nick Lewycky60829a582012-02-20 03:25:59 +00002347} // anonymous namespace
2348
Chris Lattnerb0096632005-09-26 05:16:34 +00002349/// ComputeLoadResult - Return the value that would be computed by a load from
2350/// P after the stores reflected by 'memory' have been performed. If we can't
2351/// decide, return null.
Nick Lewycky60829a582012-02-20 03:25:59 +00002352Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner4b05c322005-09-26 05:15:37 +00002353 // If this memory location has been recently stored, use the stored value: it
2354 // is the most up-to-date.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002355 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2356 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002357
Chris Lattner4b05c322005-09-26 05:15:37 +00002358 // Access it.
2359 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002360 if (GV->hasDefinitiveInitializer())
Chris Lattner4b05c322005-09-26 05:15:37 +00002361 return GV->getInitializer();
2362 return 0;
Chris Lattner4b05c322005-09-26 05:15:37 +00002363 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002364
Chris Lattner46af55e2005-09-26 06:52:44 +00002365 // Handle a constantexpr getelementptr.
2366 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2367 if (CE->getOpcode() == Instruction::GetElementPtr &&
2368 isa<GlobalVariable>(CE->getOperand(0))) {
2369 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002370 if (GV->hasDefinitiveInitializer())
Dan Gohmane525d9d2009-10-05 16:36:26 +00002371 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner46af55e2005-09-26 06:52:44 +00002372 }
2373
2374 return 0; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00002375}
2376
Nick Lewycky239fdf02012-02-06 08:24:44 +00002377/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2378/// successful, false if we can't evaluate it. NewBB returns the next BB that
2379/// control flows into, or null upon return.
Nick Lewycky60829a582012-02-20 03:25:59 +00002380bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2381 BasicBlock *&NextBB) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002382 // This is the main evaluation loop.
2383 while (1) {
2384 Constant *InstResult = 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002385
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002386 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2387
Chris Lattner99e23fa2005-09-26 04:44:35 +00002388 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002389 if (!SI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002390 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2391 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002392 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002393 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002394 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002395 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002396 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002397 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002398 }
2399 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002400 // If this is too complex for us to commit, reject it.
Michael Gottesman2a654272013-01-11 23:08:52 +00002401 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002402 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002403 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002404
Nick Lewycky73be5e32012-02-19 23:26:27 +00002405 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002406
2407 // If this might be too difficult for the backend to handle (e.g. the addr
2408 // of one global variable divided by another) then we can't commit it.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002409 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002410 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2411 << "\n");
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002412 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002413 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002414
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002415 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002416 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002417 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002418 // If we're evaluating a store through a bitcast, then we need
2419 // to pull the bitcast off the pointer type and push it onto the
2420 // stored value.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002421 Ptr = CE->getOperand(0);
Jakub Staszak9525a772012-12-06 21:57:16 +00002422
Nick Lewycky239fdf02012-02-06 08:24:44 +00002423 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak9525a772012-12-06 21:57:16 +00002424
Owen Anderson4e54efd2011-01-16 04:33:33 +00002425 // In order to push the bitcast onto the stored value, a bitcast
2426 // from NewTy to Val's type must be legal. If it's not, we can try
2427 // introspecting NewTy to find a legal conversion.
2428 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2429 // If NewTy is a struct, we can convert the pointer to the struct
2430 // into a pointer to its first member.
2431 // FIXME: This could be extended to support arrays as well.
Chris Lattner229907c2011-07-18 04:54:35 +00002432 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson4e54efd2011-01-16 04:33:33 +00002433 NewTy = STy->getTypeAtIndex(0U);
2434
Nick Lewycky239fdf02012-02-06 08:24:44 +00002435 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson4e54efd2011-01-16 04:33:33 +00002436 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2437 Constant * const IdxList[] = {IdxZero, IdxZero};
2438
Jay Foad17bab442011-07-22 08:52:50 +00002439 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002440 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2441 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2442
Owen Anderson4e54efd2011-01-16 04:33:33 +00002443 // If we can't improve the situation by introspecting NewTy,
2444 // we have to give up.
2445 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002446 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2447 "evaluate.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002448 return false;
Owen Anderson4e54efd2011-01-16 04:33:33 +00002449 }
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002450 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002451
Owen Anderson4e54efd2011-01-16 04:33:33 +00002452 // If we found compatible types, go ahead and push the bitcast
2453 // onto the stored value.
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002454 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002455
Michael Gottesman2a654272013-01-11 23:08:52 +00002456 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002457 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002458 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002459
Chris Lattner99e23fa2005-09-26 04:44:35 +00002460 MutatedMemory[Ptr] = Val;
2461 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002462 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002463 getVal(BO->getOperand(0)),
2464 getVal(BO->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002465 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002466 << "\n");
Reid Spencer266e42b2006-12-23 06:05:41 +00002467 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002468 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002469 getVal(CI->getOperand(0)),
2470 getVal(CI->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002471 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002472 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002473 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002474 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002475 getVal(CI->getOperand(0)),
Chris Lattner99e23fa2005-09-26 04:44:35 +00002476 CI->getType());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002477 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002478 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002479 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002480 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2481 getVal(SI->getOperand(1)),
2482 getVal(SI->getOperand(2)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002483 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002484 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002485 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002486 Constant *P = getVal(GEP->getOperand(0));
Chris Lattnerf96f4a82007-01-31 04:40:53 +00002487 SmallVector<Constant*, 8> GEPOps;
Gabor Greif3a9fba52008-05-29 01:59:18 +00002488 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2489 i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002490 GEPOps.push_back(getVal(*i));
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002491 InstResult =
2492 ConstantExpr::getGetElementPtr(P, GEPOps,
2493 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002494 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002495 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002496 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002497
2498 if (!LI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002499 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2500 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002501 }
2502
Nick Lewycky9d0da182012-02-21 22:08:06 +00002503 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002504 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Nick Lewycky9d0da182012-02-21 22:08:06 +00002505 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002506 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2507 "folding: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002508 }
Nick Lewycky9d0da182012-02-21 22:08:06 +00002509 InstResult = ComputeLoadResult(Ptr);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002510 if (InstResult == 0) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002511 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2512 "\n");
2513 return false; // Could not evaluate load.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002514 }
2515
2516 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002517 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002518 if (AI->isArrayAllocation()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002519 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2520 return false; // Cannot handle array allocs.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002521 }
Chris Lattner229907c2011-07-18 04:54:35 +00002522 Type *Ty = AI->getType()->getElementType();
Chris Lattner46b5c642009-11-06 04:27:31 +00002523 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002524 GlobalValue::InternalLinkage,
Owen Andersonb292b8c2009-07-30 23:03:37 +00002525 UndefValue::get(Ty),
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002526 AI->getName()));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002527 InstResult = AllocaTmps.back();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002528 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002529 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2530 CallSite CS(CurInst);
Devang Patel04852aa2009-03-09 23:04:12 +00002531
2532 // Debug info can safely be ignored here.
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002533 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002534 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel04852aa2009-03-09 23:04:12 +00002535 ++CurInst;
2536 continue;
2537 }
2538
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002539 // Cannot handle inline asm.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002540 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002541 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2542 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002543 }
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002544
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002545 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2546 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002547 if (MSI->isVolatile()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002548 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2549 "intrinsic.\n");
2550 return false;
2551 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002552 Constant *Ptr = getVal(MSI->getDest());
2553 Constant *Val = getVal(MSI->getValue());
2554 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002555 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2556 // This memset is a no-op.
Michael Gottesman2a654272013-01-11 23:08:52 +00002557 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002558 ++CurInst;
2559 continue;
2560 }
2561 }
2562
2563 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2564 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002565 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002566 ++CurInst;
2567 continue;
2568 }
2569
2570 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2571 // We don't insert an entry into Values, as it doesn't have a
2572 // meaningful return value.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002573 if (!II->use_empty()) {
Alp Tokerf907b892013-12-05 05:44:44 +00002574 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002575 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002576 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002577 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky519561f2012-02-20 23:32:26 +00002578 Value *PtrArg = getVal(II->getArgOperand(1));
2579 Value *Ptr = PtrArg->stripPointerCasts();
2580 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2581 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Nick Lewycky5b150372013-07-25 02:55:14 +00002582 if (TD && !Size->isAllOnesValue() &&
Nick Lewycky519561f2012-02-20 23:32:26 +00002583 Size->getValue().getLimitedValue() >=
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002584 TD->getTypeStoreSize(ElemTy)) {
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002585 Invariants.insert(GV);
Michael Gottesman2a654272013-01-11 23:08:52 +00002586 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2587 << "\n");
2588 } else {
2589 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2590 "invariant.\n");
2591 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002592 }
2593 // Continue even if we do nothing.
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002594 ++CurInst;
2595 continue;
2596 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002597
Michael Gottesman2a654272013-01-11 23:08:52 +00002598 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002599 return false;
2600 }
2601
Chris Lattner65a3a092005-09-27 04:45:34 +00002602 // Resolve function pointers.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002603 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002604 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002605 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002606 return false; // Cannot resolve.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002607 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002608
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002609 SmallVector<Constant*, 8> Formals;
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002610 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002611 Formals.push_back(getVal(*i));
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002612
Reid Spencer5301e7c2007-01-30 20:08:39 +00002613 if (Callee->isDeclaration()) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002614 // If this is a function we can constant fold, do it.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002615 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002616 InstResult = C;
Michael Gottesman2a654272013-01-11 23:08:52 +00002617 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2618 *InstResult << "\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002619 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002620 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002621 return false;
2622 }
2623 } else {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002624 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002625 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002626 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002627 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002628
Benjamin Kramer64a857a2013-01-12 15:34:31 +00002629 Constant *RetVal = 0;
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002630 // Execute the call, if successful, use the return value.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002631 ValueStack.push_back(new DenseMap<Value*, Constant*>);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002632 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002633 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002634 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002635 }
Benjamin Kramer93887632012-02-27 12:48:24 +00002636 delete ValueStack.pop_back_val();
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002637 InstResult = RetVal;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002638
Michael Gottesman2a654272013-01-11 23:08:52 +00002639 if (InstResult != NULL) {
2640 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2641 InstResult << "\n\n");
2642 } else {
2643 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2644 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002645 }
Reid Spencerde46e482006-11-02 20:25:50 +00002646 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002647 DEBUG(dbgs() << "Found a terminator instruction.\n");
2648
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002649 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2650 if (BI->isUnconditional()) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002651 NextBB = BI->getSuccessor(0);
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002652 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002653 ConstantInt *Cond =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002654 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner15649082007-01-12 18:30:11 +00002655 if (!Cond) return false; // Cannot determine.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002656
Nick Lewycky239fdf02012-02-06 08:24:44 +00002657 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002658 }
2659 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2660 ConstantInt *Val =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002661 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00002662 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002663 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattner31274882009-10-29 05:51:50 +00002664 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002665 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattner31274882009-10-29 05:51:50 +00002666 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002667 NextBB = BA->getBasicBlock();
Chris Lattneraa99c942009-11-01 01:27:45 +00002668 else
2669 return false; // Cannot determine.
Nick Lewycky239fdf02012-02-06 08:24:44 +00002670 } else if (isa<ReturnInst>(CurInst)) {
2671 NextBB = 0;
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002672 } else {
Bill Wendlingf891bf82011-07-31 06:30:59 +00002673 // invoke, unwind, resume, unreachable.
Michael Gottesman2a654272013-01-11 23:08:52 +00002674 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002675 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002676 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002677
Nick Lewycky239fdf02012-02-06 08:24:44 +00002678 // We succeeded at evaluating this block!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002679 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002680 return true;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002681 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002682 // Did not know how to evaluate this!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002683 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesman2a654272013-01-11 23:08:52 +00002684 "\n");
Chris Lattner65a3a092005-09-27 04:45:34 +00002685 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002686 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002687
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002688 if (!CurInst->use_empty()) {
2689 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosier43a33062011-12-02 01:26:24 +00002690 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Jakub Staszak9525a772012-12-06 21:57:16 +00002691
Nick Lewycky73be5e32012-02-19 23:26:27 +00002692 setVal(CurInst, InstResult);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002693 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002694
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002695 // If we just processed an invoke, we finished evaluating the block.
2696 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2697 NextBB = II->getNormalDest();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002698 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002699 return true;
2700 }
2701
Chris Lattner99e23fa2005-09-26 04:44:35 +00002702 // Advance program counter.
2703 ++CurInst;
2704 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00002705}
2706
Nick Lewycky239fdf02012-02-06 08:24:44 +00002707/// EvaluateFunction - Evaluate a call to function F, returning true if
2708/// successful, false if we can't evaluate it. ActualArgs contains the formal
2709/// arguments for the function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002710bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2711 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002712 // Check to see if this function is already executing (recursion). If so,
2713 // bail out. TODO: we might want to accept limited recursion.
2714 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2715 return false;
2716
2717 CallStack.push_back(F);
2718
Nick Lewycky239fdf02012-02-06 08:24:44 +00002719 // Initialize arguments to the incoming values specified.
2720 unsigned ArgNo = 0;
2721 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2722 ++AI, ++ArgNo)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002723 setVal(AI, ActualArgs[ArgNo]);
Nick Lewycky239fdf02012-02-06 08:24:44 +00002724
2725 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2726 // we can only evaluate any one basic block at most once. This set keeps
2727 // track of what we have executed so we can detect recursive cases etc.
2728 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2729
2730 // CurBB - The current basic block we're evaluating.
2731 BasicBlock *CurBB = F->begin();
2732
Nick Lewycky4231c412012-02-12 00:47:24 +00002733 BasicBlock::iterator CurInst = CurBB->begin();
2734
Nick Lewycky239fdf02012-02-06 08:24:44 +00002735 while (1) {
Duncan Sands4730cb92012-02-23 08:23:06 +00002736 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002737 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2738
Nick Lewycky73be5e32012-02-19 23:26:27 +00002739 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002740 return false;
2741
2742 if (NextBB == 0) {
2743 // Successfully running until there's no next block means that we found
2744 // the return. Fill it the return value and pop the call stack.
2745 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2746 if (RI->getNumOperands())
Nick Lewycky73be5e32012-02-19 23:26:27 +00002747 RetVal = getVal(RI->getOperand(0));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002748 CallStack.pop_back();
2749 return true;
2750 }
2751
2752 // Okay, we succeeded in evaluating this control flow. See if we have
2753 // executed the new block before. If so, we have a looping function,
2754 // which we cannot evaluate in reasonable time.
2755 if (!ExecutedBlocks.insert(NextBB))
2756 return false; // looped!
2757
2758 // Okay, we have never been in this block before. Check to see if there
2759 // are any PHI nodes. If so, evaluate them with information about where
2760 // we came from.
2761 PHINode *PN = 0;
Nick Lewycky4231c412012-02-12 00:47:24 +00002762 for (CurInst = NextBB->begin();
2763 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002764 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002765
2766 // Advance to the next block.
2767 CurBB = NextBB;
2768 }
2769}
2770
Chris Lattnerda1889b2005-09-27 04:27:01 +00002771/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2772/// we can. Return true if we can, false otherwise.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002773static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosiere6de63d2011-12-01 21:29:16 +00002774 const TargetLibraryInfo *TLI) {
Chris Lattnerda1889b2005-09-27 04:27:01 +00002775 // Call the function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002776 Evaluator Eval(TD, TLI);
Chris Lattner65a3a092005-09-27 04:45:34 +00002777 Constant *RetValDummy;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002778 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2779 SmallVector<Constant*, 0>());
Jakub Staszak9525a772012-12-06 21:57:16 +00002780
Chris Lattnerda1889b2005-09-27 04:27:01 +00002781 if (EvalSuccess) {
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002782 // We succeeded at evaluation: commit the result.
David Greene44cb8ad2010-01-05 01:28:05 +00002783 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky73be5e32012-02-19 23:26:27 +00002784 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00002785 << " stores.\n");
Nick Lewycky73be5e32012-02-19 23:26:27 +00002786 for (DenseMap<Constant*, Constant*>::const_iterator I =
2787 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewyckyb74ae9c2012-06-24 04:07:14 +00002788 I != E; ++I)
Chris Lattner46b5c642009-11-06 04:27:31 +00002789 CommitValueTo(I->second, I->first);
Nick Lewycky73be5e32012-02-19 23:26:27 +00002790 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2791 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2792 I != E; ++I)
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002793 (*I)->setConstant(true);
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002794 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002795
Chris Lattnerda1889b2005-09-27 04:27:01 +00002796 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002797}
2798
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002799/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2800/// Return true if anything changed.
2801bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2802 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2803 bool MadeChange = false;
2804 if (Ctors.empty()) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002805
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002806 // Loop over global ctors, optimizing them when we can.
2807 for (unsigned i = 0; i != Ctors.size(); ++i) {
2808 Function *F = Ctors[i];
2809 // Found a null terminator in the middle of the list, prune off the rest of
2810 // the list.
Chris Lattner838bdc12005-09-26 02:19:27 +00002811 if (F == 0) {
2812 if (i != Ctors.size()-1) {
2813 Ctors.resize(i+1);
2814 MadeChange = true;
2815 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002816 break;
2817 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002818 DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002819
Chris Lattner99e23fa2005-09-26 04:44:35 +00002820 // We cannot simplify external ctor functions.
2821 if (F->empty()) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002822
Chris Lattner99e23fa2005-09-26 04:44:35 +00002823 // If we can evaluate the ctor at compile time, do.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002824 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002825 Ctors.erase(Ctors.begin()+i);
2826 MadeChange = true;
2827 --i;
2828 ++NumCtorsEvaluated;
2829 continue;
2830 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002831 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002832
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002833 if (!MadeChange) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002834
Chris Lattner46b5c642009-11-06 04:27:31 +00002835 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002836 return true;
2837}
2838
Benjamin Kramer8817cca2013-09-22 14:09:50 +00002839static int compareNames(Constant *const *A, Constant *const *B) {
2840 return (*A)->getName().compare((*B)->getName());
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002841}
Rafael Espindola00752162013-05-09 17:22:59 +00002842
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002843static void setUsedInitializer(GlobalVariable &V,
2844 SmallPtrSet<GlobalValue *, 8> Init) {
Rafael Espindolac2bb73f2013-07-20 23:33:15 +00002845 if (Init.empty()) {
2846 V.eraseFromParent();
2847 return;
2848 }
2849
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002850 SmallVector<llvm::Constant *, 8> UsedArray;
2851 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext());
Rafael Espindola00752162013-05-09 17:22:59 +00002852
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002853 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Init.begin(), E = Init.end();
2854 I != E; ++I) {
2855 Constant *Cast = llvm::ConstantExpr::getBitCast(*I, Int8PtrTy);
2856 UsedArray.push_back(Cast);
Rafael Espindola00752162013-05-09 17:22:59 +00002857 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002858 // Sort to get deterministic order.
2859 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
2860 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola00752162013-05-09 17:22:59 +00002861
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002862 Module *M = V.getParent();
2863 V.removeFromParent();
2864 GlobalVariable *NV =
2865 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2866 llvm::ConstantArray::get(ATy, UsedArray), "");
2867 NV->takeName(&V);
2868 NV->setSection("llvm.metadata");
2869 delete &V;
Rafael Espindola00752162013-05-09 17:22:59 +00002870}
2871
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002872namespace {
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002873/// \brief An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002874class LLVMUsed {
2875 SmallPtrSet<GlobalValue *, 8> Used;
2876 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2877 GlobalVariable *UsedV;
2878 GlobalVariable *CompilerUsedV;
2879
2880public:
Rafael Espindolaec2375f2013-07-25 02:50:08 +00002881 LLVMUsed(Module &M) {
Rafael Espindola17600e22013-07-25 03:23:25 +00002882 UsedV = collectUsedGlobalVariables(M, Used, false);
2883 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola00752162013-05-09 17:22:59 +00002884 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002885 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
2886 iterator usedBegin() { return Used.begin(); }
2887 iterator usedEnd() { return Used.end(); }
2888 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2889 iterator compilerUsedEnd() { return CompilerUsed.end(); }
2890 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2891 bool compilerUsedCount(GlobalValue *GV) const {
2892 return CompilerUsed.count(GV);
2893 }
2894 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2895 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2896 bool usedInsert(GlobalValue *GV) { return Used.insert(GV); }
2897 bool compilerUsedInsert(GlobalValue *GV) { return CompilerUsed.insert(GV); }
Rafael Espindola00752162013-05-09 17:22:59 +00002898
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002899 void syncVariablesAndSets() {
2900 if (UsedV)
2901 setUsedInitializer(*UsedV, Used);
2902 if (CompilerUsedV)
2903 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2904 }
2905};
Rafael Espindola00752162013-05-09 17:22:59 +00002906}
2907
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002908static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2909 if (GA.use_empty()) // No use at all.
2910 return false;
2911
2912 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2913 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002914 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002915 if (!GA.hasOneUse())
2916 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002917 // llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002918 return true;
2919
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002920 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002921 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola00752162013-05-09 17:22:59 +00002922}
2923
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002924static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2925 const LLVMUsed &U) {
2926 unsigned N = 2;
2927 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2928 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002929 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002930 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2931 ++N;
2932 return V.hasNUsesOrMore(N);
2933}
2934
2935static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2936 if (!GA.hasLocalLinkage())
2937 return true;
2938
2939 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2940}
2941
2942static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget) {
2943 RenameTarget = false;
Rafael Espindola00752162013-05-09 17:22:59 +00002944 bool Ret = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002945 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola00752162013-05-09 17:22:59 +00002946 Ret = true;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002947
2948 // If the alias is externally visible, we may still be able to simplify it.
2949 if (!mayHaveOtherReferences(GA, U))
2950 return Ret;
2951
2952 // If the aliasee has internal linkage, give it the name and linkage
2953 // of the alias, and delete the alias. This turns:
2954 // define internal ... @f(...)
2955 // @a = alias ... @f
2956 // into:
2957 // define ... @a(...)
2958 Constant *Aliasee = GA.getAliasee();
2959 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2960 if (!Target->hasLocalLinkage())
2961 return Ret;
2962
2963 // Do not perform the transform if multiple aliases potentially target the
2964 // aliasee. This check also ensures that it is safe to replace the section
2965 // and other attributes of the aliasee with those of the alias.
2966 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2967 return Ret;
2968
2969 RenameTarget = true;
2970 return true;
Rafael Espindola00752162013-05-09 17:22:59 +00002971}
2972
Duncan Sandsed722832009-03-06 10:21:56 +00002973bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002974 bool Changed = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002975 LLVMUsed Used(M);
2976
2977 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.usedBegin(),
2978 E = Used.usedEnd();
2979 I != E; ++I)
2980 Used.compilerUsedErase(*I);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002981
Duncan Sands0bcf0852009-01-07 20:01:06 +00002982 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandsb3f27882009-02-15 09:56:08 +00002983 I != E;) {
2984 Module::alias_iterator J = I++;
Duncan Sandsed722832009-03-06 10:21:56 +00002985 // Aliases without names cannot be referenced outside this module.
2986 if (!J->hasName() && !J->isDeclaration())
2987 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandsb3f27882009-02-15 09:56:08 +00002988 // If the aliasee may change at link time, nothing can be done - bail out.
2989 if (J->mayBeOverridden())
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002990 continue;
2991
Duncan Sandsb3f27882009-02-15 09:56:08 +00002992 Constant *Aliasee = J->getAliasee();
2993 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands7a1db332009-02-18 17:55:38 +00002994 Target->removeDeadConstantUsers();
Duncan Sandsb3f27882009-02-15 09:56:08 +00002995
2996 // Make all users of the alias use the aliasee instead.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002997 bool RenameTarget;
2998 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola00752162013-05-09 17:22:59 +00002999 continue;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003000
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003001 J->replaceAllUsesWith(Aliasee);
3002 ++NumAliasesResolved;
3003 Changed = true;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003004
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003005 if (RenameTarget) {
Duncan Sands6a3df7b2009-12-08 10:10:20 +00003006 // Give the aliasee the name, linkage and other attributes of the alias.
3007 Target->takeName(J);
3008 Target->setLinkage(J->getLinkage());
3009 Target->GlobalValue::copyAttributesFrom(J);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003010
3011 if (Used.usedErase(J))
3012 Used.usedInsert(Target);
3013
3014 if (Used.compilerUsedErase(J))
3015 Used.compilerUsedInsert(Target);
Rafael Espindola8d304802013-06-12 16:45:47 +00003016 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003017 continue;
3018
Duncan Sandsb3f27882009-02-15 09:56:08 +00003019 // Delete the alias.
3020 M.getAliasList().erase(J);
3021 ++NumAliasesRemoved;
3022 Changed = true;
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003023 }
3024
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003025 Used.syncVariablesAndSets();
3026
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003027 return Changed;
3028}
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003029
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003030static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3031 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewyckyf2852562012-02-12 02:17:18 +00003032 return 0;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003033
3034 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak9525a772012-12-06 21:57:16 +00003035
Anders Carlssonee6bc702011-03-20 17:59:11 +00003036 if (!Fn)
3037 return 0;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003038
Chris Lattner229907c2011-07-18 04:54:35 +00003039 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak9525a772012-12-06 21:57:16 +00003040
3041 // Checking that the function has the right return type, the right number of
Anders Carlsson48a44912011-03-20 19:51:13 +00003042 // parameters and that they all have pointer types should be enough.
3043 if (!FTy->getReturnType()->isIntegerTy() ||
3044 FTy->getNumParams() != 3 ||
Anders Carlssonee6bc702011-03-20 17:59:11 +00003045 !FTy->getParamType(0)->isPointerTy() ||
3046 !FTy->getParamType(1)->isPointerTy() ||
3047 !FTy->getParamType(2)->isPointerTy())
3048 return 0;
3049
3050 return Fn;
3051}
3052
3053/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3054/// destructor and can therefore be eliminated.
3055/// Note that we assume that other optimization passes have already simplified
3056/// the code so we only look for a function with a single basic block, where
Benjamin Kramer1a4695a2012-02-09 16:28:15 +00003057/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3058/// other side-effect free instructions.
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003059static bool cxxDtorIsEmpty(const Function &Fn,
3060 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson48a44912011-03-20 19:51:13 +00003061 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewyckyd0781832011-03-21 02:26:01 +00003062 // nounwind, but that doesn't seem worth doing.
Anders Carlsson48a44912011-03-20 19:51:13 +00003063 if (Fn.isDeclaration())
3064 return false;
Anders Carlssonee6bc702011-03-20 17:59:11 +00003065
3066 if (++Fn.begin() != Fn.end())
3067 return false;
3068
3069 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3070 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3071 I != E; ++I) {
3072 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003073 // Ignore debug intrinsics.
3074 if (isa<DbgInfoIntrinsic>(CI))
3075 continue;
3076
Anders Carlssonee6bc702011-03-20 17:59:11 +00003077 const Function *CalledFn = CI->getCalledFunction();
3078
3079 if (!CalledFn)
3080 return false;
3081
Anders Carlsson1cc80732011-03-22 03:21:01 +00003082 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3083
Anders Carlsson48a44912011-03-20 19:51:13 +00003084 // Don't treat recursive functions as empty.
Anders Carlsson1cc80732011-03-22 03:21:01 +00003085 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson48a44912011-03-20 19:51:13 +00003086 return false;
3087
Anders Carlsson1cc80732011-03-22 03:21:01 +00003088 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003089 return false;
3090 } else if (isa<ReturnInst>(*I))
Benjamin Kramer487a3962012-02-09 14:26:06 +00003091 return true; // We're done.
3092 else if (I->mayHaveSideEffects())
3093 return false; // Destructor with side effects, bail.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003094 }
3095
3096 return false;
3097}
3098
3099bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3100 /// Itanium C++ ABI p3.3.5:
3101 ///
3102 /// After constructing a global (or local static) object, that will require
3103 /// destruction on exit, a termination function is registered as follows:
3104 ///
3105 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3106 ///
3107 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3108 /// call f(p) when DSO d is unloaded, before all such termination calls
3109 /// registered before this one. It returns zero if registration is
Nick Lewyckyd0781832011-03-21 02:26:01 +00003110 /// successful, nonzero on failure.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003111
3112 // This pass will look for calls to __cxa_atexit where the function is trivial
3113 // and remove them.
3114 bool Changed = false;
3115
Jakub Staszak9525a772012-12-06 21:57:16 +00003116 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
Anders Carlssonee6bc702011-03-20 17:59:11 +00003117 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson336fd902011-03-20 20:21:33 +00003118 // We're only interested in calls. Theoretically, we could handle invoke
3119 // instructions as well, but neither llvm-gcc nor clang generate invokes
3120 // to __cxa_atexit.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003121 CallInst *CI = dyn_cast<CallInst>(*I++);
3122 if (!CI)
Anders Carlsson336fd902011-03-20 20:21:33 +00003123 continue;
3124
Jakub Staszak9525a772012-12-06 21:57:16 +00003125 Function *DtorFn =
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003126 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssonee6bc702011-03-20 17:59:11 +00003127 if (!DtorFn)
3128 continue;
3129
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003130 SmallPtrSet<const Function *, 8> CalledFunctions;
3131 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003132 continue;
3133
3134 // Just remove the call.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003135 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3136 CI->eraseFromParent();
Anders Carlsson48a44912011-03-20 19:51:13 +00003137
Anders Carlssonee6bc702011-03-20 17:59:11 +00003138 ++NumCXXDtorsRemoved;
3139
3140 Changed |= true;
3141 }
3142
3143 return Changed;
3144}
3145
Chris Lattner25db5802004-10-07 04:16:33 +00003146bool GlobalOpt::runOnModule(Module &M) {
3147 bool Changed = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003148
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003149 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003150 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewyckycf6aae62012-02-12 01:13:18 +00003151
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003152 // Try to find the llvm.globalctors list.
3153 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner25db5802004-10-07 04:16:33 +00003154
Chris Lattner25db5802004-10-07 04:16:33 +00003155 bool LocalChange = true;
3156 while (LocalChange) {
3157 LocalChange = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003158
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003159 // Delete functions that are trivially dead, ccc -> fastcc
3160 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003161
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003162 // Optimize global_ctors list.
3163 if (GlobalCtors)
3164 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003165
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003166 // Optimize non-address-taken globals.
3167 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003168
3169 // Resolve aliases, when possible.
Duncan Sandsed722832009-03-06 10:21:56 +00003170 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003171
Manman Renb3c52fb2013-05-14 21:52:44 +00003172 // Try to remove trivial global destructors if they are not removed
3173 // already.
3174 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003175 if (CXAAtExitFn)
3176 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3177
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003178 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +00003179 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003180
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003181 // TODO: Move all global ctors functions to the end of the module for code
3182 // layout.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003183
Chris Lattner25db5802004-10-07 04:16:33 +00003184 return Changed;
3185}