blob: 82a59ed562de71211237cb33f89a4018e07df96e [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chandler Carruthd04a8d42012-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 Carruth0b8c9a82013-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 Lattner079236d2004-02-25 21:34:36 +000033#include "llvm/Pass.h"
Duncan Sands548448a2008-02-18 17:32:13 +000034#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000035#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000036#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000038#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000039#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000040#include "llvm/Target/TargetLibraryInfo.h"
Rafael Espindola713cab02013-10-21 17:14:55 +000041#include "llvm/Transforms/Utils/GlobalStatus.h"
Rafael Espindola4ef7eaf2013-07-25 03:23:25 +000042#include "llvm/Transforms/Utils/ModuleUtils.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000043#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000044using namespace llvm;
45
Chris Lattner86453c52006-12-19 22:09:18 +000046STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000047STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-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 Samsonov23eb9072013-10-07 19:03:24 +000054STATISTIC(NumLocalized , "Number of globals localized");
Chris Lattner86453c52006-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 Sands3d5378f2008-02-16 20:56:04 +000058STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000059STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
60STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000061STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000062
Chris Lattner86453c52006-12-19 22:09:18 +000063namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000064 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000065 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000066 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000067 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000068 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000069 GlobalOpt() : ModulePass(ID) {
70 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
71 }
Misha Brukmanfd939082005-04-21 23:48:37 +000072
Chris Lattnerb12914b2004-09-20 04:48:05 +000073 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000074
75 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000076 GlobalVariable *FindGlobalCtors(Module &M);
77 bool OptimizeFunctions(Module &M);
78 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000079 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000080 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000081 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
82 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
Rafael Espindolac4440e32011-01-19 16:32:21 +000083 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewycky6a577f82012-02-12 01:13:18 +000085
Micah Villmow3574eca2012-10-08 16:38:25 +000086 DataLayout *TD;
Nick Lewycky6a577f82012-02-12 01:13:18 +000087 TargetLibraryInfo *TLI;
Chris Lattner079236d2004-02-25 21:34:36 +000088 };
Chris Lattner079236d2004-02-25 21:34:36 +000089}
90
Dan Gohman844731a2008-05-13 00:00:25 +000091char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000092INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
93 "Global Variable Optimizer", false, false)
94INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
95INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000096 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000097
Chris Lattner7a90b682004-10-07 04:16:33 +000098ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000099
Dan Gohman844731a2008-05-13 00:00:25 +0000100namespace {
101
Rafael Espindolac4440e32011-01-19 16:32:21 +0000102
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000103
Rafael Espindola4a7cef22013-10-17 18:00:25 +0000104}
105
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000106/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
107/// as a root? If so, we might not really want to eliminate the stores to it.
108static bool isLeakCheckerRoot(GlobalVariable *GV) {
109 // A global variable is a root if it is a pointer, or could plausibly contain
110 // a pointer. There are two challenges; one is that we could have a struct
111 // the has an inner member which is a pointer. We recurse through the type to
112 // detect these (up to a point). The other is that we may actually be a union
113 // of a pointer and another type, and so our LLVM type is an integer which
114 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
115 // potentially contained here.
116
117 if (GV->hasPrivateLinkage())
118 return false;
119
120 SmallVector<Type *, 4> Types;
121 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
122
123 unsigned Limit = 20;
124 do {
125 Type *Ty = Types.pop_back_val();
126 switch (Ty->getTypeID()) {
127 default: break;
128 case Type::PointerTyID: return true;
129 case Type::ArrayTyID:
130 case Type::VectorTyID: {
131 SequentialType *STy = cast<SequentialType>(Ty);
132 Types.push_back(STy->getElementType());
133 break;
134 }
135 case Type::StructTyID: {
136 StructType *STy = cast<StructType>(Ty);
137 if (STy->isOpaque()) return true;
138 for (StructType::element_iterator I = STy->element_begin(),
139 E = STy->element_end(); I != E; ++I) {
140 Type *InnerTy = *I;
141 if (isa<PointerType>(InnerTy)) return true;
142 if (isa<CompositeType>(InnerTy))
143 Types.push_back(InnerTy);
144 }
145 break;
146 }
147 }
148 if (--Limit == 0) return true;
149 } while (!Types.empty());
150 return false;
151}
152
153/// Given a value that is stored to a global but never read, determine whether
154/// it's safe to remove the store and the chain of computation that feeds the
155/// store.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000156static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000157 do {
158 if (isa<Constant>(V))
159 return true;
160 if (!V->hasOneUse())
161 return false;
Nick Lewyckyb8cd66b2012-07-25 21:19:40 +0000162 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
163 isa<GlobalValue>(V))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000164 return false;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000165 if (isAllocationFn(V, TLI))
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000166 return true;
167
168 Instruction *I = cast<Instruction>(V);
169 if (I->mayHaveSideEffects())
170 return false;
171 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
172 if (!GEP->hasAllConstantIndices())
173 return false;
174 } else if (I->getNumOperands() != 1) {
175 return false;
176 }
177
178 V = I->getOperand(0);
179 } while (1);
180}
181
182/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
183/// of the global and clean up any that obviously don't assign the global a
184/// value that isn't dynamically allocated.
185///
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000186static bool CleanupPointerRootUsers(GlobalVariable *GV,
187 const TargetLibraryInfo *TLI) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000188 // A brief explanation of leak checkers. The goal is to find bugs where
189 // pointers are forgotten, causing an accumulating growth in memory
190 // usage over time. The common strategy for leak checkers is to whitelist the
191 // memory pointed to by globals at exit. This is popular because it also
192 // solves another problem where the main thread of a C++ program may shut down
193 // before other threads that are still expecting to use those globals. To
194 // handle that case, we expect the program may create a singleton and never
195 // destroy it.
196
197 bool Changed = false;
198
199 // If Dead[n].first is the only use of a malloc result, we can delete its
200 // chain of computation and the store to the global in Dead[n].second.
201 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
202
203 // Constants can't be pointers to dynamically allocated memory.
204 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
205 UI != E;) {
206 User *U = *UI++;
207 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
208 Value *V = SI->getValueOperand();
209 if (isa<Constant>(V)) {
210 Changed = true;
211 SI->eraseFromParent();
212 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
213 if (I->hasOneUse())
214 Dead.push_back(std::make_pair(I, SI));
215 }
216 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
217 if (isa<Constant>(MSI->getValue())) {
218 Changed = true;
219 MSI->eraseFromParent();
220 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
221 if (I->hasOneUse())
222 Dead.push_back(std::make_pair(I, MSI));
223 }
224 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
225 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
226 if (MemSrc && MemSrc->isConstant()) {
227 Changed = true;
228 MTI->eraseFromParent();
229 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
230 if (I->hasOneUse())
231 Dead.push_back(std::make_pair(I, MTI));
232 }
233 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
234 if (CE->use_empty()) {
235 CE->destroyConstant();
236 Changed = true;
237 }
238 } else if (Constant *C = dyn_cast<Constant>(U)) {
Rafael Espindola9bb874c2013-10-17 18:06:32 +0000239 if (isSafeToDestroyConstant(C)) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000240 C->destroyConstant();
241 // This could have invalidated UI, start over from scratch.
242 Dead.clear();
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000243 CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000244 return true;
245 }
246 }
247 }
248
249 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000250 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000251 Dead[i].second->eraseFromParent();
252 Instruction *I = Dead[i].first;
253 do {
Michael Gottesmandcf66952013-01-11 23:08:52 +0000254 if (isAllocationFn(I, TLI))
255 break;
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000256 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
257 if (!J)
258 break;
259 I->eraseFromParent();
260 I = J;
Nick Lewycky952f5d52012-07-24 21:33:00 +0000261 } while (1);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000262 I->eraseFromParent();
263 }
264 }
265
266 return Changed;
267}
268
Chris Lattnere47ba742004-10-06 20:57:02 +0000269/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
270/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000271/// quick scan over the use list to clean up the easy and obvious cruft. This
272/// returns true if it made a change.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000273static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Micah Villmow3574eca2012-10-08 16:38:25 +0000274 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner031955d2004-10-10 16:43:46 +0000275 bool Changed = false;
Bill Wendling2b792362013-04-02 08:16:45 +0000276 SmallVector<User*, 8> WorkList(V->use_begin(), V->use_end());
277 while (!WorkList.empty()) {
278 User *U = WorkList.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000279
Chris Lattner7a90b682004-10-07 04:16:33 +0000280 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000281 if (Init) {
282 // Replace the load with the initializer.
283 LI->replaceAllUsesWith(Init);
284 LI->eraseFromParent();
285 Changed = true;
286 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000287 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000288 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000289 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000290 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000291 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
292 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000293 Constant *SubInit = 0;
294 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000295 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Nick Lewycky6a577f82012-02-12 01:13:18 +0000296 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000297 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000298 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000299 // Pointer cast, delete any stores and memsets to the global.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000300 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
Chris Lattner35c81b02005-02-27 18:58:52 +0000301 }
302
303 if (CE->use_empty()) {
304 CE->destroyConstant();
305 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000306 }
307 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000308 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
309 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
310 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000311 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000312 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000313 ConstantExpr *CE =
Nick Lewycky6a577f82012-02-12 01:13:18 +0000314 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000315 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000316 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Kramerc1ea16e2012-03-28 14:50:09 +0000317
318 // If the initializer is an all-null value and we have an inbounds GEP,
319 // we already know what the result of any load from that GEP is.
320 // TODO: Handle splats.
321 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
322 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattner7b52fe72007-11-09 17:33:02 +0000323 }
Nick Lewycky6a577f82012-02-12 01:13:18 +0000324 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000325
Chris Lattner031955d2004-10-10 16:43:46 +0000326 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000327 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000328 Changed = true;
329 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000330 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
331 if (MI->getRawDest() == V) {
332 MI->eraseFromParent();
333 Changed = true;
334 }
335
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000336 } else if (Constant *C = dyn_cast<Constant>(U)) {
337 // If we have a chain of dead constantexprs or other things dangling from
338 // us, and if they are all dead, nuke them without remorse.
Rafael Espindola9bb874c2013-10-17 18:06:32 +0000339 if (isSafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000340 C->destroyConstant();
Nick Lewycky6a577f82012-02-12 01:13:18 +0000341 CleanupConstantGlobalUsers(V, Init, TD, TLI);
Chris Lattner031955d2004-10-10 16:43:46 +0000342 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000343 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000344 }
345 }
Chris Lattner031955d2004-10-10 16:43:46 +0000346 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000347}
348
Chris Lattner941db492008-01-14 02:09:12 +0000349/// isSafeSROAElementUse - Return true if the specified instruction is a safe
350/// user of a derived expression from a global that we want to SROA.
351static bool isSafeSROAElementUse(Value *V) {
352 // We might have a dead and dangling constant hanging off of here.
353 if (Constant *C = dyn_cast<Constant>(V))
Rafael Espindola9bb874c2013-10-17 18:06:32 +0000354 return isSafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000355
Chris Lattner941db492008-01-14 02:09:12 +0000356 Instruction *I = dyn_cast<Instruction>(V);
357 if (!I) return false;
358
359 // Loads are ok.
360 if (isa<LoadInst>(I)) return true;
361
362 // Stores *to* the pointer are ok.
363 if (StoreInst *SI = dyn_cast<StoreInst>(I))
364 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000365
Chris Lattner941db492008-01-14 02:09:12 +0000366 // Otherwise, it must be a GEP.
367 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
368 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000369
Chris Lattner941db492008-01-14 02:09:12 +0000370 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
371 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
372 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000373
Chris Lattner941db492008-01-14 02:09:12 +0000374 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
375 I != E; ++I)
376 if (!isSafeSROAElementUse(*I))
377 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000378 return true;
379}
380
Chris Lattner941db492008-01-14 02:09:12 +0000381
382/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
383/// Look at it and its uses and decide whether it is safe to SROA this global.
384///
385static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
386 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000387 if (!isa<GetElementPtrInst>(U) &&
388 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000389 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
390 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000391
Chris Lattner941db492008-01-14 02:09:12 +0000392 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
393 // don't like < 3 operand CE's, and we don't like non-constant integer
394 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
395 // value of C.
396 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
397 !cast<Constant>(U->getOperand(1))->isNullValue() ||
398 !isa<ConstantInt>(U->getOperand(2)))
399 return false;
400
401 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
402 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000403
Chris Lattner941db492008-01-14 02:09:12 +0000404 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000405 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000406 uint64_t NumElements = AT->getNumElements();
407 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000408
Chris Lattner941db492008-01-14 02:09:12 +0000409 // Check to make sure that index falls within the array. If not,
410 // something funny is going on, so we won't do the optimization.
411 //
412 if (Idx->getZExtValue() >= NumElements)
413 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000414
Chris Lattner941db492008-01-14 02:09:12 +0000415 // We cannot scalar repl this level of the array unless any array
416 // sub-indices are in-range constants. In particular, consider:
417 // A[0][i]. We cannot know that the user isn't doing invalid things like
418 // allowing i to index an out-of-range subscript that accesses A[1].
419 //
420 // Scalar replacing *just* the outer index of the array is probably not
421 // going to be a win anyway, so just give up.
422 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000423 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000424 ++GEPI) {
425 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000426 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000427 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000428 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000429 NumElements = SubVectorTy->getNumElements();
430 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000431 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000432 "Indexed GEP type is not array, vector, or struct!");
433 continue;
434 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000435
Chris Lattner941db492008-01-14 02:09:12 +0000436 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
437 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
438 return false;
439 }
440 }
441
442 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
443 if (!isSafeSROAElementUse(*I))
444 return false;
445 return true;
446}
447
448/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
449/// is safe for us to perform this transformation.
450///
451static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
452 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
453 UI != E; ++UI) {
454 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
455 return false;
456 }
457 return true;
458}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000459
Chris Lattner941db492008-01-14 02:09:12 +0000460
Chris Lattner670c8892004-10-08 17:32:09 +0000461/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
462/// variable. This opens the door for other optimizations by exposing the
463/// behavior of the program in a more fine-grained way. We have determined that
464/// this transformation is safe already. We return the first global variable we
465/// insert so that the caller can reprocess it.
Micah Villmow3574eca2012-10-08 16:38:25 +0000466static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000467 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000468 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000469 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000470
Rafael Espindolabb46f522009-01-15 20:18:42 +0000471 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000472 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000473 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000474
Chris Lattner670c8892004-10-08 17:32:09 +0000475 std::vector<GlobalVariable*> NewGlobals;
476 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
477
Chris Lattner998182b2008-04-26 07:40:11 +0000478 // Get the alignment of the global, either explicit or target-specific.
479 unsigned StartAlignment = GV->getAlignment();
480 if (StartAlignment == 0)
481 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000482
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000483 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000484 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000485 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000486 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000487 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000488 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000489 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000490 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000491 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000492 GV->getThreadLocalMode(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000493 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000494 Globals.insert(GV, NGV);
495 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000496
Chris Lattner998182b2008-04-26 07:40:11 +0000497 // Calculate the known alignment of the field. If the original aggregate
498 // had 256 byte alignment for example, something might depend on that:
499 // propagate info to each field.
500 uint64_t FieldOffset = Layout.getElementOffset(i);
501 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
502 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
503 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000504 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000505 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000506 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000507 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000508 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000509 else
Chris Lattner998182b2008-04-26 07:40:11 +0000510 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000511
Chris Lattner1f21ef12005-02-23 16:53:04 +0000512 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000513 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000514 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000515
Duncan Sands777d2302009-05-09 07:06:46 +0000516 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000517 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000518 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000519 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000520 assert(In && "Couldn't get element of initializer?");
521
Chris Lattner7b550cc2009-11-06 04:27:31 +0000522 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000523 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000524 In, GV->getName()+"."+Twine(i),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000525 GV->getThreadLocalMode(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000526 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000527 Globals.insert(GV, NGV);
528 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000529
Chris Lattner998182b2008-04-26 07:40:11 +0000530 // Calculate the known alignment of the field. If the original aggregate
531 // had 256 byte alignment for example, something might depend on that:
532 // propagate info to each field.
533 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
534 if (NewAlign > EltAlign)
535 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000536 }
537 }
538
539 if (NewGlobals.empty())
540 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000541
David Greene3215b0e2010-01-05 01:28:05 +0000542 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000543
Chris Lattner7b550cc2009-11-06 04:27:31 +0000544 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000545
546 // Loop over all of the uses of the global, replacing the constantexpr geps,
547 // with smaller constantexpr geps or direct references.
548 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000549 User *GEP = GV->use_back();
550 assert(((isa<ConstantExpr>(GEP) &&
551 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
552 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000553
Chris Lattner670c8892004-10-08 17:32:09 +0000554 // Ignore the 1th operand, which has to be zero or else the program is quite
555 // broken (undefined). Get the 2nd operand, which is the structure or array
556 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000557 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000558 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
559
Chris Lattner30ba5692004-10-11 05:54:41 +0000560 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000561
562 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000563 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000564 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000565 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000566 Idxs.push_back(NullInt);
567 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
568 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000569 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000570 } else {
571 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000572 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000573 Idxs.push_back(NullInt);
574 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
575 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000576 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000577 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000578 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000579 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000580 GEP->replaceAllUsesWith(NewPtr);
581
582 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000583 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000584 else
585 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000586 }
587
Chris Lattnere40e2d12004-10-08 20:25:55 +0000588 // Delete the old global, now that it is dead.
589 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000590 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000591
592 // Loop over the new globals array deleting any globals that are obviously
593 // dead. This can arise due to scalarization of a structure or an array that
594 // has elements that are dead.
595 unsigned FirstGlobal = 0;
596 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
597 if (NewGlobals[i]->use_empty()) {
598 Globals.erase(NewGlobals[i]);
599 if (FirstGlobal == i) ++FirstGlobal;
600 }
601
602 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000603}
604
Chris Lattner9b34a612004-10-09 21:48:45 +0000605/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000606/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000607/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000608static bool AllUsesOfValueWillTrapIfNull(const Value *V,
609 SmallPtrSet<const PHINode*, 8> &PHIs) {
610 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000611 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000612 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000613
614 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000615 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000616 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000617 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000618 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000619 return false; // Storing the value.
620 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000621 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000622 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000623 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000624 return false; // Not calling the ptr
625 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000626 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000627 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000628 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000629 return false; // Not calling the ptr
630 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000631 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000632 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000633 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000634 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000635 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000636 // If we've already seen this phi node, ignore it, it has already been
637 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000638 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
639 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000640 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000641 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000642 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000643 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000644 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000645 return false;
646 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000647 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000648 return true;
649}
650
651/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000652/// from GV will trap if the loaded value is null. Note that this also permits
653/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000654static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
655 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000656 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000657 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000658
Gabor Greif6ce02b52010-04-06 19:24:18 +0000659 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
660 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000661 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000662 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000663 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000664 // Ignore stores to the global.
665 } else {
666 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000667 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000668 return false;
669 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000670 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000671 return true;
672}
673
Chris Lattner7b550cc2009-11-06 04:27:31 +0000674static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000675 bool Changed = false;
676 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
677 Instruction *I = cast<Instruction>(*UI++);
678 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
679 LI->setOperand(0, NewV);
680 Changed = true;
681 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
682 if (SI->getOperand(1) == V) {
683 SI->setOperand(1, NewV);
684 Changed = true;
685 }
686 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000687 CallSite CS(I);
688 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000689 // Calling through the pointer! Turn into a direct call, but be careful
690 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000691 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000692 Changed = true;
693 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000694 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
695 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000696 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000697 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000698 }
699
700 if (PassedAsArg) {
701 // Being passed as an argument also. Be careful to not invalidate UI!
702 UI = V->use_begin();
703 }
704 }
705 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
706 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000707 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000708 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000709 if (CI->use_empty()) {
710 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000711 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000712 }
713 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
714 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000715 SmallVector<Constant*, 8> Idxs;
716 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000717 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
718 i != e; ++i)
719 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000720 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000721 else
722 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000723 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000724 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000725 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000726 if (GEPI->use_empty()) {
727 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000728 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000729 }
730 }
731 }
732
733 return Changed;
734}
735
736
737/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
738/// value stored into it. If there are uses of the loaded value that would trap
739/// if the loaded value is dynamically null, then we know that they cannot be
740/// reachable with a null optimize away the load.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000741static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Micah Villmow3574eca2012-10-08 16:38:25 +0000742 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000743 TargetLibraryInfo *TLI) {
Chris Lattner708148e2004-10-10 23:14:11 +0000744 bool Changed = false;
745
Chris Lattner92c6bd22009-01-14 00:12:58 +0000746 // Keep track of whether we are able to remove all the uses of the global
747 // other than the store that defines it.
748 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000749
Chris Lattner708148e2004-10-10 23:14:11 +0000750 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000751 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
752 User *GlobalUser = *GUI++;
753 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000754 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000755 // If we were able to delete all uses of the loads
756 if (LI->use_empty()) {
757 LI->eraseFromParent();
758 Changed = true;
759 } else {
760 AllNonStoreUsesGone = false;
761 }
762 } else if (isa<StoreInst>(GlobalUser)) {
763 // Ignore the store that stores "LV" to the global.
764 assert(GlobalUser->getOperand(1) == GV &&
765 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000766 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000767 AllNonStoreUsesGone = false;
768
769 // If we get here we could have other crazy uses that are transitively
770 // loaded.
771 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramerab164232012-09-28 10:01:27 +0000772 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
773 isa<BitCastInst>(GlobalUser) ||
774 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner98a42b22011-05-22 07:15:13 +0000775 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000776 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000777 }
Chris Lattner708148e2004-10-10 23:14:11 +0000778
779 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000780 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000781 ++NumGlobUses;
782 }
783
Chris Lattner708148e2004-10-10 23:14:11 +0000784 // If we nuked all of the loads, then none of the stores are needed either,
785 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000786 if (AllNonStoreUsesGone) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000787 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000788 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000789 } else {
790 Changed = true;
791 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
792 }
Chris Lattner708148e2004-10-10 23:14:11 +0000793 if (GV->use_empty()) {
Nick Lewycky8899d5c2012-07-24 07:21:08 +0000794 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
795 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000796 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000797 ++NumDeleted;
798 }
Chris Lattner708148e2004-10-10 23:14:11 +0000799 }
800 return Changed;
801}
802
Chris Lattner30ba5692004-10-11 05:54:41 +0000803/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
804/// instructions that are foldable.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000805static void ConstantPropUsersOf(Value *V,
Micah Villmow3574eca2012-10-08 16:38:25 +0000806 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000807 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
808 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Nick Lewycky6a577f82012-02-12 01:13:18 +0000809 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000810 I->replaceAllUsesWith(NewC);
811
Chris Lattnerd514d822005-02-01 01:23:31 +0000812 // Advance UI to the next non-I use to avoid invalidating it!
813 // Instructions could multiply use V.
814 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000815 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000816 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000817 }
818}
819
820/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
821/// variable, and transforms the program as if it always contained the result of
822/// the specified malloc. Because it is always the result of the specified
823/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000824/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000825static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000826 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000827 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000828 ConstantInt *NElements,
Micah Villmow3574eca2012-10-08 16:38:25 +0000829 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +0000830 TargetLibraryInfo *TLI) {
Chris Lattnera6874652010-02-25 22:33:52 +0000831 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000832
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000833 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +0000834 if (NElements->getZExtValue() == 1)
835 GlobalType = AllocTy;
836 else
837 // If we have an array allocation, the global variable is of an array.
838 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000839
840 // Create the new global variable. The contents of the malloc'd memory is
841 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000842 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000843 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000844 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000845 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000846 GV->getName()+".body",
847 GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +0000848 GV->getThreadLocalMode());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000849
Chris Lattnera6874652010-02-25 22:33:52 +0000850 // If there are bitcast users of the malloc (which is typical, usually we have
851 // a malloc + bitcast) then replace them with uses of the new global. Update
852 // other users to use the global as well.
853 BitCastInst *TheBC = 0;
854 while (!CI->use_empty()) {
855 Instruction *User = cast<Instruction>(CI->use_back());
856 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
857 if (BCI->getType() == NewGV->getType()) {
858 BCI->replaceAllUsesWith(NewGV);
859 BCI->eraseFromParent();
860 } else {
861 BCI->setOperand(0, NewGV);
862 }
863 } else {
864 if (TheBC == 0)
865 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
866 User->replaceUsesOfWith(CI, TheBC);
867 }
868 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000869
Victor Hernandez83d63912009-09-18 22:35:49 +0000870 Constant *RepValue = NewGV;
871 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000872 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000873 GV->getType()->getElementType());
874
875 // If there is a comparison against null, we will insert a global bool to
876 // keep track of whether the global was initialized yet or not.
877 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000878 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000879 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000880 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000881 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +0000882 bool InitBoolUsed = false;
883
884 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000885 while (!GV->use_empty()) {
886 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000887 // The global is initialized when the store to it occurs.
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000888 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
889 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000890 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000891 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000892 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000893
Chris Lattnera6874652010-02-25 22:33:52 +0000894 LoadInst *LI = cast<LoadInst>(GV->use_back());
895 while (!LI->use_empty()) {
896 Use &LoadUse = LI->use_begin().getUse();
897 if (!isa<ICmpInst>(LoadUse.getUser())) {
898 LoadUse = RepValue;
899 continue;
900 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000901
Chris Lattnera6874652010-02-25 22:33:52 +0000902 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
903 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +0000904 // Sink the load to where the compare was, if atomic rules allow us to.
905 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
906 LI->getOrdering(), LI->getSynchScope(),
907 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattnera6874652010-02-25 22:33:52 +0000908 InitBoolUsed = true;
909 switch (ICI->getPredicate()) {
910 default: llvm_unreachable("Unknown ICmp Predicate!");
911 case ICmpInst::ICMP_ULT:
912 case ICmpInst::ICMP_SLT: // X < null -> always false
913 LV = ConstantInt::getFalse(GV->getContext());
914 break;
915 case ICmpInst::ICMP_ULE:
916 case ICmpInst::ICMP_SLE:
917 case ICmpInst::ICMP_EQ:
918 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
919 break;
920 case ICmpInst::ICMP_NE:
921 case ICmpInst::ICMP_UGE:
922 case ICmpInst::ICMP_SGE:
923 case ICmpInst::ICMP_UGT:
924 case ICmpInst::ICMP_SGT:
925 break; // no change.
926 }
927 ICI->replaceAllUsesWith(LV);
928 ICI->eraseFromParent();
929 }
930 LI->eraseFromParent();
931 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000932
933 // If the initialization boolean was used, insert it, otherwise delete it.
934 if (!InitBoolUsed) {
935 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000936 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000937 delete InitBool;
938 } else
939 GV->getParent()->getGlobalList().insert(GV, InitBool);
940
Chris Lattnera6874652010-02-25 22:33:52 +0000941 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000942 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000943 CI->eraseFromParent();
944
945 // To further other optimizations, loop over all users of NewGV and try to
946 // constant prop them. This will promote GEP instructions with constant
947 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Nick Lewycky6a577f82012-02-12 01:13:18 +0000948 ConstantPropUsersOf(NewGV, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000949 if (RepValue != NewGV)
Nick Lewycky6a577f82012-02-12 01:13:18 +0000950 ConstantPropUsersOf(RepValue, TD, TLI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000951
952 return NewGV;
953}
954
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000955/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
956/// to make sure that there are no complex uses of V. We permit simple things
957/// like dereferencing the pointer, but not storing through the address, unless
958/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000959static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
960 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000961 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000962 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000963 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000964 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000965
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000966 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
967 continue; // Fine, ignore.
968 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000969
Gabor Greif0b520db2010-04-06 18:58:22 +0000970 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000971 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
972 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000973 continue; // Otherwise, storing through it, or storing into GV... fine.
974 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000975
Chris Lattnera2fb2342010-04-10 18:19:22 +0000976 // Must index into the array and into the struct.
977 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000978 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000979 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000980 continue;
981 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000982
Gabor Greif0b520db2010-04-06 18:58:22 +0000983 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000984 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
985 // cycles.
986 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000987 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
988 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000989 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000990 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000991
Gabor Greif0b520db2010-04-06 18:58:22 +0000992 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000993 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
994 return false;
995 continue;
996 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000997
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000998 return false;
999 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001000 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +00001001}
1002
Chris Lattner86395032006-09-30 23:32:09 +00001003/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1004/// somewhere. Transform all uses of the allocation into loads from the
1005/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001006/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +00001007/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001008static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +00001009 GlobalVariable *GV) {
1010 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001011 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1012 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001013 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1014 // If this is the store of the allocation into the global, remove it.
1015 if (SI->getOperand(1) == GV) {
1016 SI->eraseFromParent();
1017 continue;
1018 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001019 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1020 // Insert the load in the corresponding predecessor, not right before the
1021 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001022 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001023 } else if (isa<BitCastInst>(U)) {
1024 // Must be bitcast between the malloc and store to initialize the global.
1025 ReplaceUsesOfMallocWithGlobal(U, GV);
1026 U->eraseFromParent();
1027 continue;
1028 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1029 // If this is a "GEP bitcast" and the user is a store to the global, then
1030 // just process it as a bitcast.
1031 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1032 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1033 if (SI->getOperand(1) == GV) {
1034 // Must be bitcast GEP between the malloc and store to initialize
1035 // the global.
1036 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1037 GEPI->eraseFromParent();
1038 continue;
1039 }
Chris Lattner86395032006-09-30 23:32:09 +00001040 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001041
Chris Lattner86395032006-09-30 23:32:09 +00001042 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001043 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001044 U->replaceUsesOfWith(Alloc, NL);
1045 }
1046}
1047
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001048/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1049/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1050/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001051static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001052 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1053 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001054 // We permit two users of the load: setcc comparing against the null
1055 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001056 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1057 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001058 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001059
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001060 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001061 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001062 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1063 return false;
1064 continue;
1065 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001066
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001067 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001068 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001069 // Must index into the array and into the struct.
1070 if (GEPI->getNumOperands() < 3)
1071 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001072
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001073 // Otherwise the GEP is ok.
1074 continue;
1075 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001076
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001077 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001078 if (!LoadUsingPHIsPerLoad.insert(PN))
1079 // This means some phi nodes are dependent on each other.
1080 // Avoid infinite looping!
1081 return false;
1082 if (!LoadUsingPHIs.insert(PN))
1083 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001084 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001085
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001086 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001087 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1088 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001089 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001090
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001091 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001092 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001093
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001094 // Otherwise we don't know what this is, not ok.
1095 return false;
1096 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001097
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001098 return true;
1099}
1100
1101
1102/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1103/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001104static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001105 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001106 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1107 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001108 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1109 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001110 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001111 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1112 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001113 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001114 LoadUsingPHIsPerLoad.clear();
1115 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001116
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001117 // If we reach here, we know that all uses of the loads and transitive uses
1118 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001119 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001120 // Check to verify that all operands of the PHIs are either PHIS that can be
1121 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001122 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1123 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001124 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001125 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1126 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001127
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001128 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001129 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001130
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001131 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001132 // One of the PHIs in our set is (optimistically) ok.
1133 if (LoadUsingPHIs.count(InPN))
1134 continue;
1135 return false;
1136 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001137
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001138 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001139 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001140 if (LI->getOperand(0) == GV)
1141 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001142
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001143 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001144
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001145 // Anything else is rejected.
1146 return false;
1147 }
1148 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001149
Chris Lattner86395032006-09-30 23:32:09 +00001150 return true;
1151}
1152
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001153static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1154 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001155 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001156 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001157
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001158 if (FieldNo >= FieldVals.size())
1159 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001160
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001161 // If we already have this value, just reuse the previously scalarized
1162 // version.
1163 if (Value *FieldVal = FieldVals[FieldNo])
1164 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001165
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001166 // Depending on what instruction this is, we have several cases.
1167 Value *Result;
1168 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1169 // This is a scalarized version of the load from the global. Just create
1170 // a new Load of the scalarized global.
1171 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1172 InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001173 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001174 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001175 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1176 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1177 // field.
Matt Arsenault244d2452013-10-21 19:43:56 +00001178 StructType *ST = cast<StructType>(PN->getType()->getPointerElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001179
Jay Foadd8b4fb42011-03-30 11:19:20 +00001180 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001181 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001182 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001183 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001184 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001185 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1186 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001187 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001188 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001189
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001190 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001191}
1192
Chris Lattner330245e2007-09-13 17:29:05 +00001193/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1194/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001195static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001196 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001197 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001198 // If this is a comparison against null, handle it.
1199 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1200 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1201 // If we have a setcc of the loaded pointer, we can use a setcc of any
1202 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001203 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001204 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001205
Owen Anderson333c4002009-07-09 23:48:35 +00001206 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001207 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001208 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001209 SCI->replaceAllUsesWith(New);
1210 SCI->eraseFromParent();
1211 return;
1212 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001213
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001214 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001215 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1216 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1217 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001218
Chris Lattnera637a8b2007-09-13 18:00:31 +00001219 // Load the pointer for this field.
1220 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001221 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001222 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001223
Chris Lattnera637a8b2007-09-13 18:00:31 +00001224 // Create the new GEP idx vector.
1225 SmallVector<Value*, 8> GEPIdx;
1226 GEPIdx.push_back(GEPI->getOperand(1));
1227 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001228
Jay Foada9203102011-07-25 09:48:08 +00001229 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001230 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001231 GEPI->replaceAllUsesWith(NGEPI);
1232 GEPI->eraseFromParent();
1233 return;
1234 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001235
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001236 // Recursively transform the users of PHI nodes. This will lazily create the
1237 // PHIs that are needed for individual elements. Keep track of what PHIs we
1238 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1239 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1240 // already been seen first by another load, so its uses have already been
1241 // processed.
1242 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001243 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1244 std::vector<Value*>())).second)
1245 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001246
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001247 // If this is the first time we've seen this PHI, recursively process all
1248 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001249 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1250 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001251 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001252 }
Chris Lattner330245e2007-09-13 17:29:05 +00001253}
1254
Chris Lattner86395032006-09-30 23:32:09 +00001255/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1256/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1257/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001258/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001259static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001260 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001261 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001262 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001263 UI != E; ) {
1264 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001265 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001266 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001267
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001268 if (Load->use_empty()) {
1269 Load->eraseFromParent();
1270 InsertedScalarizedValues.erase(Load);
1271 }
Chris Lattner86395032006-09-30 23:32:09 +00001272}
1273
Victor Hernandez83d63912009-09-18 22:35:49 +00001274/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1275/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001276static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001277 Value *NElems, DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001278 const TargetLibraryInfo *TLI) {
David Greene3215b0e2010-01-05 01:28:05 +00001279 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001280 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001281 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001282
1283 // There is guaranteed to be at least one use of the malloc (storing
1284 // it into GV). If there are other uses, change them to be uses of
1285 // the global to simplify later code. This also deletes the store
1286 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001287 ReplaceUsesOfMallocWithGlobal(CI, GV);
1288
Victor Hernandez83d63912009-09-18 22:35:49 +00001289 // Okay, at this point, there are no users of the malloc. Insert N
1290 // new mallocs at the same place as CI, and N globals.
1291 std::vector<Value*> FieldGlobals;
1292 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001293
Victor Hernandez83d63912009-09-18 22:35:49 +00001294 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001295 Type *FieldTy = STy->getElementType(FieldNo);
1296 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001297
Victor Hernandez83d63912009-09-18 22:35:49 +00001298 GlobalVariable *NGV =
1299 new GlobalVariable(*GV->getParent(),
1300 PFieldTy, false, GlobalValue::InternalLinkage,
1301 Constant::getNullValue(PFieldTy),
1302 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001303 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001304 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001305
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001306 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001307 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001308 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Matt Arsenaultcf16bae2013-09-11 07:29:40 +00001309 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001310 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1311 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001312 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001313 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001314 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001315 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001316 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001317
Victor Hernandez83d63912009-09-18 22:35:49 +00001318 // The tricky aspect of this transformation is handling the case when malloc
1319 // fails. In the original code, malloc failing would set the result pointer
1320 // of malloc to null. In this case, some mallocs could succeed and others
1321 // could fail. As such, we emit code that looks like this:
1322 // F0 = malloc(field0)
1323 // F1 = malloc(field1)
1324 // F2 = malloc(field2)
1325 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1326 // if (F0) { free(F0); F0 = 0; }
1327 // if (F1) { free(F1); F1 = 0; }
1328 // if (F2) { free(F2); F2 = 0; }
1329 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001330 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001331 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1332 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001333 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001334 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001335 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1336 Constant::getNullValue(FieldMallocs[i]->getType()),
1337 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001338 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001339 }
1340
1341 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001342 BasicBlock *OrigBB = CI->getParent();
1343 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001344
Victor Hernandez83d63912009-09-18 22:35:49 +00001345 // Create the block to check the first condition. Put all these blocks at the
1346 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001347 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1348 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001349 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001350
Victor Hernandez83d63912009-09-18 22:35:49 +00001351 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1352 // branch on RunningOr.
1353 OrigBB->getTerminator()->eraseFromParent();
1354 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001355
Victor Hernandez83d63912009-09-18 22:35:49 +00001356 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1357 // pointer, because some may be null while others are not.
1358 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1359 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001360 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001361 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001362 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001363 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001364 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001365 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001366 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1367 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001368
1369 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001370 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001371 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1372 FreeBlock);
1373 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001374
Victor Hernandez83d63912009-09-18 22:35:49 +00001375 NullPtrBlock = NextBlock;
1376 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001377
Victor Hernandez83d63912009-09-18 22:35:49 +00001378 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001379
1380 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001381 CI->eraseFromParent();
1382
1383 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1384 /// update all uses of the load, keep track of what scalarized loads are
1385 /// inserted for a given load.
1386 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1387 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001388
Victor Hernandez83d63912009-09-18 22:35:49 +00001389 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001390
Victor Hernandez83d63912009-09-18 22:35:49 +00001391 // Okay, the malloc site is completely handled. All of the uses of GV are now
1392 // loads, and all uses of those loads are simple. Rewrite them to use loads
1393 // of the per-field globals instead.
1394 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1395 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001396
Victor Hernandez83d63912009-09-18 22:35:49 +00001397 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001398 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001399 continue;
1400 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001401
Victor Hernandez83d63912009-09-18 22:35:49 +00001402 // Must be a store of null.
1403 StoreInst *SI = cast<StoreInst>(User);
1404 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1405 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001406
Victor Hernandez83d63912009-09-18 22:35:49 +00001407 // Insert a store of null into each global.
1408 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001409 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001410 Constant *Null = Constant::getNullValue(PT->getElementType());
1411 new StoreInst(Null, FieldGlobals[i], SI);
1412 }
1413 // Erase the original store.
1414 SI->eraseFromParent();
1415 }
1416
1417 // While we have PHIs that are interesting to rewrite, do it.
1418 while (!PHIsToRewrite.empty()) {
1419 PHINode *PN = PHIsToRewrite.back().first;
1420 unsigned FieldNo = PHIsToRewrite.back().second;
1421 PHIsToRewrite.pop_back();
1422 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1423 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1424
1425 // Add all the incoming values. This can materialize more phis.
1426 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1427 Value *InVal = PN->getIncomingValue(i);
1428 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001429 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001430 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1431 }
1432 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001433
Victor Hernandez83d63912009-09-18 22:35:49 +00001434 // Drop all inter-phi links and any loads that made it this far.
1435 for (DenseMap<Value*, std::vector<Value*> >::iterator
1436 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1437 I != E; ++I) {
1438 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1439 PN->dropAllReferences();
1440 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1441 LI->dropAllReferences();
1442 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001443
Victor Hernandez83d63912009-09-18 22:35:49 +00001444 // Delete all the phis and loads now that inter-references are dead.
1445 for (DenseMap<Value*, std::vector<Value*> >::iterator
1446 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1447 I != E; ++I) {
1448 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1449 PN->eraseFromParent();
1450 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1451 LI->eraseFromParent();
1452 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001453
Victor Hernandez83d63912009-09-18 22:35:49 +00001454 // The old global is now dead, remove it.
1455 GV->eraseFromParent();
1456
1457 ++NumHeapSRA;
1458 return cast<GlobalVariable>(FieldGlobals[0]);
1459}
1460
Chris Lattnere61d0a62008-12-15 21:02:25 +00001461/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1462/// pointer global variable with a single value stored it that is a malloc or
1463/// cast of malloc.
1464static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001465 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001466 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001467 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001468 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001469 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001470 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001471 if (!TD)
1472 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001473
Victor Hernandez83d63912009-09-18 22:35:49 +00001474 // If this is a malloc of an abstract type, don't touch it.
1475 if (!AllocTy->isSized())
1476 return false;
1477
1478 // We can't optimize this global unless all uses of it are *known* to be
1479 // of the malloc value, not of the null initializer value (consider a use
1480 // that compares the global's value against zero to see if the malloc has
1481 // been reached). To do this, we check to see if all uses of the global
1482 // would trap if the global were null: this proves that they must all
1483 // happen after the malloc.
1484 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1485 return false;
1486
1487 // We can't optimize this if the malloc itself is used in a complex way,
1488 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001489 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001490 // GEP'd. These are all things we could transform to using the global
1491 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001492 SmallPtrSet<const PHINode*, 8> PHIs;
1493 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1494 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001495
1496 // If we have a global that is only initialized with a fixed size malloc,
1497 // transform the program to use global memory instead of malloc'd memory.
1498 // This eliminates dynamic allocation, avoids an indirection accessing the
1499 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001500 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001501 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng86cd4452010-04-14 20:52:55 +00001502 if (!NElems)
1503 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001504
Evan Cheng86cd4452010-04-14 20:52:55 +00001505 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1506 // Restrict this transformation to only working on small allocations
1507 // (2048 bytes currently), as we don't want to introduce a 16M global or
1508 // something.
1509 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001510 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001511 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001512 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001513
Evan Cheng86cd4452010-04-14 20:52:55 +00001514 // If the allocation is an array of structures, consider transforming this
1515 // into multiple malloc'd arrays, one for each field. This is basically
1516 // SRoA for malloc'd memory.
1517
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001518 if (Ordering != NotAtomic)
1519 return false;
1520
Evan Cheng86cd4452010-04-14 20:52:55 +00001521 // If this is an allocation of a fixed size array of structs, analyze as a
1522 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001523 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001524 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001525 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001526
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001527 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001528 if (!AllocSTy)
1529 return false;
1530
1531 // This the structure has an unreasonable number of fields, leave it
1532 // alone.
1533 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1534 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1535
1536 // If this is a fixed size array, transform the Malloc to be an alloc of
1537 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001538 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Matt Arsenaultcf16bae2013-09-11 07:29:40 +00001539 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Evan Cheng86cd4452010-04-14 20:52:55 +00001540 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1541 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1542 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1543 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1544 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001545 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001546 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1547 CI->replaceAllUsesWith(Cast);
1548 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001549 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1550 CI = cast<CallInst>(BCI->getOperand(0));
1551 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001552 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001553 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001554
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001555 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1556 TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001557 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001558 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001559
Victor Hernandez83d63912009-09-18 22:35:49 +00001560 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001561}
Victor Hernandez83d63912009-09-18 22:35:49 +00001562
Chris Lattner9b34a612004-10-09 21:48:45 +00001563// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1564// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001565static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001566 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001567 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001568 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001569 // Ignore no-op GEPs and bitcasts.
1570 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001571
Chris Lattner708148e2004-10-10 23:14:11 +00001572 // If we are dealing with a pointer global that is initialized to null and
1573 // only has one (non-null) value stored into it, then we can optimize any
1574 // users of the loaded value (often calls and loads) that would trap if the
1575 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001576 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001577 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001578 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1579 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001580 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001581
Chris Lattner708148e2004-10-10 23:14:11 +00001582 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001583 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001584 return true;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001585 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1586 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001587 if (MallocType &&
1588 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1589 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001590 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001591 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001592 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001593
Chris Lattner9b34a612004-10-09 21:48:45 +00001594 return false;
1595}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001596
Chris Lattner58e44f42008-01-14 01:17:44 +00001597/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1598/// two values ever stored into GV are its initializer and OtherVal. See if we
1599/// can shrink the global into a boolean and select between the two values
1600/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001601static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001602 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001603
Chris Lattner58e44f42008-01-14 01:17:44 +00001604 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001605 // an FP value, pointer or vector, don't do this optimization because a select
1606 // between them is very expensive and unlikely to lead to later
1607 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1608 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001609 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001610 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001611 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001612 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001613
Chris Lattner58e44f42008-01-14 01:17:44 +00001614 // Walk the use list of the global seeing if all the uses are load or store.
1615 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001616 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1617 User *U = *I;
1618 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001619 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001620 }
1621
David Greene3215b0e2010-01-05 01:28:05 +00001622 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001623
Chris Lattner96a86b22004-12-12 05:53:50 +00001624 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001625 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1626 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001627 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001628 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001629 GV->getName()+".b",
Joey Gouly1d505a32013-01-10 10:31:11 +00001630 GV->getThreadLocalMode(),
1631 GV->getType()->getAddressSpace());
Chris Lattner96a86b22004-12-12 05:53:50 +00001632 GV->getParent()->getGlobalList().insert(GV, NewGV);
1633
1634 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001635 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001636 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001637
1638 // If initialized to zero and storing one into the global, we can use a cast
1639 // instead of a select to synthesize the desired value.
1640 bool IsOneZero = false;
1641 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001642 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001643
1644 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001645 Instruction *UI = cast<Instruction>(GV->use_back());
1646 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001647 // Change the store into a boolean store.
1648 bool StoringOther = SI->getOperand(0) == OtherVal;
1649 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001650 Value *StoreVal;
Bill Wendling17fe48c2013-02-13 23:00:51 +00001651 if (StoringOther || SI->getOperand(0) == InitVal) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001652 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1653 StoringOther);
Bill Wendling17fe48c2013-02-13 23:00:51 +00001654 } else {
Chris Lattner38c25562004-12-12 19:34:41 +00001655 // Otherwise, we are storing a previously loaded copy. To do this,
1656 // change the copy from copying the original value to just copying the
1657 // bool.
1658 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1659
Gabor Greif9e4f2432010-06-24 14:42:01 +00001660 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001661 // select instruction. If not, it will be a load of the original
1662 // global.
1663 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1664 assert(LI->getOperand(0) == GV && "Not a copy!");
1665 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001666 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1667 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001668 } else {
1669 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1670 "This is not a form that we understand!");
1671 StoreVal = StoredVal->getOperand(0);
1672 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1673 }
1674 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001675 new StoreInst(StoreVal, NewGV, false, 0,
1676 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001677 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001678 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001679 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001680 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1681 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001682 Value *NSI;
1683 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001684 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001685 else
Gabor Greif051a9502008-04-06 20:25:17 +00001686 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001687 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001688 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001689 }
1690 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001691 }
1692
Bill Wendling17fe48c2013-02-13 23:00:51 +00001693 // Retain the name of the old global variable. People who are debugging their
1694 // programs may expect these variables to be named the same.
1695 NewGV->takeName(GV);
Chris Lattner96a86b22004-12-12 05:53:50 +00001696 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001697 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001698}
1699
1700
Nick Lewyckydb292a62012-02-12 00:52:26 +00001701/// ProcessGlobal - Analyze the specified global variable and optimize it if
1702/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001703bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1704 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001705 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001706 return false;
1707
1708 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001709 GV->removeDeadConstantUsers();
1710
1711 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001712 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001713 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001714 ++NumDeleted;
1715 return true;
1716 }
1717
Rafael Espindola2f135d42012-06-15 18:00:24 +00001718 if (!GV->hasLocalLinkage())
1719 return false;
1720
Rafael Espindolac4440e32011-01-19 16:32:21 +00001721 GlobalStatus GS;
1722
Rafael Espindola713cab02013-10-21 17:14:55 +00001723 if (GlobalStatus::analyzeGlobal(GV, GS))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001724 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001725
Rafael Espindolab75fcec2013-10-17 18:18:52 +00001726 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
Rafael Espindolac4440e32011-01-19 16:32:21 +00001727 GV->setUnnamedAddr(true);
1728 NumUnnamed++;
1729 }
1730
1731 if (GV->isConstant() || !GV->hasInitializer())
1732 return false;
1733
Rafael Espindola466fa172013-09-05 19:15:21 +00001734 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolac4440e32011-01-19 16:32:21 +00001735}
1736
1737/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1738/// it if possible. If we make a change, return true.
1739bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1740 Module::global_iterator &GVI,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001741 const GlobalStatus &GS) {
Alexey Samsonov23eb9072013-10-07 19:03:24 +00001742 // If this is a first class global and has only one accessing function
1743 // and this function is main (which we know is not recursive), we replace
1744 // the global with a local alloca in this function.
1745 //
1746 // NOTE: It doesn't make sense to promote non single-value types since we
1747 // are just replacing static memory to stack memory.
1748 //
1749 // If the global is in different address space, don't bring it to stack.
1750 if (!GS.HasMultipleAccessingFunctions &&
1751 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1752 GV->getType()->getElementType()->isSingleValueType() &&
1753 GS.AccessingFunction->getName() == "main" &&
1754 GS.AccessingFunction->hasExternalLinkage() &&
1755 GV->getType()->getAddressSpace() == 0) {
1756 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1757 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1758 ->getEntryBlock().begin());
1759 Type *ElemTy = GV->getType()->getElementType();
1760 // FIXME: Pass Global's alignment when globals have alignment
1761 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1762 if (!isa<UndefValue>(GV->getInitializer()))
1763 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1764
1765 GV->replaceAllUsesWith(Alloca);
1766 GV->eraseFromParent();
1767 ++NumLocalized;
1768 return true;
1769 }
1770
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001771 // If the global is never loaded (but may be stored to), it is dead.
1772 // Delete it now.
Rafael Espindolab75fcec2013-10-17 18:18:52 +00001773 if (!GS.IsLoaded) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001774 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1775
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001776 bool Changed;
1777 if (isLeakCheckerRoot(GV)) {
1778 // Delete any constant stores to the global.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001779 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001780 } else {
1781 // Delete any stores we can find to the global. We may not be able to
1782 // make it completely dead though.
1783 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1784 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001785
1786 // If the global is dead now, delete it.
1787 if (GV->use_empty()) {
1788 GV->eraseFromParent();
1789 ++NumDeleted;
1790 Changed = true;
1791 }
1792 return Changed;
1793
Rafael Espindolab75fcec2013-10-17 18:18:52 +00001794 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00001795 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001796 GV->setConstant(true);
1797
1798 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001799 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001800
1801 // If the global is dead now, just nuke it.
1802 if (GV->use_empty()) {
1803 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1804 << "all users and delete global!\n");
1805 GV->eraseFromParent();
1806 ++NumDeleted;
1807 }
1808
1809 ++NumMarked;
1810 return true;
1811 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001812 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001813 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1814 GVI = FirstNewGV; // Don't skip the newly produced globals!
1815 return true;
1816 }
Rafael Espindolab75fcec2013-10-17 18:18:52 +00001817 } else if (GS.StoredType == GlobalStatus::StoredOnce) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001818 // If the initial value for the global was an undef value, and if only
1819 // one other value was stored into it, we can just change the
1820 // initializer to be the stored value, then delete all stores to the
1821 // global. This allows us to mark it constant.
1822 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1823 if (isa<UndefValue>(GV->getInitializer())) {
1824 // Change the initial value here.
1825 GV->setInitializer(SOVConstant);
1826
1827 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001828 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001829
1830 if (GV->use_empty()) {
1831 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001832 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001833 GV->eraseFromParent();
1834 ++NumDeleted;
1835 } else {
1836 GVI = GV;
1837 }
1838 ++NumSubstitute;
1839 return true;
1840 }
1841
1842 // Try to optimize globals based on the knowledge that only one value
1843 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001844 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001845 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001846 return true;
1847
1848 // Otherwise, if the global was not a boolean, we can shrink it to be a
1849 // boolean.
Eli Friedmanb1c54932013-09-09 22:00:13 +00001850 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1851 if (GS.Ordering == NotAtomic) {
1852 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1853 ++NumShrunkToBool;
1854 return true;
1855 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001856 }
Eli Friedmanb1c54932013-09-09 22:00:13 +00001857 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001858 }
1859
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001860 return false;
1861}
1862
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001863/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1864/// function, changing them to FastCC.
1865static void ChangeCalleesToFastCall(Function *F) {
1866 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00001867 if (isa<BlockAddress>(*UI))
1868 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00001869 CallSite User(cast<Instruction>(*UI));
1870 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001871 }
1872}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001873
Bill Wendling99faa3b2012-12-07 23:16:57 +00001874static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001875 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling8e47daf2013-01-25 23:09:36 +00001876 unsigned Index = Attrs.getSlotIndex(i);
1877 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands548448a2008-02-18 17:32:13 +00001878 continue;
1879
Duncan Sands548448a2008-02-18 17:32:13 +00001880 // There can be only one.
Bill Wendling8e47daf2013-01-25 23:09:36 +00001881 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001882 }
1883
1884 return Attrs;
1885}
1886
1887static void RemoveNestAttribute(Function *F) {
Bill Wendling5886b7b2012-10-14 06:39:53 +00001888 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001889 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00001890 if (isa<BlockAddress>(*UI))
1891 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00001892 CallSite User(cast<Instruction>(*UI));
Bill Wendling5886b7b2012-10-14 06:39:53 +00001893 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001894 }
1895}
1896
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001897bool GlobalOpt::OptimizeFunctions(Module &M) {
1898 bool Changed = false;
1899 // Optimize functions.
1900 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1901 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001902 // Functions without names cannot be referenced outside this module.
1903 if (!F->hasName() && !F->isDeclaration())
1904 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001905 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00001906 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001907 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001908 Changed = true;
1909 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001910 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001911 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001912 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001913 // If this function has C calling conventions, is not a varargs
1914 // function, and is only called directly, promote it to use the Fast
1915 // calling convention.
1916 F->setCallingConv(CallingConv::Fast);
1917 ChangeCalleesToFastCall(F);
1918 ++NumFastCallFns;
1919 Changed = true;
1920 }
1921
Bill Wendling034b94b2012-12-19 07:18:57 +00001922 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001923 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001924 // The function is not used by a trampoline intrinsic, so it is safe
1925 // to remove the 'nest' attribute.
1926 RemoveNestAttribute(F);
1927 ++NumNestRemoved;
1928 Changed = true;
1929 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001930 }
1931 }
1932 return Changed;
1933}
1934
1935bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1936 bool Changed = false;
1937 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1938 GVI != E; ) {
1939 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001940 // Global variables without names cannot be referenced outside this module.
1941 if (!GV->hasName() && !GV->isDeclaration())
1942 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001943 // Simplify the initializer.
1944 if (GV->hasInitializer())
1945 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00001946 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001947 if (New && New != CE)
1948 GV->setInitializer(New);
1949 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001950
1951 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001952 }
1953 return Changed;
1954}
1955
Nick Lewycky2c44a802011-04-08 07:30:21 +00001956/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001957/// initializers have an init priority of 65535.
1958GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001959 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1960 if (GV == 0) return 0;
Jakub Staszak582088c2012-12-06 21:57:16 +00001961
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001962 // Verify that the initializer is simple enough for us to handle. We are
1963 // only allowed to optimize the initializer if it is unique.
1964 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001965
1966 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1967 return GV;
1968 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00001969
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001970 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001971 if (isa<ConstantAggregateZero>(*i))
1972 continue;
1973 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001974 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1975 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001976
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001977 // Must have a function or null ptr.
1978 if (!isa<Function>(CS->getOperand(1)))
1979 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001980
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001981 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001982 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1983 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001984 return 0;
1985 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001986
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001987 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001988}
1989
Chris Lattnerdb973e62005-09-26 02:31:18 +00001990/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1991/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001992static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001993 if (GV->getInitializer()->isNullValue())
1994 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001995 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1996 std::vector<Function*> Result;
1997 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001998 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1999 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002000 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2001 }
2002 return Result;
2003}
2004
Chris Lattnerdb973e62005-09-26 02:31:18 +00002005/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2006/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002007static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002008 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002009 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002010 Constant *CSVals[2];
2011 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2012 CSVals[1] = 0;
2013
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002014 StructType *StructTy =
Matt Arsenault244d2452013-10-21 19:43:56 +00002015 cast<StructType>(GCL->getType()->getElementType()->getArrayElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002016
Chris Lattnerdb973e62005-09-26 02:31:18 +00002017 // Create the new init list.
2018 std::vector<Constant*> CAList;
2019 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002020 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002021 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002022 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002023 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002024 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002025 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002026 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002027 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002028 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002029 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002030 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002031 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002032
Chris Lattnerdb973e62005-09-26 02:31:18 +00002033 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002034 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002035 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002036
Chris Lattnerdb973e62005-09-26 02:31:18 +00002037 // If we didn't change the number of elements, don't create a new GV.
2038 if (CA->getType() == GCL->getInitializer()->getType()) {
2039 GCL->setInitializer(CA);
2040 return GCL;
2041 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002042
Chris Lattnerdb973e62005-09-26 02:31:18 +00002043 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002044 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002045 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002046 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002047 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002048 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002049
Chris Lattnerdb973e62005-09-26 02:31:18 +00002050 // Nuke the old list, replacing any uses with the new one.
2051 if (!GCL->use_empty()) {
2052 Constant *V = NGV;
2053 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002054 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002055 GCL->replaceAllUsesWith(V);
2056 }
2057 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002058
Chris Lattnerdb973e62005-09-26 02:31:18 +00002059 if (Ctors.size())
2060 return NGV;
2061 else
2062 return 0;
2063}
Chris Lattner79c11012005-09-26 04:44:35 +00002064
2065
Jakub Staszak582088c2012-12-06 21:57:16 +00002066static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002067isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002068 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002069 const DataLayout *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002070
2071
2072/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2073/// handled by the code generator. We don't want to generate something like:
2074/// void *X = &X/42;
2075/// because the code generator doesn't have a relocation that can handle that.
2076///
2077/// This function should be called if C was not found (but just got inserted)
2078/// in SimpleConstants to avoid having to rescan the same constants all the
2079/// time.
2080static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002081 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002082 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002083 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2084 // all supported.
2085 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2086 isa<GlobalValue>(C))
2087 return true;
Jakub Staszak582088c2012-12-06 21:57:16 +00002088
Chris Lattner1945d582010-12-07 04:33:29 +00002089 // Aggregate values are safe if all their elements are.
2090 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2091 isa<ConstantVector>(C)) {
2092 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2093 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002094 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002095 return false;
2096 }
2097 return true;
2098 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002099
Chris Lattner1945d582010-12-07 04:33:29 +00002100 // We don't know exactly what relocations are allowed in constant expressions,
2101 // so we allow &global+constantoffset, which is safe and uniformly supported
2102 // across targets.
2103 ConstantExpr *CE = cast<ConstantExpr>(C);
2104 switch (CE->getOpcode()) {
2105 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002106 // Bitcast is fine if the casted value is fine.
2107 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2108
Chris Lattner1945d582010-12-07 04:33:29 +00002109 case Instruction::IntToPtr:
2110 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002111 // int <=> ptr is fine if the int type is the same size as the
2112 // pointer type.
2113 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2114 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2115 return false;
2116 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002117
Chris Lattner1945d582010-12-07 04:33:29 +00002118 // GEP is fine if it is simple + constant offset.
2119 case Instruction::GetElementPtr:
2120 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2121 if (!isa<ConstantInt>(CE->getOperand(i)))
2122 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002123 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002124
Chris Lattner1945d582010-12-07 04:33:29 +00002125 case Instruction::Add:
2126 // We allow simple+cst.
2127 if (!isa<ConstantInt>(CE->getOperand(1)))
2128 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002129 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002130 }
2131 return false;
2132}
2133
Jakub Staszak582088c2012-12-06 21:57:16 +00002134static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002135isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002136 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002137 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002138 // If we already checked this constant, we win.
2139 if (!SimpleConstants.insert(C)) return true;
2140 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002141 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002142}
2143
2144
Chris Lattner79c11012005-09-26 04:44:35 +00002145/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002146/// enough for us to understand. In particular, if it is a cast to anything
2147/// other than from one pointer type to another pointer type, we punt.
2148/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002149/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002150static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002151 // Conservatively, avoid aggregate types. This is because we don't
2152 // want to worry about them partially overlapping other stores.
2153 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2154 return false;
2155
Dan Gohmanfd54a892009-09-07 22:31:26 +00002156 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002157 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002158 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002159 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002160
Owen Andersone95a32c2011-01-14 22:31:13 +00002161 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002162 // Handle a constantexpr gep.
2163 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002164 isa<GlobalVariable>(CE->getOperand(0)) &&
2165 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002166 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002167 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002168 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002169 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002170 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002171
Dan Gohman80bdc962009-09-07 22:44:55 +00002172 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002173 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002174 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002175
2176 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002177 // notional bounds of the corresponding static array types.
2178 if (!CE->isGEPWithNoNotionalOverIndexing())
2179 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002180
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002181 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak582088c2012-12-06 21:57:16 +00002182
Owen Andersoncff6b372011-01-14 22:19:20 +00002183 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2184 // and we know how to evaluate it by moving the bitcast from the pointer
2185 // operand to the value operand.
2186 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002187 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002188 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2189 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002190 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002191 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002192 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002193
Chris Lattner79c11012005-09-26 04:44:35 +00002194 return false;
2195}
2196
Chris Lattner798b4d52005-09-26 06:52:44 +00002197/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2198/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2199/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2200static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Shengefcdb292012-12-01 10:54:28 +00002201 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002202 // Base case of the recursion.
2203 if (OpNo == Addr->getNumOperands()) {
2204 assert(Val->getType() == Init->getType() && "Type mismatch!");
2205 return Val;
2206 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002207
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002208 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002209 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002210 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002211 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2212 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002213
Chris Lattner798b4d52005-09-26 06:52:44 +00002214 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002215 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2216 unsigned Idx = CU->getZExtValue();
2217 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Shengefcdb292012-12-01 10:54:28 +00002218 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002219
Chris Lattner798b4d52005-09-26 06:52:44 +00002220 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002221 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002222 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002223
Chris Lattnerb065b062011-06-20 04:01:31 +00002224 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002225 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002226
2227 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002228 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002229 NumElts = ATy->getNumElements();
2230 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002231 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002232
2233 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002234 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2235 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002236
2237 assert(CI->getZExtValue() < NumElts);
2238 Elts[CI->getZExtValue()] =
Zhou Shengefcdb292012-12-01 10:54:28 +00002239 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnerb065b062011-06-20 04:01:31 +00002240
2241 if (Init->getType()->isArrayTy())
2242 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2243 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002244}
2245
Chris Lattner79c11012005-09-26 04:44:35 +00002246/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2247/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002248static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002249 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2250 assert(GV->hasInitializer());
2251 GV->setInitializer(Val);
2252 return;
2253 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002254
Chris Lattner798b4d52005-09-26 06:52:44 +00002255 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2256 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Shengefcdb292012-12-01 10:54:28 +00002257 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002258}
2259
Nick Lewycky7fa76772012-02-20 03:25:59 +00002260namespace {
2261
2262/// Evaluator - This class evaluates LLVM IR, producing the Constant
2263/// representing each SSA instruction. Changes to global variables are stored
2264/// in a mapping that can be iterated over after the evaluation is complete.
2265/// Once an evaluation call fails, the evaluation object should not be reused.
2266class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002267public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002268 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002269 : TD(TD), TLI(TLI) {
2270 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2271 }
2272
Nick Lewycky7fa76772012-02-20 03:25:59 +00002273 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002274 DeleteContainerPointers(ValueStack);
2275 while (!AllocaTmps.empty()) {
2276 GlobalVariable *Tmp = AllocaTmps.back();
2277 AllocaTmps.pop_back();
2278
2279 // If there are still users of the alloca, the program is doing something
2280 // silly, e.g. storing the address of the alloca somewhere and using it
2281 // later. Since this is undefined, we'll just make it be null.
2282 if (!Tmp->use_empty())
2283 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2284 delete Tmp;
2285 }
2286 }
2287
2288 /// EvaluateFunction - Evaluate a call to function F, returning true if
2289 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2290 /// arguments for the function.
2291 bool EvaluateFunction(Function *F, Constant *&RetVal,
2292 const SmallVectorImpl<Constant*> &ActualArgs);
2293
2294 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2295 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2296 /// control flows into, or null upon return.
2297 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2298
2299 Constant *getVal(Value *V) {
2300 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2301 Constant *R = ValueStack.back()->lookup(V);
2302 assert(R && "Reference to an uncomputed value!");
2303 return R;
2304 }
2305
2306 void setVal(Value *V, Constant *C) {
2307 ValueStack.back()->operator[](V) = C;
2308 }
2309
2310 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2311 return MutatedMemory;
2312 }
2313
2314 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2315 return Invariants;
2316 }
2317
2318private:
2319 Constant *ComputeLoadResult(Constant *P);
2320
2321 /// ValueStack - As we compute SSA register values, we store their contents
2322 /// here. The back of the vector contains the current function and the stack
2323 /// contains the values in the calling frames.
2324 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2325
2326 /// CallStack - This is used to detect recursion. In pathological situations
2327 /// we could hit exponential behavior, but at least there is nothing
2328 /// unbounded.
2329 SmallVector<Function*, 4> CallStack;
2330
2331 /// MutatedMemory - For each store we execute, we update this map. Loads
2332 /// check this to get the most up-to-date value. If evaluation is successful,
2333 /// this state is committed to the process.
2334 DenseMap<Constant*, Constant*> MutatedMemory;
2335
2336 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2337 /// to represent its body. This vector is needed so we can delete the
2338 /// temporary globals when we are done.
2339 SmallVector<GlobalVariable*, 32> AllocaTmps;
2340
2341 /// Invariants - These global variables have been marked invariant by the
2342 /// static constructor.
2343 SmallPtrSet<GlobalVariable*, 8> Invariants;
2344
2345 /// SimpleConstants - These are constants we have checked and know to be
2346 /// simple enough to live in a static initializer of a global.
2347 SmallPtrSet<Constant*, 8> SimpleConstants;
2348
Micah Villmow3574eca2012-10-08 16:38:25 +00002349 const DataLayout *TD;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002350 const TargetLibraryInfo *TLI;
2351};
2352
Nick Lewycky7fa76772012-02-20 03:25:59 +00002353} // anonymous namespace
2354
Chris Lattner562a0552005-09-26 05:16:34 +00002355/// ComputeLoadResult - Return the value that would be computed by a load from
2356/// P after the stores reflected by 'memory' have been performed. If we can't
2357/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002358Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002359 // If this memory location has been recently stored, use the stored value: it
2360 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002361 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2362 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002363
Chris Lattner04de1cf2005-09-26 05:15:37 +00002364 // Access it.
2365 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002366 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002367 return GV->getInitializer();
2368 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002369 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002370
Chris Lattner798b4d52005-09-26 06:52:44 +00002371 // Handle a constantexpr getelementptr.
2372 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2373 if (CE->getOpcode() == Instruction::GetElementPtr &&
2374 isa<GlobalVariable>(CE->getOperand(0))) {
2375 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002376 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002377 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002378 }
2379
2380 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002381}
2382
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002383/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2384/// successful, false if we can't evaluate it. NewBB returns the next BB that
2385/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002386bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2387 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002388 // This is the main evaluation loop.
2389 while (1) {
2390 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002391
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002392 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2393
Chris Lattner79c11012005-09-26 04:44:35 +00002394 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002395 if (!SI->isSimple()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002396 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2397 return false; // no volatile/atomic accesses.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002398 }
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002399 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002400 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002401 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Nick Lewyckya641c072012-02-21 22:08:06 +00002402 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002403 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002404 }
2405 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002406 // If this is too complex for us to commit, reject it.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002407 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattnercd271422005-09-27 04:45:34 +00002408 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002409 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002410
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002411 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002412
2413 // If this might be too difficult for the backend to handle (e.g. the addr
2414 // of one global variable divided by another) then we can't commit it.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002415 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002416 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2417 << "\n");
Chris Lattner1945d582010-12-07 04:33:29 +00002418 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002419 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002420
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002421 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002422 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002423 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Andersoncff6b372011-01-14 22:19:20 +00002424 // If we're evaluating a store through a bitcast, then we need
2425 // to pull the bitcast off the pointer type and push it onto the
2426 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002427 Ptr = CE->getOperand(0);
Jakub Staszak582088c2012-12-06 21:57:16 +00002428
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002429 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak582088c2012-12-06 21:57:16 +00002430
Owen Anderson66f708f2011-01-16 04:33:33 +00002431 // In order to push the bitcast onto the stored value, a bitcast
2432 // from NewTy to Val's type must be legal. If it's not, we can try
2433 // introspecting NewTy to find a legal conversion.
2434 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2435 // If NewTy is a struct, we can convert the pointer to the struct
2436 // into a pointer to its first member.
2437 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002438 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002439 NewTy = STy->getTypeAtIndex(0U);
2440
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002441 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002442 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2443 Constant * const IdxList[] = {IdxZero, IdxZero};
2444
Jay Foadb4263a62011-07-22 08:52:50 +00002445 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002446 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2447 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2448
Owen Anderson66f708f2011-01-16 04:33:33 +00002449 // If we can't improve the situation by introspecting NewTy,
2450 // we have to give up.
2451 } else {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002452 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2453 "evaluate.\n");
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002454 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002455 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002456 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002457
Owen Anderson66f708f2011-01-16 04:33:33 +00002458 // If we found compatible types, go ahead and push the bitcast
2459 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002460 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002461
Michael Gottesmandcf66952013-01-11 23:08:52 +00002462 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Andersoncff6b372011-01-14 22:19:20 +00002463 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002464 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002465
Chris Lattner79c11012005-09-26 04:44:35 +00002466 MutatedMemory[Ptr] = Val;
2467 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002468 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002469 getVal(BO->getOperand(0)),
2470 getVal(BO->getOperand(1)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002471 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002472 << "\n");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002473 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002474 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002475 getVal(CI->getOperand(0)),
2476 getVal(CI->getOperand(1)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002477 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002478 << "\n");
Chris Lattner79c11012005-09-26 04:44:35 +00002479 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002480 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002481 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002482 CI->getType());
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002483 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002484 << "\n");
Chris Lattner79c11012005-09-26 04:44:35 +00002485 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002486 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2487 getVal(SI->getOperand(1)),
2488 getVal(SI->getOperand(2)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002489 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002490 << "\n");
Chris Lattner04de1cf2005-09-26 05:15:37 +00002491 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002492 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002493 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002494 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2495 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002496 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002497 InstResult =
2498 ConstantExpr::getGetElementPtr(P, GEPOps,
2499 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002500 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002501 << "\n");
Chris Lattner04de1cf2005-09-26 05:15:37 +00002502 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002503
2504 if (!LI->isSimple()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002505 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2506 return false; // no volatile/atomic accesses.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002507 }
2508
Nick Lewyckya641c072012-02-21 22:08:06 +00002509 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002510 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Nick Lewyckya641c072012-02-21 22:08:06 +00002511 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002512 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2513 "folding: " << *Ptr << "\n");
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002514 }
Nick Lewyckya641c072012-02-21 22:08:06 +00002515 InstResult = ComputeLoadResult(Ptr);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002516 if (InstResult == 0) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002517 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2518 "\n");
2519 return false; // Could not evaluate load.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002520 }
2521
2522 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattnera22fdb02005-09-26 17:07:09 +00002523 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002524 if (AI->isArrayAllocation()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002525 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2526 return false; // Cannot handle array allocs.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002527 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002528 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002529 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002530 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002531 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002532 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002533 InstResult = AllocaTmps.back();
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002534 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002535 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2536 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002537
2538 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002539 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002540 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel412a4462009-03-09 23:04:12 +00002541 ++CurInst;
2542 continue;
2543 }
2544
Chris Lattner7cd580f2006-07-07 21:37:01 +00002545 // Cannot handle inline asm.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002546 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002547 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2548 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002549 }
Chris Lattner7cd580f2006-07-07 21:37:01 +00002550
Nick Lewycky81266c52012-02-17 06:59:21 +00002551 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2552 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002553 if (MSI->isVolatile()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002554 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2555 "intrinsic.\n");
2556 return false;
2557 }
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002558 Constant *Ptr = getVal(MSI->getDest());
2559 Constant *Val = getVal(MSI->getValue());
2560 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002561 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2562 // This memset is a no-op.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002563 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002564 ++CurInst;
2565 continue;
2566 }
2567 }
2568
2569 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2570 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002571 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002572 ++CurInst;
2573 continue;
2574 }
2575
2576 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2577 // We don't insert an entry into Values, as it doesn't have a
2578 // meaningful return value.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002579 if (!II->use_empty()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002580 DEBUG(dbgs() << "Found unused invariant_start. Cant evaluate.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002581 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002582 }
Nick Lewycky81266c52012-02-17 06:59:21 +00002583 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002584 Value *PtrArg = getVal(II->getArgOperand(1));
2585 Value *Ptr = PtrArg->stripPointerCasts();
2586 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2587 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Nick Lewyckyb97b1622013-07-25 02:55:14 +00002588 if (TD && !Size->isAllOnesValue() &&
Nick Lewycky0ef05572012-02-20 23:32:26 +00002589 Size->getValue().getLimitedValue() >=
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002590 TD->getTypeStoreSize(ElemTy)) {
Nick Lewycky81266c52012-02-17 06:59:21 +00002591 Invariants.insert(GV);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002592 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2593 << "\n");
2594 } else {
2595 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2596 "invariant.\n");
2597 }
Nick Lewycky81266c52012-02-17 06:59:21 +00002598 }
2599 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002600 ++CurInst;
2601 continue;
2602 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002603
Michael Gottesmandcf66952013-01-11 23:08:52 +00002604 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewycky1f237b02011-05-29 18:41:56 +00002605 return false;
2606 }
2607
Chris Lattnercd271422005-09-27 04:45:34 +00002608 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002609 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002610 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002611 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002612 return false; // Cannot resolve.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002613 }
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002614
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002615 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002616 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002617 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002618
Reid Spencer5cbf9852007-01-30 20:08:39 +00002619 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002620 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002621 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002622 InstResult = C;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002623 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2624 *InstResult << "\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002625 } else {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002626 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002627 return false;
2628 }
2629 } else {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002630 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002631 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002632 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002633 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002634
Benjamin Kramer08135892013-01-12 15:34:31 +00002635 Constant *RetVal = 0;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002636 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002637 ValueStack.push_back(new DenseMap<Value*, Constant*>);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002638 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002639 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002640 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002641 }
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002642 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002643 InstResult = RetVal;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002644
Michael Gottesmandcf66952013-01-11 23:08:52 +00002645 if (InstResult != NULL) {
2646 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2647 InstResult << "\n\n");
2648 } else {
2649 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2650 }
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002651 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002652 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002653 DEBUG(dbgs() << "Found a terminator instruction.\n");
2654
Chris Lattnercdf98be2005-09-26 04:57:38 +00002655 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2656 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002657 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002658 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002659 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002660 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002661 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002662
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002663 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002664 }
2665 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2666 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002667 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002668 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002669 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002670 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002671 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002672 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002673 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002674 else
2675 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002676 } else if (isa<ReturnInst>(CurInst)) {
2677 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002678 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002679 // invoke, unwind, resume, unreachable.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002680 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattnercd271422005-09-27 04:45:34 +00002681 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002682 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002683
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002684 // We succeeded at evaluating this block!
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002685 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002686 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002687 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002688 // Did not know how to evaluate this!
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002689 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesmandcf66952013-01-11 23:08:52 +00002690 "\n");
Chris Lattnercd271422005-09-27 04:45:34 +00002691 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002692 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002693
Chris Lattner1945d582010-12-07 04:33:29 +00002694 if (!CurInst->use_empty()) {
2695 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002696 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Jakub Staszak582088c2012-12-06 21:57:16 +00002697
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002698 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002699 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002700
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002701 // If we just processed an invoke, we finished evaluating the block.
2702 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2703 NextBB = II->getNormalDest();
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002704 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002705 return true;
2706 }
2707
Chris Lattner79c11012005-09-26 04:44:35 +00002708 // Advance program counter.
2709 ++CurInst;
2710 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002711}
2712
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002713/// EvaluateFunction - Evaluate a call to function F, returning true if
2714/// successful, false if we can't evaluate it. ActualArgs contains the formal
2715/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002716bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2717 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002718 // Check to see if this function is already executing (recursion). If so,
2719 // bail out. TODO: we might want to accept limited recursion.
2720 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2721 return false;
2722
2723 CallStack.push_back(F);
2724
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002725 // Initialize arguments to the incoming values specified.
2726 unsigned ArgNo = 0;
2727 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2728 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002729 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002730
2731 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2732 // we can only evaluate any one basic block at most once. This set keeps
2733 // track of what we have executed so we can detect recursive cases etc.
2734 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2735
2736 // CurBB - The current basic block we're evaluating.
2737 BasicBlock *CurBB = F->begin();
2738
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002739 BasicBlock::iterator CurInst = CurBB->begin();
2740
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002741 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002742 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002743 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2744
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002745 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002746 return false;
2747
2748 if (NextBB == 0) {
2749 // Successfully running until there's no next block means that we found
2750 // the return. Fill it the return value and pop the call stack.
2751 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2752 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002753 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002754 CallStack.pop_back();
2755 return true;
2756 }
2757
2758 // Okay, we succeeded in evaluating this control flow. See if we have
2759 // executed the new block before. If so, we have a looping function,
2760 // which we cannot evaluate in reasonable time.
2761 if (!ExecutedBlocks.insert(NextBB))
2762 return false; // looped!
2763
2764 // Okay, we have never been in this block before. Check to see if there
2765 // are any PHI nodes. If so, evaluate them with information about where
2766 // we came from.
2767 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002768 for (CurInst = NextBB->begin();
2769 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002770 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002771
2772 // Advance to the next block.
2773 CurBB = NextBB;
2774 }
2775}
2776
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002777/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2778/// we can. Return true if we can, false otherwise.
Micah Villmow3574eca2012-10-08 16:38:25 +00002779static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosier00737bd2011-12-01 21:29:16 +00002780 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002781 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002782 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002783 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002784 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2785 SmallVector<Constant*, 0>());
Jakub Staszak582088c2012-12-06 21:57:16 +00002786
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002787 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002788 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002789 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002790 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002791 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002792 for (DenseMap<Constant*, Constant*>::const_iterator I =
2793 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002794 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002795 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002796 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2797 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2798 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002799 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002800 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002801
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002802 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002803}
2804
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002805/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2806/// Return true if anything changed.
2807bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2808 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2809 bool MadeChange = false;
2810 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002811
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002812 // Loop over global ctors, optimizing them when we can.
2813 for (unsigned i = 0; i != Ctors.size(); ++i) {
2814 Function *F = Ctors[i];
2815 // Found a null terminator in the middle of the list, prune off the rest of
2816 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002817 if (F == 0) {
2818 if (i != Ctors.size()-1) {
2819 Ctors.resize(i+1);
2820 MadeChange = true;
2821 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002822 break;
2823 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002824 DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002825
Chris Lattner79c11012005-09-26 04:44:35 +00002826 // We cannot simplify external ctor functions.
2827 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002828
Chris Lattner79c11012005-09-26 04:44:35 +00002829 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002830 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002831 Ctors.erase(Ctors.begin()+i);
2832 MadeChange = true;
2833 --i;
2834 ++NumCtorsEvaluated;
2835 continue;
2836 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002837 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002838
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002839 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002840
Chris Lattner7b550cc2009-11-06 04:27:31 +00002841 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002842 return true;
2843}
2844
Benjamin Kramer0d293e42013-09-22 14:09:50 +00002845static int compareNames(Constant *const *A, Constant *const *B) {
2846 return (*A)->getName().compare((*B)->getName());
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002847}
Rafael Espindola95f88532013-05-09 17:22:59 +00002848
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002849static void setUsedInitializer(GlobalVariable &V,
2850 SmallPtrSet<GlobalValue *, 8> Init) {
Rafael Espindola64f2f912013-07-20 23:33:15 +00002851 if (Init.empty()) {
2852 V.eraseFromParent();
2853 return;
2854 }
2855
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002856 SmallVector<llvm::Constant *, 8> UsedArray;
2857 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext());
Rafael Espindola95f88532013-05-09 17:22:59 +00002858
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002859 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Init.begin(), E = Init.end();
2860 I != E; ++I) {
2861 Constant *Cast = llvm::ConstantExpr::getBitCast(*I, Int8PtrTy);
2862 UsedArray.push_back(Cast);
Rafael Espindola95f88532013-05-09 17:22:59 +00002863 }
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002864 // Sort to get deterministic order.
2865 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
2866 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola95f88532013-05-09 17:22:59 +00002867
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002868 Module *M = V.getParent();
2869 V.removeFromParent();
2870 GlobalVariable *NV =
2871 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2872 llvm::ConstantArray::get(ATy, UsedArray), "");
2873 NV->takeName(&V);
2874 NV->setSection("llvm.metadata");
2875 delete &V;
Rafael Espindola95f88532013-05-09 17:22:59 +00002876}
2877
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002878namespace {
Rafael Espindola70968312013-07-19 18:44:51 +00002879/// \brief An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002880class LLVMUsed {
2881 SmallPtrSet<GlobalValue *, 8> Used;
2882 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2883 GlobalVariable *UsedV;
2884 GlobalVariable *CompilerUsedV;
2885
2886public:
Rafael Espindola2d680822013-07-25 02:50:08 +00002887 LLVMUsed(Module &M) {
Rafael Espindola4ef7eaf2013-07-25 03:23:25 +00002888 UsedV = collectUsedGlobalVariables(M, Used, false);
2889 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola95f88532013-05-09 17:22:59 +00002890 }
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002891 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
2892 iterator usedBegin() { return Used.begin(); }
2893 iterator usedEnd() { return Used.end(); }
2894 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2895 iterator compilerUsedEnd() { return CompilerUsed.end(); }
2896 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2897 bool compilerUsedCount(GlobalValue *GV) const {
2898 return CompilerUsed.count(GV);
2899 }
2900 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2901 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2902 bool usedInsert(GlobalValue *GV) { return Used.insert(GV); }
2903 bool compilerUsedInsert(GlobalValue *GV) { return CompilerUsed.insert(GV); }
Rafael Espindola95f88532013-05-09 17:22:59 +00002904
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002905 void syncVariablesAndSets() {
2906 if (UsedV)
2907 setUsedInitializer(*UsedV, Used);
2908 if (CompilerUsedV)
2909 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2910 }
2911};
Rafael Espindola95f88532013-05-09 17:22:59 +00002912}
2913
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002914static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2915 if (GA.use_empty()) // No use at all.
2916 return false;
2917
2918 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2919 "We should have removed the duplicated "
Rafael Espindola70968312013-07-19 18:44:51 +00002920 "element from llvm.compiler.used");
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002921 if (!GA.hasOneUse())
2922 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola70968312013-07-19 18:44:51 +00002923 // llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002924 return true;
2925
Rafael Espindola70968312013-07-19 18:44:51 +00002926 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002927 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola95f88532013-05-09 17:22:59 +00002928}
2929
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002930static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2931 const LLVMUsed &U) {
2932 unsigned N = 2;
2933 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2934 "We should have removed the duplicated "
Rafael Espindola70968312013-07-19 18:44:51 +00002935 "element from llvm.compiler.used");
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002936 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2937 ++N;
2938 return V.hasNUsesOrMore(N);
2939}
2940
2941static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2942 if (!GA.hasLocalLinkage())
2943 return true;
2944
2945 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2946}
2947
2948static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget) {
2949 RenameTarget = false;
Rafael Espindola95f88532013-05-09 17:22:59 +00002950 bool Ret = false;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002951 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola95f88532013-05-09 17:22:59 +00002952 Ret = true;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002953
2954 // If the alias is externally visible, we may still be able to simplify it.
2955 if (!mayHaveOtherReferences(GA, U))
2956 return Ret;
2957
2958 // If the aliasee has internal linkage, give it the name and linkage
2959 // of the alias, and delete the alias. This turns:
2960 // define internal ... @f(...)
2961 // @a = alias ... @f
2962 // into:
2963 // define ... @a(...)
2964 Constant *Aliasee = GA.getAliasee();
2965 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2966 if (!Target->hasLocalLinkage())
2967 return Ret;
2968
2969 // Do not perform the transform if multiple aliases potentially target the
2970 // aliasee. This check also ensures that it is safe to replace the section
2971 // and other attributes of the aliasee with those of the alias.
2972 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2973 return Ret;
2974
2975 RenameTarget = true;
2976 return true;
Rafael Espindola95f88532013-05-09 17:22:59 +00002977}
2978
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002979bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002980 bool Changed = false;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002981 LLVMUsed Used(M);
2982
2983 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.usedBegin(),
2984 E = Used.usedEnd();
2985 I != E; ++I)
2986 Used.compilerUsedErase(*I);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002987
Duncan Sands177d84e2009-01-07 20:01:06 +00002988 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002989 I != E;) {
2990 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002991 // Aliases without names cannot be referenced outside this module.
2992 if (!J->hasName() && !J->isDeclaration())
2993 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002994 // If the aliasee may change at link time, nothing can be done - bail out.
2995 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002996 continue;
2997
Duncan Sands4782b302009-02-15 09:56:08 +00002998 Constant *Aliasee = J->getAliasee();
2999 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00003000 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00003001
3002 // Make all users of the alias use the aliasee instead.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003003 bool RenameTarget;
3004 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola95f88532013-05-09 17:22:59 +00003005 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00003006
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003007 J->replaceAllUsesWith(Aliasee);
3008 ++NumAliasesResolved;
3009 Changed = true;
Duncan Sands4782b302009-02-15 09:56:08 +00003010
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003011 if (RenameTarget) {
Duncan Sands7a154cf2009-12-08 10:10:20 +00003012 // Give the aliasee the name, linkage and other attributes of the alias.
3013 Target->takeName(J);
3014 Target->setLinkage(J->getLinkage());
3015 Target->GlobalValue::copyAttributesFrom(J);
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003016
3017 if (Used.usedErase(J))
3018 Used.usedInsert(Target);
3019
3020 if (Used.compilerUsedErase(J))
3021 Used.compilerUsedInsert(Target);
Rafael Espindola100fbdd2013-06-12 16:45:47 +00003022 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003023 continue;
3024
Duncan Sands4782b302009-02-15 09:56:08 +00003025 // Delete the alias.
3026 M.getAliasList().erase(J);
3027 ++NumAliasesRemoved;
3028 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003029 }
3030
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003031 Used.syncVariablesAndSets();
3032
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003033 return Changed;
3034}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003035
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003036static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3037 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00003038 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003039
3040 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak582088c2012-12-06 21:57:16 +00003041
Anders Carlssona201c4c2011-03-20 17:59:11 +00003042 if (!Fn)
3043 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003044
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003045 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak582088c2012-12-06 21:57:16 +00003046
3047 // Checking that the function has the right return type, the right number of
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003048 // parameters and that they all have pointer types should be enough.
3049 if (!FTy->getReturnType()->isIntegerTy() ||
3050 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003051 !FTy->getParamType(0)->isPointerTy() ||
3052 !FTy->getParamType(1)->isPointerTy() ||
3053 !FTy->getParamType(2)->isPointerTy())
3054 return 0;
3055
3056 return Fn;
3057}
3058
3059/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3060/// destructor and can therefore be eliminated.
3061/// Note that we assume that other optimization passes have already simplified
3062/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003063/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3064/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003065static bool cxxDtorIsEmpty(const Function &Fn,
3066 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003067 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003068 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003069 if (Fn.isDeclaration())
3070 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003071
3072 if (++Fn.begin() != Fn.end())
3073 return false;
3074
3075 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3076 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3077 I != E; ++I) {
3078 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003079 // Ignore debug intrinsics.
3080 if (isa<DbgInfoIntrinsic>(CI))
3081 continue;
3082
Anders Carlssona201c4c2011-03-20 17:59:11 +00003083 const Function *CalledFn = CI->getCalledFunction();
3084
3085 if (!CalledFn)
3086 return false;
3087
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003088 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3089
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003090 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003091 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003092 return false;
3093
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003094 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003095 return false;
3096 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003097 return true; // We're done.
3098 else if (I->mayHaveSideEffects())
3099 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003100 }
3101
3102 return false;
3103}
3104
3105bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3106 /// Itanium C++ ABI p3.3.5:
3107 ///
3108 /// After constructing a global (or local static) object, that will require
3109 /// destruction on exit, a termination function is registered as follows:
3110 ///
3111 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3112 ///
3113 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3114 /// call f(p) when DSO d is unloaded, before all such termination calls
3115 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003116 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003117
3118 // This pass will look for calls to __cxa_atexit where the function is trivial
3119 // and remove them.
3120 bool Changed = false;
3121
Jakub Staszak582088c2012-12-06 21:57:16 +00003122 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
Anders Carlssona201c4c2011-03-20 17:59:11 +00003123 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003124 // We're only interested in calls. Theoretically, we could handle invoke
3125 // instructions as well, but neither llvm-gcc nor clang generate invokes
3126 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003127 CallInst *CI = dyn_cast<CallInst>(*I++);
3128 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003129 continue;
3130
Jakub Staszak582088c2012-12-06 21:57:16 +00003131 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003132 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003133 if (!DtorFn)
3134 continue;
3135
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003136 SmallPtrSet<const Function *, 8> CalledFunctions;
3137 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003138 continue;
3139
3140 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003141 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3142 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003143
Anders Carlssona201c4c2011-03-20 17:59:11 +00003144 ++NumCXXDtorsRemoved;
3145
3146 Changed |= true;
3147 }
3148
3149 return Changed;
3150}
3151
Chris Lattner7a90b682004-10-07 04:16:33 +00003152bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003153 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003154
Micah Villmow3574eca2012-10-08 16:38:25 +00003155 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003156 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003157
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003158 // Try to find the llvm.globalctors list.
3159 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003160
Chris Lattner7a90b682004-10-07 04:16:33 +00003161 bool LocalChange = true;
3162 while (LocalChange) {
3163 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003164
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003165 // Delete functions that are trivially dead, ccc -> fastcc
3166 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003167
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003168 // Optimize global_ctors list.
3169 if (GlobalCtors)
3170 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003171
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003172 // Optimize non-address-taken globals.
3173 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003174
3175 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003176 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003177
Manman Ren51502702013-05-14 21:52:44 +00003178 // Try to remove trivial global destructors if they are not removed
3179 // already.
3180 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003181 if (CXAAtExitFn)
3182 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3183
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003184 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003185 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003186
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003187 // TODO: Move all global ctors functions to the end of the module for code
3188 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003189
Chris Lattner079236d2004-02-25 21:34:36 +00003190 return Changed;
3191}