blob: 74ed4e2e54eb16cee8c99dcf1a22a7bc9e2b5e44 [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.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001178 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001179 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001180
Jay Foadd8b4fb42011-03-30 11:19:20 +00001181 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001182 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001183 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001184 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001185 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001186 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1187 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001188 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001189 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001190
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001191 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001192}
1193
Chris Lattner330245e2007-09-13 17:29:05 +00001194/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1195/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001196static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001197 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001198 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001199 // If this is a comparison against null, handle it.
1200 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1201 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1202 // If we have a setcc of the loaded pointer, we can use a setcc of any
1203 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001204 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001205 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001206
Owen Anderson333c4002009-07-09 23:48:35 +00001207 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001208 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001209 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001210 SCI->replaceAllUsesWith(New);
1211 SCI->eraseFromParent();
1212 return;
1213 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001214
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001215 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001216 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1217 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1218 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001219
Chris Lattnera637a8b2007-09-13 18:00:31 +00001220 // Load the pointer for this field.
1221 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001222 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001223 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001224
Chris Lattnera637a8b2007-09-13 18:00:31 +00001225 // Create the new GEP idx vector.
1226 SmallVector<Value*, 8> GEPIdx;
1227 GEPIdx.push_back(GEPI->getOperand(1));
1228 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001229
Jay Foada9203102011-07-25 09:48:08 +00001230 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001231 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001232 GEPI->replaceAllUsesWith(NGEPI);
1233 GEPI->eraseFromParent();
1234 return;
1235 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001236
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001237 // Recursively transform the users of PHI nodes. This will lazily create the
1238 // PHIs that are needed for individual elements. Keep track of what PHIs we
1239 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1240 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1241 // already been seen first by another load, so its uses have already been
1242 // processed.
1243 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001244 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1245 std::vector<Value*>())).second)
1246 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001247
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001248 // If this is the first time we've seen this PHI, recursively process all
1249 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001250 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1251 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001252 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001253 }
Chris Lattner330245e2007-09-13 17:29:05 +00001254}
1255
Chris Lattner86395032006-09-30 23:32:09 +00001256/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1257/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1258/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001259/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001260static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001261 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001262 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001263 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001264 UI != E; ) {
1265 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001266 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001267 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001268
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001269 if (Load->use_empty()) {
1270 Load->eraseFromParent();
1271 InsertedScalarizedValues.erase(Load);
1272 }
Chris Lattner86395032006-09-30 23:32:09 +00001273}
1274
Victor Hernandez83d63912009-09-18 22:35:49 +00001275/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1276/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001277static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001278 Value *NElems, DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001279 const TargetLibraryInfo *TLI) {
David Greene3215b0e2010-01-05 01:28:05 +00001280 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001281 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001282 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001283
1284 // There is guaranteed to be at least one use of the malloc (storing
1285 // it into GV). If there are other uses, change them to be uses of
1286 // the global to simplify later code. This also deletes the store
1287 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001288 ReplaceUsesOfMallocWithGlobal(CI, GV);
1289
Victor Hernandez83d63912009-09-18 22:35:49 +00001290 // Okay, at this point, there are no users of the malloc. Insert N
1291 // new mallocs at the same place as CI, and N globals.
1292 std::vector<Value*> FieldGlobals;
1293 std::vector<Value*> FieldMallocs;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001294
Victor Hernandez83d63912009-09-18 22:35:49 +00001295 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001296 Type *FieldTy = STy->getElementType(FieldNo);
1297 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001298
Victor Hernandez83d63912009-09-18 22:35:49 +00001299 GlobalVariable *NGV =
1300 new GlobalVariable(*GV->getParent(),
1301 PFieldTy, false, GlobalValue::InternalLinkage,
1302 Constant::getNullValue(PFieldTy),
1303 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001304 GV->getThreadLocalMode());
Victor Hernandez83d63912009-09-18 22:35:49 +00001305 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001306
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001307 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001308 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001309 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Matt Arsenaultcf16bae2013-09-11 07:29:40 +00001310 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001311 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1312 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001313 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001314 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001315 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001316 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001317 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001318
Victor Hernandez83d63912009-09-18 22:35:49 +00001319 // The tricky aspect of this transformation is handling the case when malloc
1320 // fails. In the original code, malloc failing would set the result pointer
1321 // of malloc to null. In this case, some mallocs could succeed and others
1322 // could fail. As such, we emit code that looks like this:
1323 // F0 = malloc(field0)
1324 // F1 = malloc(field1)
1325 // F2 = malloc(field2)
1326 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1327 // if (F0) { free(F0); F0 = 0; }
1328 // if (F1) { free(F1); F1 = 0; }
1329 // if (F2) { free(F2); F2 = 0; }
1330 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001331 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001332 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1333 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001334 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001335 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001336 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1337 Constant::getNullValue(FieldMallocs[i]->getType()),
1338 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001339 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001340 }
1341
1342 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001343 BasicBlock *OrigBB = CI->getParent();
1344 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001345
Victor Hernandez83d63912009-09-18 22:35:49 +00001346 // Create the block to check the first condition. Put all these blocks at the
1347 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001348 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1349 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001350 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001351
Victor Hernandez83d63912009-09-18 22:35:49 +00001352 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1353 // branch on RunningOr.
1354 OrigBB->getTerminator()->eraseFromParent();
1355 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001356
Victor Hernandez83d63912009-09-18 22:35:49 +00001357 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1358 // pointer, because some may be null while others are not.
1359 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1360 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001361 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001362 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001363 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001364 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001365 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001366 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001367 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1368 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001369
1370 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001371 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001372 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1373 FreeBlock);
1374 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001375
Victor Hernandez83d63912009-09-18 22:35:49 +00001376 NullPtrBlock = NextBlock;
1377 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001378
Victor Hernandez83d63912009-09-18 22:35:49 +00001379 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001380
1381 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001382 CI->eraseFromParent();
1383
1384 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1385 /// update all uses of the load, keep track of what scalarized loads are
1386 /// inserted for a given load.
1387 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1388 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001389
Victor Hernandez83d63912009-09-18 22:35:49 +00001390 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001391
Victor Hernandez83d63912009-09-18 22:35:49 +00001392 // Okay, the malloc site is completely handled. All of the uses of GV are now
1393 // loads, and all uses of those loads are simple. Rewrite them to use loads
1394 // of the per-field globals instead.
1395 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1396 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001397
Victor Hernandez83d63912009-09-18 22:35:49 +00001398 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001399 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001400 continue;
1401 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001402
Victor Hernandez83d63912009-09-18 22:35:49 +00001403 // Must be a store of null.
1404 StoreInst *SI = cast<StoreInst>(User);
1405 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1406 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001407
Victor Hernandez83d63912009-09-18 22:35:49 +00001408 // Insert a store of null into each global.
1409 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001410 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001411 Constant *Null = Constant::getNullValue(PT->getElementType());
1412 new StoreInst(Null, FieldGlobals[i], SI);
1413 }
1414 // Erase the original store.
1415 SI->eraseFromParent();
1416 }
1417
1418 // While we have PHIs that are interesting to rewrite, do it.
1419 while (!PHIsToRewrite.empty()) {
1420 PHINode *PN = PHIsToRewrite.back().first;
1421 unsigned FieldNo = PHIsToRewrite.back().second;
1422 PHIsToRewrite.pop_back();
1423 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1424 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1425
1426 // Add all the incoming values. This can materialize more phis.
1427 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1428 Value *InVal = PN->getIncomingValue(i);
1429 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001430 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001431 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1432 }
1433 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001434
Victor Hernandez83d63912009-09-18 22:35:49 +00001435 // Drop all inter-phi links and any loads that made it this far.
1436 for (DenseMap<Value*, std::vector<Value*> >::iterator
1437 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1438 I != E; ++I) {
1439 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1440 PN->dropAllReferences();
1441 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1442 LI->dropAllReferences();
1443 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001444
Victor Hernandez83d63912009-09-18 22:35:49 +00001445 // Delete all the phis and loads now that inter-references are dead.
1446 for (DenseMap<Value*, std::vector<Value*> >::iterator
1447 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1448 I != E; ++I) {
1449 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1450 PN->eraseFromParent();
1451 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1452 LI->eraseFromParent();
1453 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001454
Victor Hernandez83d63912009-09-18 22:35:49 +00001455 // The old global is now dead, remove it.
1456 GV->eraseFromParent();
1457
1458 ++NumHeapSRA;
1459 return cast<GlobalVariable>(FieldGlobals[0]);
1460}
1461
Chris Lattnere61d0a62008-12-15 21:02:25 +00001462/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1463/// pointer global variable with a single value stored it that is a malloc or
1464/// cast of malloc.
1465static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001466 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001467 Type *AllocTy,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001468 AtomicOrdering Ordering,
Victor Hernandez83d63912009-09-18 22:35:49 +00001469 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001470 DataLayout *TD,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001471 TargetLibraryInfo *TLI) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001472 if (!TD)
1473 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001474
Victor Hernandez83d63912009-09-18 22:35:49 +00001475 // If this is a malloc of an abstract type, don't touch it.
1476 if (!AllocTy->isSized())
1477 return false;
1478
1479 // We can't optimize this global unless all uses of it are *known* to be
1480 // of the malloc value, not of the null initializer value (consider a use
1481 // that compares the global's value against zero to see if the malloc has
1482 // been reached). To do this, we check to see if all uses of the global
1483 // would trap if the global were null: this proves that they must all
1484 // happen after the malloc.
1485 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1486 return false;
1487
1488 // We can't optimize this if the malloc itself is used in a complex way,
1489 // for example, being stored into multiple globals. This allows the
Nick Lewyckybc384a12012-02-05 19:48:37 +00001490 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez83d63912009-09-18 22:35:49 +00001491 // GEP'd. These are all things we could transform to using the global
1492 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001493 SmallPtrSet<const PHINode*, 8> PHIs;
1494 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1495 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001496
1497 // If we have a global that is only initialized with a fixed size malloc,
1498 // transform the program to use global memory instead of malloc'd memory.
1499 // This eliminates dynamic allocation, avoids an indirection accessing the
1500 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001501 // We cannot optimize the malloc if we cannot determine malloc array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001502 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
Evan Cheng86cd4452010-04-14 20:52:55 +00001503 if (!NElems)
1504 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001505
Evan Cheng86cd4452010-04-14 20:52:55 +00001506 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1507 // Restrict this transformation to only working on small allocations
1508 // (2048 bytes currently), as we don't want to introduce a 16M global or
1509 // something.
1510 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
Nick Lewycky6a577f82012-02-12 01:13:18 +00001511 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001512 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001513 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001514
Evan Cheng86cd4452010-04-14 20:52:55 +00001515 // If the allocation is an array of structures, consider transforming this
1516 // into multiple malloc'd arrays, one for each field. This is basically
1517 // SRoA for malloc'd memory.
1518
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001519 if (Ordering != NotAtomic)
1520 return false;
1521
Evan Cheng86cd4452010-04-14 20:52:55 +00001522 // If this is an allocation of a fixed size array of structs, analyze as a
1523 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001524 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001525 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001526 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001527
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001528 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001529 if (!AllocSTy)
1530 return false;
1531
1532 // This the structure has an unreasonable number of fields, leave it
1533 // alone.
1534 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1535 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1536
1537 // If this is a fixed size array, transform the Malloc to be an alloc of
1538 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001539 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Matt Arsenaultcf16bae2013-09-11 07:29:40 +00001540 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
Evan Cheng86cd4452010-04-14 20:52:55 +00001541 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1542 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1543 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1544 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1545 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001546 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001547 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1548 CI->replaceAllUsesWith(Cast);
1549 CI->eraseFromParent();
Nuno Lopeseb7c6862012-06-22 00:25:01 +00001550 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1551 CI = cast<CallInst>(BCI->getOperand(0));
1552 else
Nuno Lopescd88efe2012-06-22 00:29:58 +00001553 CI = cast<CallInst>(Malloc);
Evan Cheng86cd4452010-04-14 20:52:55 +00001554 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001555
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001556 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1557 TD, TLI);
Evan Cheng86cd4452010-04-14 20:52:55 +00001558 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001559 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001560
Victor Hernandez83d63912009-09-18 22:35:49 +00001561 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001562}
Victor Hernandez83d63912009-09-18 22:35:49 +00001563
Chris Lattner9b34a612004-10-09 21:48:45 +00001564// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1565// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001566static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001567 AtomicOrdering Ordering,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001568 Module::global_iterator &GVI,
Micah Villmow3574eca2012-10-08 16:38:25 +00001569 DataLayout *TD, TargetLibraryInfo *TLI) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001570 // Ignore no-op GEPs and bitcasts.
1571 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001572
Chris Lattner708148e2004-10-10 23:14:11 +00001573 // If we are dealing with a pointer global that is initialized to null and
1574 // only has one (non-null) value stored into it, then we can optimize any
1575 // users of the loaded value (often calls and loads) that would trap if the
1576 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001577 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001578 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001579 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1580 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001581 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001582
Chris Lattner708148e2004-10-10 23:14:11 +00001583 // Optimize away any trapping uses of the loaded value.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001584 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
Chris Lattner8be80122004-10-10 17:07:12 +00001585 return true;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001586 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1587 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewycky6a577f82012-02-12 01:13:18 +00001588 if (MallocType &&
1589 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1590 TD, TLI))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001591 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001592 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001593 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001594
Chris Lattner9b34a612004-10-09 21:48:45 +00001595 return false;
1596}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001597
Chris Lattner58e44f42008-01-14 01:17:44 +00001598/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1599/// two values ever stored into GV are its initializer and OtherVal. See if we
1600/// can shrink the global into a boolean and select between the two values
1601/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001602static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001603 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001604
Chris Lattner58e44f42008-01-14 01:17:44 +00001605 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001606 // an FP value, pointer or vector, don't do this optimization because a select
1607 // between them is very expensive and unlikely to lead to later
1608 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1609 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001610 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001611 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001612 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001613 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001614
Chris Lattner58e44f42008-01-14 01:17:44 +00001615 // Walk the use list of the global seeing if all the uses are load or store.
1616 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001617 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1618 User *U = *I;
1619 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001620 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001621 }
1622
David Greene3215b0e2010-01-05 01:28:05 +00001623 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001624
Chris Lattner96a86b22004-12-12 05:53:50 +00001625 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001626 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1627 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001628 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001629 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001630 GV->getName()+".b",
Joey Gouly1d505a32013-01-10 10:31:11 +00001631 GV->getThreadLocalMode(),
1632 GV->getType()->getAddressSpace());
Chris Lattner96a86b22004-12-12 05:53:50 +00001633 GV->getParent()->getGlobalList().insert(GV, NewGV);
1634
1635 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001636 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001637 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001638
1639 // If initialized to zero and storing one into the global, we can use a cast
1640 // instead of a select to synthesize the desired value.
1641 bool IsOneZero = false;
1642 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001643 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001644
1645 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001646 Instruction *UI = cast<Instruction>(GV->use_back());
1647 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001648 // Change the store into a boolean store.
1649 bool StoringOther = SI->getOperand(0) == OtherVal;
1650 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001651 Value *StoreVal;
Bill Wendling17fe48c2013-02-13 23:00:51 +00001652 if (StoringOther || SI->getOperand(0) == InitVal) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001653 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1654 StoringOther);
Bill Wendling17fe48c2013-02-13 23:00:51 +00001655 } else {
Chris Lattner38c25562004-12-12 19:34:41 +00001656 // Otherwise, we are storing a previously loaded copy. To do this,
1657 // change the copy from copying the original value to just copying the
1658 // bool.
1659 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1660
Gabor Greif9e4f2432010-06-24 14:42:01 +00001661 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001662 // select instruction. If not, it will be a load of the original
1663 // global.
1664 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1665 assert(LI->getOperand(0) == GV && "Not a copy!");
1666 // Insert a new load, to preserve the saved value.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001667 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1668 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner38c25562004-12-12 19:34:41 +00001669 } else {
1670 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1671 "This is not a form that we understand!");
1672 StoreVal = StoredVal->getOperand(0);
1673 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1674 }
1675 }
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001676 new StoreInst(StoreVal, NewGV, false, 0,
1677 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patel771281f2009-03-06 01:39:36 +00001678 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001679 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001680 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001681 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1682 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001683 Value *NSI;
1684 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001685 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001686 else
Gabor Greif051a9502008-04-06 20:25:17 +00001687 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001688 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001689 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001690 }
1691 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001692 }
1693
Bill Wendling17fe48c2013-02-13 23:00:51 +00001694 // Retain the name of the old global variable. People who are debugging their
1695 // programs may expect these variables to be named the same.
1696 NewGV->takeName(GV);
Chris Lattner96a86b22004-12-12 05:53:50 +00001697 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001698 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001699}
1700
1701
Nick Lewyckydb292a62012-02-12 00:52:26 +00001702/// ProcessGlobal - Analyze the specified global variable and optimize it if
1703/// possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001704bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1705 Module::global_iterator &GVI) {
Rafael Espindola03977292012-06-14 22:48:13 +00001706 if (!GV->isDiscardableIfUnused())
Rafael Espindolac4440e32011-01-19 16:32:21 +00001707 return false;
1708
1709 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001710 GV->removeDeadConstantUsers();
1711
1712 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001713 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001714 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001715 ++NumDeleted;
1716 return true;
1717 }
1718
Rafael Espindola2f135d42012-06-15 18:00:24 +00001719 if (!GV->hasLocalLinkage())
1720 return false;
1721
Rafael Espindolac4440e32011-01-19 16:32:21 +00001722 GlobalStatus GS;
1723
Rafael Espindola713cab02013-10-21 17:14:55 +00001724 if (GlobalStatus::analyzeGlobal(GV, GS))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001725 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001726
Rafael Espindolab75fcec2013-10-17 18:18:52 +00001727 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
Rafael Espindolac4440e32011-01-19 16:32:21 +00001728 GV->setUnnamedAddr(true);
1729 NumUnnamed++;
1730 }
1731
1732 if (GV->isConstant() || !GV->hasInitializer())
1733 return false;
1734
Rafael Espindola466fa172013-09-05 19:15:21 +00001735 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolac4440e32011-01-19 16:32:21 +00001736}
1737
1738/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1739/// it if possible. If we make a change, return true.
1740bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1741 Module::global_iterator &GVI,
Rafael Espindolac4440e32011-01-19 16:32:21 +00001742 const GlobalStatus &GS) {
Alexey Samsonov23eb9072013-10-07 19:03:24 +00001743 // If this is a first class global and has only one accessing function
1744 // and this function is main (which we know is not recursive), we replace
1745 // the global with a local alloca in this function.
1746 //
1747 // NOTE: It doesn't make sense to promote non single-value types since we
1748 // are just replacing static memory to stack memory.
1749 //
1750 // If the global is in different address space, don't bring it to stack.
1751 if (!GS.HasMultipleAccessingFunctions &&
1752 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1753 GV->getType()->getElementType()->isSingleValueType() &&
1754 GS.AccessingFunction->getName() == "main" &&
1755 GS.AccessingFunction->hasExternalLinkage() &&
1756 GV->getType()->getAddressSpace() == 0) {
1757 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1758 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1759 ->getEntryBlock().begin());
1760 Type *ElemTy = GV->getType()->getElementType();
1761 // FIXME: Pass Global's alignment when globals have alignment
1762 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1763 if (!isa<UndefValue>(GV->getInitializer()))
1764 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1765
1766 GV->replaceAllUsesWith(Alloca);
1767 GV->eraseFromParent();
1768 ++NumLocalized;
1769 return true;
1770 }
1771
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001772 // If the global is never loaded (but may be stored to), it is dead.
1773 // Delete it now.
Rafael Espindolab75fcec2013-10-17 18:18:52 +00001774 if (!GS.IsLoaded) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001775 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1776
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001777 bool Changed;
1778 if (isLeakCheckerRoot(GV)) {
1779 // Delete any constant stores to the global.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001780 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001781 } else {
1782 // Delete any stores we can find to the global. We may not be able to
1783 // make it completely dead though.
1784 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1785 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001786
1787 // If the global is dead now, delete it.
1788 if (GV->use_empty()) {
1789 GV->eraseFromParent();
1790 ++NumDeleted;
1791 Changed = true;
1792 }
1793 return Changed;
1794
Rafael Espindolab75fcec2013-10-17 18:18:52 +00001795 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00001796 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001797 GV->setConstant(true);
1798
1799 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001800 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001801
1802 // If the global is dead now, just nuke it.
1803 if (GV->use_empty()) {
1804 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1805 << "all users and delete global!\n");
1806 GV->eraseFromParent();
1807 ++NumDeleted;
1808 }
1809
1810 ++NumMarked;
1811 return true;
1812 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001813 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001814 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1815 GVI = FirstNewGV; // Don't skip the newly produced globals!
1816 return true;
1817 }
Rafael Espindolab75fcec2013-10-17 18:18:52 +00001818 } else if (GS.StoredType == GlobalStatus::StoredOnce) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001819 // If the initial value for the global was an undef value, and if only
1820 // one other value was stored into it, we can just change the
1821 // initializer to be the stored value, then delete all stores to the
1822 // global. This allows us to mark it constant.
1823 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1824 if (isa<UndefValue>(GV->getInitializer())) {
1825 // Change the initial value here.
1826 GV->setInitializer(SOVConstant);
1827
1828 // Clean up any obviously simplifiable users now.
Nick Lewycky6a577f82012-02-12 01:13:18 +00001829 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001830
1831 if (GV->use_empty()) {
1832 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewycky8899d5c2012-07-24 07:21:08 +00001833 << "simplify all users and delete global!\n");
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001834 GV->eraseFromParent();
1835 ++NumDeleted;
1836 } else {
1837 GVI = GV;
1838 }
1839 ++NumSubstitute;
1840 return true;
1841 }
1842
1843 // Try to optimize globals based on the knowledge that only one value
1844 // (besides its initializer) is ever stored to the global.
Nick Lewyckyfad4d402012-02-05 19:56:38 +00001845 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Nick Lewycky6a577f82012-02-12 01:13:18 +00001846 TD, TLI))
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001847 return true;
1848
1849 // Otherwise, if the global was not a boolean, we can shrink it to be a
1850 // boolean.
Eli Friedmanb1c54932013-09-09 22:00:13 +00001851 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1852 if (GS.Ordering == NotAtomic) {
1853 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1854 ++NumShrunkToBool;
1855 return true;
1856 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001857 }
Eli Friedmanb1c54932013-09-09 22:00:13 +00001858 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001859 }
1860
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001861 return false;
1862}
1863
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001864/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1865/// function, changing them to FastCC.
1866static void ChangeCalleesToFastCall(Function *F) {
1867 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00001868 if (isa<BlockAddress>(*UI))
1869 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00001870 CallSite User(cast<Instruction>(*UI));
1871 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001872 }
1873}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001874
Bill Wendling99faa3b2012-12-07 23:16:57 +00001875static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001876 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling8e47daf2013-01-25 23:09:36 +00001877 unsigned Index = Attrs.getSlotIndex(i);
1878 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands548448a2008-02-18 17:32:13 +00001879 continue;
1880
Duncan Sands548448a2008-02-18 17:32:13 +00001881 // There can be only one.
Bill Wendling8e47daf2013-01-25 23:09:36 +00001882 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001883 }
1884
1885 return Attrs;
1886}
1887
1888static void RemoveNestAttribute(Function *F) {
Bill Wendling5886b7b2012-10-14 06:39:53 +00001889 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001890 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadb7454fd2012-05-12 08:30:16 +00001891 if (isa<BlockAddress>(*UI))
1892 continue;
Duncan Sands548448a2008-02-18 17:32:13 +00001893 CallSite User(cast<Instruction>(*UI));
Bill Wendling5886b7b2012-10-14 06:39:53 +00001894 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001895 }
1896}
1897
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001898bool GlobalOpt::OptimizeFunctions(Module &M) {
1899 bool Changed = false;
1900 // Optimize functions.
1901 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1902 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001903 // Functions without names cannot be referenced outside this module.
1904 if (!F->hasName() && !F->isDeclaration())
1905 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001906 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00001907 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001908 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001909 Changed = true;
1910 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001911 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001912 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001913 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001914 // If this function has C calling conventions, is not a varargs
1915 // function, and is only called directly, promote it to use the Fast
1916 // calling convention.
1917 F->setCallingConv(CallingConv::Fast);
1918 ChangeCalleesToFastCall(F);
1919 ++NumFastCallFns;
1920 Changed = true;
1921 }
1922
Bill Wendling034b94b2012-12-19 07:18:57 +00001923 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001924 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001925 // The function is not used by a trampoline intrinsic, so it is safe
1926 // to remove the 'nest' attribute.
1927 RemoveNestAttribute(F);
1928 ++NumNestRemoved;
1929 Changed = true;
1930 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001931 }
1932 }
1933 return Changed;
1934}
1935
1936bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1937 bool Changed = false;
1938 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1939 GVI != E; ) {
1940 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001941 // Global variables without names cannot be referenced outside this module.
1942 if (!GV->hasName() && !GV->isDeclaration())
1943 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001944 // Simplify the initializer.
1945 if (GV->hasInitializer())
1946 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Chad Rosieraab8e282011-12-02 01:26:24 +00001947 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001948 if (New && New != CE)
1949 GV->setInitializer(New);
1950 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001951
1952 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001953 }
1954 return Changed;
1955}
1956
Nick Lewycky2c44a802011-04-08 07:30:21 +00001957/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001958/// initializers have an init priority of 65535.
1959GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001960 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1961 if (GV == 0) return 0;
Jakub Staszak582088c2012-12-06 21:57:16 +00001962
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001963 // Verify that the initializer is simple enough for us to handle. We are
1964 // only allowed to optimize the initializer if it is unique.
1965 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001966
1967 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1968 return GV;
1969 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00001970
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001971 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001972 if (isa<ConstantAggregateZero>(*i))
1973 continue;
1974 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001975 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1976 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001977
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001978 // Must have a function or null ptr.
1979 if (!isa<Function>(CS->getOperand(1)))
1980 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001981
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001982 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001983 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1984 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001985 return 0;
1986 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001987
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001988 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001989}
1990
Chris Lattnerdb973e62005-09-26 02:31:18 +00001991/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1992/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001993static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001994 if (GV->getInitializer()->isNullValue())
1995 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001996 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1997 std::vector<Function*> Result;
1998 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001999 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2000 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002001 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2002 }
2003 return Result;
2004}
2005
Chris Lattnerdb973e62005-09-26 02:31:18 +00002006/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2007/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002008static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002009 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002010 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00002011 Constant *CSVals[2];
2012 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2013 CSVals[1] = 0;
2014
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002015 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00002016 cast <StructType>(
2017 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002018
Chris Lattnerdb973e62005-09-26 02:31:18 +00002019 // Create the new init list.
2020 std::vector<Constant*> CAList;
2021 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00002022 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00002023 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00002024 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002025 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002026 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002027 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00002028 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00002029 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00002030 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00002031 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002032 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00002033 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002034
Chris Lattnerdb973e62005-09-26 02:31:18 +00002035 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002036 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00002037 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002038
Chris Lattnerdb973e62005-09-26 02:31:18 +00002039 // If we didn't change the number of elements, don't create a new GV.
2040 if (CA->getType() == GCL->getInitializer()->getType()) {
2041 GCL->setInitializer(CA);
2042 return GCL;
2043 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002044
Chris Lattnerdb973e62005-09-26 02:31:18 +00002045 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002046 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002047 GCL->getLinkage(), CA, "",
Hans Wennborgce718ff2012-06-23 11:37:03 +00002048 GCL->getThreadLocalMode());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002049 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002050 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002051
Chris Lattnerdb973e62005-09-26 02:31:18 +00002052 // Nuke the old list, replacing any uses with the new one.
2053 if (!GCL->use_empty()) {
2054 Constant *V = NGV;
2055 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002056 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002057 GCL->replaceAllUsesWith(V);
2058 }
2059 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002060
Chris Lattnerdb973e62005-09-26 02:31:18 +00002061 if (Ctors.size())
2062 return NGV;
2063 else
2064 return 0;
2065}
Chris Lattner79c11012005-09-26 04:44:35 +00002066
2067
Jakub Staszak582088c2012-12-06 21:57:16 +00002068static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002069isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002070 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002071 const DataLayout *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002072
2073
2074/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2075/// handled by the code generator. We don't want to generate something like:
2076/// void *X = &X/42;
2077/// because the code generator doesn't have a relocation that can handle that.
2078///
2079/// This function should be called if C was not found (but just got inserted)
2080/// in SimpleConstants to avoid having to rescan the same constants all the
2081/// time.
2082static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002083 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002084 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002085 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2086 // all supported.
2087 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2088 isa<GlobalValue>(C))
2089 return true;
Jakub Staszak582088c2012-12-06 21:57:16 +00002090
Chris Lattner1945d582010-12-07 04:33:29 +00002091 // Aggregate values are safe if all their elements are.
2092 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2093 isa<ConstantVector>(C)) {
2094 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2095 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002096 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002097 return false;
2098 }
2099 return true;
2100 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002101
Chris Lattner1945d582010-12-07 04:33:29 +00002102 // We don't know exactly what relocations are allowed in constant expressions,
2103 // so we allow &global+constantoffset, which is safe and uniformly supported
2104 // across targets.
2105 ConstantExpr *CE = cast<ConstantExpr>(C);
2106 switch (CE->getOpcode()) {
2107 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002108 // Bitcast is fine if the casted value is fine.
2109 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2110
Chris Lattner1945d582010-12-07 04:33:29 +00002111 case Instruction::IntToPtr:
2112 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002113 // int <=> ptr is fine if the int type is the same size as the
2114 // pointer type.
2115 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2116 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2117 return false;
2118 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002119
Chris Lattner1945d582010-12-07 04:33:29 +00002120 // GEP is fine if it is simple + constant offset.
2121 case Instruction::GetElementPtr:
2122 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2123 if (!isa<ConstantInt>(CE->getOperand(i)))
2124 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002125 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Jakub Staszak582088c2012-12-06 21:57:16 +00002126
Chris Lattner1945d582010-12-07 04:33:29 +00002127 case Instruction::Add:
2128 // We allow simple+cst.
2129 if (!isa<ConstantInt>(CE->getOperand(1)))
2130 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002131 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002132 }
2133 return false;
2134}
2135
Jakub Staszak582088c2012-12-06 21:57:16 +00002136static inline bool
Chris Lattner1945d582010-12-07 04:33:29 +00002137isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002138 SmallPtrSet<Constant*, 8> &SimpleConstants,
Micah Villmow3574eca2012-10-08 16:38:25 +00002139 const DataLayout *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002140 // If we already checked this constant, we win.
2141 if (!SimpleConstants.insert(C)) return true;
2142 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002143 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002144}
2145
2146
Chris Lattner79c11012005-09-26 04:44:35 +00002147/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002148/// enough for us to understand. In particular, if it is a cast to anything
2149/// other than from one pointer type to another pointer type, we punt.
2150/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002151/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002152static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002153 // Conservatively, avoid aggregate types. This is because we don't
2154 // want to worry about them partially overlapping other stores.
2155 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2156 return false;
2157
Dan Gohmanfd54a892009-09-07 22:31:26 +00002158 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002159 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002160 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002161 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002162
Owen Andersone95a32c2011-01-14 22:31:13 +00002163 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002164 // Handle a constantexpr gep.
2165 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002166 isa<GlobalVariable>(CE->getOperand(0)) &&
2167 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002168 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002169 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002170 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002171 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002172 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002173
Dan Gohman80bdc962009-09-07 22:44:55 +00002174 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002175 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002176 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002177
2178 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002179 // notional bounds of the corresponding static array types.
2180 if (!CE->isGEPWithNoNotionalOverIndexing())
2181 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002182
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002183 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak582088c2012-12-06 21:57:16 +00002184
Owen Andersoncff6b372011-01-14 22:19:20 +00002185 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2186 // and we know how to evaluate it by moving the bitcast from the pointer
2187 // operand to the value operand.
2188 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002189 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002190 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2191 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002192 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002193 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002194 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002195
Chris Lattner79c11012005-09-26 04:44:35 +00002196 return false;
2197}
2198
Chris Lattner798b4d52005-09-26 06:52:44 +00002199/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2200/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2201/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2202static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Shengefcdb292012-12-01 10:54:28 +00002203 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002204 // Base case of the recursion.
2205 if (OpNo == Addr->getNumOperands()) {
2206 assert(Val->getType() == Init->getType() && "Type mismatch!");
2207 return Val;
2208 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002209
Chris Lattnera78fa8c2012-01-27 03:08:05 +00002210 SmallVector<Constant*, 32> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002211 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002212 // Break up the constant into its elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002213 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2214 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002215
Chris Lattner798b4d52005-09-26 06:52:44 +00002216 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002217 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2218 unsigned Idx = CU->getZExtValue();
2219 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Shengefcdb292012-12-01 10:54:28 +00002220 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002221
Chris Lattner798b4d52005-09-26 06:52:44 +00002222 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002223 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002224 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002225
Chris Lattnerb065b062011-06-20 04:01:31 +00002226 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002227 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002228
2229 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002230 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002231 NumElts = ATy->getNumElements();
2232 else
Chris Lattnerd59ae902012-01-26 02:32:04 +00002233 NumElts = InitTy->getVectorNumElements();
Chris Lattnerb065b062011-06-20 04:01:31 +00002234
2235 // Break up the array into elements.
Chris Lattnerd59ae902012-01-26 02:32:04 +00002236 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2237 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnerb065b062011-06-20 04:01:31 +00002238
2239 assert(CI->getZExtValue() < NumElts);
2240 Elts[CI->getZExtValue()] =
Zhou Shengefcdb292012-12-01 10:54:28 +00002241 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnerb065b062011-06-20 04:01:31 +00002242
2243 if (Init->getType()->isArrayTy())
2244 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2245 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002246}
2247
Chris Lattner79c11012005-09-26 04:44:35 +00002248/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2249/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002250static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002251 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2252 assert(GV->hasInitializer());
2253 GV->setInitializer(Val);
2254 return;
2255 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002256
Chris Lattner798b4d52005-09-26 06:52:44 +00002257 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2258 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Shengefcdb292012-12-01 10:54:28 +00002259 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002260}
2261
Nick Lewycky7fa76772012-02-20 03:25:59 +00002262namespace {
2263
2264/// Evaluator - This class evaluates LLVM IR, producing the Constant
2265/// representing each SSA instruction. Changes to global variables are stored
2266/// in a mapping that can be iterated over after the evaluation is complete.
2267/// Once an evaluation call fails, the evaluation object should not be reused.
2268class Evaluator {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002269public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002270 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002271 : TD(TD), TLI(TLI) {
2272 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2273 }
2274
Nick Lewycky7fa76772012-02-20 03:25:59 +00002275 ~Evaluator() {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002276 DeleteContainerPointers(ValueStack);
2277 while (!AllocaTmps.empty()) {
2278 GlobalVariable *Tmp = AllocaTmps.back();
2279 AllocaTmps.pop_back();
2280
2281 // If there are still users of the alloca, the program is doing something
2282 // silly, e.g. storing the address of the alloca somewhere and using it
2283 // later. Since this is undefined, we'll just make it be null.
2284 if (!Tmp->use_empty())
2285 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2286 delete Tmp;
2287 }
2288 }
2289
2290 /// EvaluateFunction - Evaluate a call to function F, returning true if
2291 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2292 /// arguments for the function.
2293 bool EvaluateFunction(Function *F, Constant *&RetVal,
2294 const SmallVectorImpl<Constant*> &ActualArgs);
2295
2296 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2297 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2298 /// control flows into, or null upon return.
2299 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2300
2301 Constant *getVal(Value *V) {
2302 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2303 Constant *R = ValueStack.back()->lookup(V);
2304 assert(R && "Reference to an uncomputed value!");
2305 return R;
2306 }
2307
2308 void setVal(Value *V, Constant *C) {
2309 ValueStack.back()->operator[](V) = C;
2310 }
2311
2312 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2313 return MutatedMemory;
2314 }
2315
2316 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2317 return Invariants;
2318 }
2319
2320private:
2321 Constant *ComputeLoadResult(Constant *P);
2322
2323 /// ValueStack - As we compute SSA register values, we store their contents
2324 /// here. The back of the vector contains the current function and the stack
2325 /// contains the values in the calling frames.
2326 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2327
2328 /// CallStack - This is used to detect recursion. In pathological situations
2329 /// we could hit exponential behavior, but at least there is nothing
2330 /// unbounded.
2331 SmallVector<Function*, 4> CallStack;
2332
2333 /// MutatedMemory - For each store we execute, we update this map. Loads
2334 /// check this to get the most up-to-date value. If evaluation is successful,
2335 /// this state is committed to the process.
2336 DenseMap<Constant*, Constant*> MutatedMemory;
2337
2338 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2339 /// to represent its body. This vector is needed so we can delete the
2340 /// temporary globals when we are done.
2341 SmallVector<GlobalVariable*, 32> AllocaTmps;
2342
2343 /// Invariants - These global variables have been marked invariant by the
2344 /// static constructor.
2345 SmallPtrSet<GlobalVariable*, 8> Invariants;
2346
2347 /// SimpleConstants - These are constants we have checked and know to be
2348 /// simple enough to live in a static initializer of a global.
2349 SmallPtrSet<Constant*, 8> SimpleConstants;
2350
Micah Villmow3574eca2012-10-08 16:38:25 +00002351 const DataLayout *TD;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002352 const TargetLibraryInfo *TLI;
2353};
2354
Nick Lewycky7fa76772012-02-20 03:25:59 +00002355} // anonymous namespace
2356
Chris Lattner562a0552005-09-26 05:16:34 +00002357/// ComputeLoadResult - Return the value that would be computed by a load from
2358/// P after the stores reflected by 'memory' have been performed. If we can't
2359/// decide, return null.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002360Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002361 // If this memory location has been recently stored, use the stored value: it
2362 // is the most up-to-date.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002363 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2364 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002365
Chris Lattner04de1cf2005-09-26 05:15:37 +00002366 // Access it.
2367 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002368 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002369 return GV->getInitializer();
2370 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002371 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002372
Chris Lattner798b4d52005-09-26 06:52:44 +00002373 // Handle a constantexpr getelementptr.
2374 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2375 if (CE->getOpcode() == Instruction::GetElementPtr &&
2376 isa<GlobalVariable>(CE->getOperand(0))) {
2377 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002378 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002379 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002380 }
2381
2382 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002383}
2384
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002385/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2386/// successful, false if we can't evaluate it. NewBB returns the next BB that
2387/// control flows into, or null upon return.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002388bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2389 BasicBlock *&NextBB) {
Chris Lattner79c11012005-09-26 04:44:35 +00002390 // This is the main evaluation loop.
2391 while (1) {
2392 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002393
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002394 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2395
Chris Lattner79c11012005-09-26 04:44:35 +00002396 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002397 if (!SI->isSimple()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002398 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2399 return false; // no volatile/atomic accesses.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002400 }
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002401 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002403 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Nick Lewyckya641c072012-02-21 22:08:06 +00002404 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002405 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002406 }
2407 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002408 // If this is too complex for us to commit, reject it.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002409 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattnercd271422005-09-27 04:45:34 +00002410 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002411 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002412
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002413 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002414
2415 // If this might be too difficult for the backend to handle (e.g. the addr
2416 // of one global variable divided by another) then we can't commit it.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002417 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002418 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2419 << "\n");
Chris Lattner1945d582010-12-07 04:33:29 +00002420 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002421 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002422
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002423 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002424 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002425 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Andersoncff6b372011-01-14 22:19:20 +00002426 // If we're evaluating a store through a bitcast, then we need
2427 // to pull the bitcast off the pointer type and push it onto the
2428 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002429 Ptr = CE->getOperand(0);
Jakub Staszak582088c2012-12-06 21:57:16 +00002430
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002431 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak582088c2012-12-06 21:57:16 +00002432
Owen Anderson66f708f2011-01-16 04:33:33 +00002433 // In order to push the bitcast onto the stored value, a bitcast
2434 // from NewTy to Val's type must be legal. If it's not, we can try
2435 // introspecting NewTy to find a legal conversion.
2436 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2437 // If NewTy is a struct, we can convert the pointer to the struct
2438 // into a pointer to its first member.
2439 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002440 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002441 NewTy = STy->getTypeAtIndex(0U);
2442
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002443 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002444 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2445 Constant * const IdxList[] = {IdxZero, IdxZero};
2446
Jay Foadb4263a62011-07-22 08:52:50 +00002447 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewyckya641c072012-02-21 22:08:06 +00002448 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2449 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2450
Owen Anderson66f708f2011-01-16 04:33:33 +00002451 // If we can't improve the situation by introspecting NewTy,
2452 // we have to give up.
2453 } else {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002454 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2455 "evaluate.\n");
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002456 return false;
Owen Anderson66f708f2011-01-16 04:33:33 +00002457 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002458 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002459
Owen Anderson66f708f2011-01-16 04:33:33 +00002460 // If we found compatible types, go ahead and push the bitcast
2461 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002462 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002463
Michael Gottesmandcf66952013-01-11 23:08:52 +00002464 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Andersoncff6b372011-01-14 22:19:20 +00002465 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002466 }
Jakub Staszak582088c2012-12-06 21:57:16 +00002467
Chris Lattner79c11012005-09-26 04:44:35 +00002468 MutatedMemory[Ptr] = Val;
2469 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002470 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002471 getVal(BO->getOperand(0)),
2472 getVal(BO->getOperand(1)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002473 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002474 << "\n");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002475 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002476 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002477 getVal(CI->getOperand(0)),
2478 getVal(CI->getOperand(1)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002479 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002480 << "\n");
Chris Lattner79c11012005-09-26 04:44:35 +00002481 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002482 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002483 getVal(CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002484 CI->getType());
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002485 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002486 << "\n");
Chris Lattner79c11012005-09-26 04:44:35 +00002487 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002488 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2489 getVal(SI->getOperand(1)),
2490 getVal(SI->getOperand(2)));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002491 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002492 << "\n");
Chris Lattner04de1cf2005-09-26 05:15:37 +00002493 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002494 Constant *P = getVal(GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002495 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002496 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2497 i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002498 GEPOps.push_back(getVal(*i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002499 InstResult =
2500 ConstantExpr::getGetElementPtr(P, GEPOps,
2501 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002502 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesmandcf66952013-01-11 23:08:52 +00002503 << "\n");
Chris Lattner04de1cf2005-09-26 05:15:37 +00002504 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002505
2506 if (!LI->isSimple()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002507 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2508 return false; // no volatile/atomic accesses.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002509 }
2510
Nick Lewyckya641c072012-02-21 22:08:06 +00002511 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002512 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Nick Lewyckya641c072012-02-21 22:08:06 +00002513 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002514 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2515 "folding: " << *Ptr << "\n");
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002516 }
Nick Lewyckya641c072012-02-21 22:08:06 +00002517 InstResult = ComputeLoadResult(Ptr);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002518 if (InstResult == 0) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002519 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2520 "\n");
2521 return false; // Could not evaluate load.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002522 }
2523
2524 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattnera22fdb02005-09-26 17:07:09 +00002525 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002526 if (AI->isArrayAllocation()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002527 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2528 return false; // Cannot handle array allocs.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002529 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002530 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002531 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002532 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002533 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002534 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002535 InstResult = AllocaTmps.back();
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002536 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002537 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2538 CallSite CS(CurInst);
Devang Patel412a4462009-03-09 23:04:12 +00002539
2540 // Debug info can safely be ignored here.
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002541 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002542 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel412a4462009-03-09 23:04:12 +00002543 ++CurInst;
2544 continue;
2545 }
2546
Chris Lattner7cd580f2006-07-07 21:37:01 +00002547 // Cannot handle inline asm.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002548 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002549 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2550 return false;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002551 }
Chris Lattner7cd580f2006-07-07 21:37:01 +00002552
Nick Lewycky81266c52012-02-17 06:59:21 +00002553 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2554 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002555 if (MSI->isVolatile()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002556 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2557 "intrinsic.\n");
2558 return false;
2559 }
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002560 Constant *Ptr = getVal(MSI->getDest());
2561 Constant *Val = getVal(MSI->getValue());
2562 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky81266c52012-02-17 06:59:21 +00002563 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2564 // This memset is a no-op.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002565 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002566 ++CurInst;
2567 continue;
2568 }
2569 }
2570
2571 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2572 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002573 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002574 ++CurInst;
2575 continue;
2576 }
2577
2578 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2579 // We don't insert an entry into Values, as it doesn't have a
2580 // meaningful return value.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002581 if (!II->use_empty()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002582 DEBUG(dbgs() << "Found unused invariant_start. Cant evaluate.\n");
Nick Lewycky81266c52012-02-17 06:59:21 +00002583 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002584 }
Nick Lewycky81266c52012-02-17 06:59:21 +00002585 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky0ef05572012-02-20 23:32:26 +00002586 Value *PtrArg = getVal(II->getArgOperand(1));
2587 Value *Ptr = PtrArg->stripPointerCasts();
2588 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2589 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Nick Lewyckyb97b1622013-07-25 02:55:14 +00002590 if (TD && !Size->isAllOnesValue() &&
Nick Lewycky0ef05572012-02-20 23:32:26 +00002591 Size->getValue().getLimitedValue() >=
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002592 TD->getTypeStoreSize(ElemTy)) {
Nick Lewycky81266c52012-02-17 06:59:21 +00002593 Invariants.insert(GV);
Michael Gottesmandcf66952013-01-11 23:08:52 +00002594 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2595 << "\n");
2596 } else {
2597 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2598 "invariant.\n");
2599 }
Nick Lewycky81266c52012-02-17 06:59:21 +00002600 }
2601 // Continue even if we do nothing.
Nick Lewycky1f237b02011-05-29 18:41:56 +00002602 ++CurInst;
2603 continue;
2604 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002605
Michael Gottesmandcf66952013-01-11 23:08:52 +00002606 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewycky1f237b02011-05-29 18:41:56 +00002607 return false;
2608 }
2609
Chris Lattnercd271422005-09-27 04:45:34 +00002610 // Resolve function pointers.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002611 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002612 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002613 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002614 return false; // Cannot resolve.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002615 }
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002616
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002617 SmallVector<Constant*, 8> Formals;
Nick Lewycky132bd9c2012-02-12 05:09:35 +00002618 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002619 Formals.push_back(getVal(*i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002620
Reid Spencer5cbf9852007-01-30 20:08:39 +00002621 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002622 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002623 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002624 InstResult = C;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002625 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2626 *InstResult << "\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002627 } else {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002628 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002629 return false;
2630 }
2631 } else {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002632 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002633 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002634 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002635 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002636
Benjamin Kramer08135892013-01-12 15:34:31 +00002637 Constant *RetVal = 0;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002638 // Execute the call, if successful, use the return value.
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002639 ValueStack.push_back(new DenseMap<Value*, Constant*>);
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002640 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesmandcf66952013-01-11 23:08:52 +00002641 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002642 return false;
Michael Gottesmandcf66952013-01-11 23:08:52 +00002643 }
Benjamin Kramer3bbf2b62012-02-27 12:48:24 +00002644 delete ValueStack.pop_back_val();
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002645 InstResult = RetVal;
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002646
Michael Gottesmandcf66952013-01-11 23:08:52 +00002647 if (InstResult != NULL) {
2648 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2649 InstResult << "\n\n");
2650 } else {
2651 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2652 }
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002653 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002654 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002655 DEBUG(dbgs() << "Found a terminator instruction.\n");
2656
Chris Lattnercdf98be2005-09-26 04:57:38 +00002657 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2658 if (BI->isUnconditional()) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002659 NextBB = BI->getSuccessor(0);
Chris Lattnercdf98be2005-09-26 04:57:38 +00002660 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002661 ConstantInt *Cond =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002662 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002663 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002664
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002665 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002666 }
2667 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2668 ConstantInt *Val =
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002669 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002670 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002671 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002672 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002673 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002674 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002675 NextBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002676 else
2677 return false; // Cannot determine.
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002678 } else if (isa<ReturnInst>(CurInst)) {
2679 NextBB = 0;
Chris Lattnercdf98be2005-09-26 04:57:38 +00002680 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002681 // invoke, unwind, resume, unreachable.
Michael Gottesmandcf66952013-01-11 23:08:52 +00002682 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattnercd271422005-09-27 04:45:34 +00002683 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002684 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002685
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002686 // We succeeded at evaluating this block!
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002687 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002688 return true;
Chris Lattner79c11012005-09-26 04:44:35 +00002689 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002690 // Did not know how to evaluate this!
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002691 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesmandcf66952013-01-11 23:08:52 +00002692 "\n");
Chris Lattnercd271422005-09-27 04:45:34 +00002693 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002694 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002695
Chris Lattner1945d582010-12-07 04:33:29 +00002696 if (!CurInst->use_empty()) {
2697 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002698 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Jakub Staszak582088c2012-12-06 21:57:16 +00002699
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002700 setVal(CurInst, InstResult);
Chris Lattner1945d582010-12-07 04:33:29 +00002701 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002702
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002703 // If we just processed an invoke, we finished evaluating the block.
2704 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2705 NextBB = II->getNormalDest();
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002706 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmanf1ce79f2012-03-13 18:01:37 +00002707 return true;
2708 }
2709
Chris Lattner79c11012005-09-26 04:44:35 +00002710 // Advance program counter.
2711 ++CurInst;
2712 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002713}
2714
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002715/// EvaluateFunction - Evaluate a call to function F, returning true if
2716/// successful, false if we can't evaluate it. ActualArgs contains the formal
2717/// arguments for the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002718bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2719 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002720 // Check to see if this function is already executing (recursion). If so,
2721 // bail out. TODO: we might want to accept limited recursion.
2722 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2723 return false;
2724
2725 CallStack.push_back(F);
2726
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002727 // Initialize arguments to the incoming values specified.
2728 unsigned ArgNo = 0;
2729 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2730 ++AI, ++ArgNo)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002731 setVal(AI, ActualArgs[ArgNo]);
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002732
2733 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2734 // we can only evaluate any one basic block at most once. This set keeps
2735 // track of what we have executed so we can detect recursive cases etc.
2736 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2737
2738 // CurBB - The current basic block we're evaluating.
2739 BasicBlock *CurBB = F->begin();
2740
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002741 BasicBlock::iterator CurInst = CurBB->begin();
2742
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002743 while (1) {
Duncan Sands4b794f82012-02-23 08:23:06 +00002744 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002745 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2746
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002747 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002748 return false;
2749
2750 if (NextBB == 0) {
2751 // Successfully running until there's no next block means that we found
2752 // the return. Fill it the return value and pop the call stack.
2753 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2754 if (RI->getNumOperands())
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002755 RetVal = getVal(RI->getOperand(0));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002756 CallStack.pop_back();
2757 return true;
2758 }
2759
2760 // Okay, we succeeded in evaluating this control flow. See if we have
2761 // executed the new block before. If so, we have a looping function,
2762 // which we cannot evaluate in reasonable time.
2763 if (!ExecutedBlocks.insert(NextBB))
2764 return false; // looped!
2765
2766 // Okay, we have never been in this block before. Check to see if there
2767 // are any PHI nodes. If so, evaluate them with information about where
2768 // we came from.
2769 PHINode *PN = 0;
Nick Lewycky8e4ba6b2012-02-12 00:47:24 +00002770 for (CurInst = NextBB->begin();
2771 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002772 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewyckyda82fd42012-02-06 08:24:44 +00002773
2774 // Advance to the next block.
2775 CurBB = NextBB;
2776 }
2777}
2778
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002779/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2780/// we can. Return true if we can, false otherwise.
Micah Villmow3574eca2012-10-08 16:38:25 +00002781static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
Chad Rosier00737bd2011-12-01 21:29:16 +00002782 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002783 // Call the function.
Nick Lewycky7fa76772012-02-20 03:25:59 +00002784 Evaluator Eval(TD, TLI);
Chris Lattnercd271422005-09-27 04:45:34 +00002785 Constant *RetValDummy;
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002786 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2787 SmallVector<Constant*, 0>());
Jakub Staszak582088c2012-12-06 21:57:16 +00002788
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002789 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002790 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002791 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002792 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002793 << " stores.\n");
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002794 for (DenseMap<Constant*, Constant*>::const_iterator I =
2795 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewycky3eab3c42012-06-24 04:07:14 +00002796 I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002797 CommitValueTo(I->second, I->first);
Nick Lewycky23ec5d72012-02-19 23:26:27 +00002798 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2799 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2800 I != E; ++I)
Nick Lewycky81266c52012-02-17 06:59:21 +00002801 (*I)->setConstant(true);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002802 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002803
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002804 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002805}
2806
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002807/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2808/// Return true if anything changed.
2809bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2810 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2811 bool MadeChange = false;
2812 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002813
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002814 // Loop over global ctors, optimizing them when we can.
2815 for (unsigned i = 0; i != Ctors.size(); ++i) {
2816 Function *F = Ctors[i];
2817 // Found a null terminator in the middle of the list, prune off the rest of
2818 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002819 if (F == 0) {
2820 if (i != Ctors.size()-1) {
2821 Ctors.resize(i+1);
2822 MadeChange = true;
2823 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002824 break;
2825 }
Michael Gottesmancddd8a62013-01-11 20:07:53 +00002826 DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002827
Chris Lattner79c11012005-09-26 04:44:35 +00002828 // We cannot simplify external ctor functions.
2829 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002830
Chris Lattner79c11012005-09-26 04:44:35 +00002831 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002832 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002833 Ctors.erase(Ctors.begin()+i);
2834 MadeChange = true;
2835 --i;
2836 ++NumCtorsEvaluated;
2837 continue;
2838 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002839 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002840
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002841 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002842
Chris Lattner7b550cc2009-11-06 04:27:31 +00002843 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002844 return true;
2845}
2846
Benjamin Kramer0d293e42013-09-22 14:09:50 +00002847static int compareNames(Constant *const *A, Constant *const *B) {
2848 return (*A)->getName().compare((*B)->getName());
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002849}
Rafael Espindola95f88532013-05-09 17:22:59 +00002850
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002851static void setUsedInitializer(GlobalVariable &V,
2852 SmallPtrSet<GlobalValue *, 8> Init) {
Rafael Espindola64f2f912013-07-20 23:33:15 +00002853 if (Init.empty()) {
2854 V.eraseFromParent();
2855 return;
2856 }
2857
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002858 SmallVector<llvm::Constant *, 8> UsedArray;
2859 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext());
Rafael Espindola95f88532013-05-09 17:22:59 +00002860
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002861 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Init.begin(), E = Init.end();
2862 I != E; ++I) {
2863 Constant *Cast = llvm::ConstantExpr::getBitCast(*I, Int8PtrTy);
2864 UsedArray.push_back(Cast);
Rafael Espindola95f88532013-05-09 17:22:59 +00002865 }
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002866 // Sort to get deterministic order.
2867 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
2868 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola95f88532013-05-09 17:22:59 +00002869
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002870 Module *M = V.getParent();
2871 V.removeFromParent();
2872 GlobalVariable *NV =
2873 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2874 llvm::ConstantArray::get(ATy, UsedArray), "");
2875 NV->takeName(&V);
2876 NV->setSection("llvm.metadata");
2877 delete &V;
Rafael Espindola95f88532013-05-09 17:22:59 +00002878}
2879
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002880namespace {
Rafael Espindola70968312013-07-19 18:44:51 +00002881/// \brief An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002882class LLVMUsed {
2883 SmallPtrSet<GlobalValue *, 8> Used;
2884 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2885 GlobalVariable *UsedV;
2886 GlobalVariable *CompilerUsedV;
2887
2888public:
Rafael Espindola2d680822013-07-25 02:50:08 +00002889 LLVMUsed(Module &M) {
Rafael Espindola4ef7eaf2013-07-25 03:23:25 +00002890 UsedV = collectUsedGlobalVariables(M, Used, false);
2891 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola95f88532013-05-09 17:22:59 +00002892 }
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002893 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
2894 iterator usedBegin() { return Used.begin(); }
2895 iterator usedEnd() { return Used.end(); }
2896 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2897 iterator compilerUsedEnd() { return CompilerUsed.end(); }
2898 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2899 bool compilerUsedCount(GlobalValue *GV) const {
2900 return CompilerUsed.count(GV);
2901 }
2902 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2903 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2904 bool usedInsert(GlobalValue *GV) { return Used.insert(GV); }
2905 bool compilerUsedInsert(GlobalValue *GV) { return CompilerUsed.insert(GV); }
Rafael Espindola95f88532013-05-09 17:22:59 +00002906
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002907 void syncVariablesAndSets() {
2908 if (UsedV)
2909 setUsedInitializer(*UsedV, Used);
2910 if (CompilerUsedV)
2911 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2912 }
2913};
Rafael Espindola95f88532013-05-09 17:22:59 +00002914}
2915
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002916static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2917 if (GA.use_empty()) // No use at all.
2918 return false;
2919
2920 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2921 "We should have removed the duplicated "
Rafael Espindola70968312013-07-19 18:44:51 +00002922 "element from llvm.compiler.used");
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002923 if (!GA.hasOneUse())
2924 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola70968312013-07-19 18:44:51 +00002925 // llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002926 return true;
2927
Rafael Espindola70968312013-07-19 18:44:51 +00002928 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002929 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola95f88532013-05-09 17:22:59 +00002930}
2931
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002932static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2933 const LLVMUsed &U) {
2934 unsigned N = 2;
2935 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2936 "We should have removed the duplicated "
Rafael Espindola70968312013-07-19 18:44:51 +00002937 "element from llvm.compiler.used");
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002938 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2939 ++N;
2940 return V.hasNUsesOrMore(N);
2941}
2942
2943static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2944 if (!GA.hasLocalLinkage())
2945 return true;
2946
2947 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2948}
2949
2950static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget) {
2951 RenameTarget = false;
Rafael Espindola95f88532013-05-09 17:22:59 +00002952 bool Ret = false;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002953 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola95f88532013-05-09 17:22:59 +00002954 Ret = true;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002955
2956 // If the alias is externally visible, we may still be able to simplify it.
2957 if (!mayHaveOtherReferences(GA, U))
2958 return Ret;
2959
2960 // If the aliasee has internal linkage, give it the name and linkage
2961 // of the alias, and delete the alias. This turns:
2962 // define internal ... @f(...)
2963 // @a = alias ... @f
2964 // into:
2965 // define ... @a(...)
2966 Constant *Aliasee = GA.getAliasee();
2967 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2968 if (!Target->hasLocalLinkage())
2969 return Ret;
2970
2971 // Do not perform the transform if multiple aliases potentially target the
2972 // aliasee. This check also ensures that it is safe to replace the section
2973 // and other attributes of the aliasee with those of the alias.
2974 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2975 return Ret;
2976
2977 RenameTarget = true;
2978 return true;
Rafael Espindola95f88532013-05-09 17:22:59 +00002979}
2980
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002981bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002982 bool Changed = false;
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00002983 LLVMUsed Used(M);
2984
2985 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.usedBegin(),
2986 E = Used.usedEnd();
2987 I != E; ++I)
2988 Used.compilerUsedErase(*I);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002989
Duncan Sands177d84e2009-01-07 20:01:06 +00002990 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002991 I != E;) {
2992 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002993 // Aliases without names cannot be referenced outside this module.
2994 if (!J->hasName() && !J->isDeclaration())
2995 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002996 // If the aliasee may change at link time, nothing can be done - bail out.
2997 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002998 continue;
2999
Duncan Sands4782b302009-02-15 09:56:08 +00003000 Constant *Aliasee = J->getAliasee();
3001 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00003002 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00003003
3004 // Make all users of the alias use the aliasee instead.
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003005 bool RenameTarget;
3006 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola95f88532013-05-09 17:22:59 +00003007 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00003008
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003009 J->replaceAllUsesWith(Aliasee);
3010 ++NumAliasesResolved;
3011 Changed = true;
Duncan Sands4782b302009-02-15 09:56:08 +00003012
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003013 if (RenameTarget) {
Duncan Sands7a154cf2009-12-08 10:10:20 +00003014 // Give the aliasee the name, linkage and other attributes of the alias.
3015 Target->takeName(J);
3016 Target->setLinkage(J->getLinkage());
3017 Target->GlobalValue::copyAttributesFrom(J);
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003018
3019 if (Used.usedErase(J))
3020 Used.usedInsert(Target);
3021
3022 if (Used.compilerUsedErase(J))
3023 Used.compilerUsedInsert(Target);
Rafael Espindola100fbdd2013-06-12 16:45:47 +00003024 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003025 continue;
3026
Duncan Sands4782b302009-02-15 09:56:08 +00003027 // Delete the alias.
3028 M.getAliasList().erase(J);
3029 ++NumAliasesRemoved;
3030 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003031 }
3032
Rafael Espindolad1b6ca22013-06-11 17:48:06 +00003033 Used.syncVariablesAndSets();
3034
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003035 return Changed;
3036}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003037
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003038static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3039 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewycky6f160d32012-02-12 02:17:18 +00003040 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003041
3042 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak582088c2012-12-06 21:57:16 +00003043
Anders Carlssona201c4c2011-03-20 17:59:11 +00003044 if (!Fn)
3045 return 0;
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003046
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003047 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak582088c2012-12-06 21:57:16 +00003048
3049 // Checking that the function has the right return type, the right number of
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003050 // parameters and that they all have pointer types should be enough.
3051 if (!FTy->getReturnType()->isIntegerTy() ||
3052 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00003053 !FTy->getParamType(0)->isPointerTy() ||
3054 !FTy->getParamType(1)->isPointerTy() ||
3055 !FTy->getParamType(2)->isPointerTy())
3056 return 0;
3057
3058 return Fn;
3059}
3060
3061/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3062/// destructor and can therefore be eliminated.
3063/// Note that we assume that other optimization passes have already simplified
3064/// the code so we only look for a function with a single basic block, where
Benjamin Kramerc1322a12012-02-09 16:28:15 +00003065/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3066/// other side-effect free instructions.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003067static bool cxxDtorIsEmpty(const Function &Fn,
3068 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003069 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003070 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003071 if (Fn.isDeclaration())
3072 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00003073
3074 if (++Fn.begin() != Fn.end())
3075 return false;
3076
3077 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3078 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3079 I != E; ++I) {
3080 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00003081 // Ignore debug intrinsics.
3082 if (isa<DbgInfoIntrinsic>(CI))
3083 continue;
3084
Anders Carlssona201c4c2011-03-20 17:59:11 +00003085 const Function *CalledFn = CI->getCalledFunction();
3086
3087 if (!CalledFn)
3088 return false;
3089
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003090 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3091
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003092 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003093 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003094 return false;
3095
Anders Carlsson807bc2a2011-03-22 03:21:01 +00003096 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003097 return false;
3098 } else if (isa<ReturnInst>(*I))
Benjamin Kramerd4692742012-02-09 14:26:06 +00003099 return true; // We're done.
3100 else if (I->mayHaveSideEffects())
3101 return false; // Destructor with side effects, bail.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003102 }
3103
3104 return false;
3105}
3106
3107bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3108 /// Itanium C++ ABI p3.3.5:
3109 ///
3110 /// After constructing a global (or local static) object, that will require
3111 /// destruction on exit, a termination function is registered as follows:
3112 ///
3113 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3114 ///
3115 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3116 /// call f(p) when DSO d is unloaded, before all such termination calls
3117 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00003118 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00003119
3120 // This pass will look for calls to __cxa_atexit where the function is trivial
3121 // and remove them.
3122 bool Changed = false;
3123
Jakub Staszak582088c2012-12-06 21:57:16 +00003124 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
Anders Carlssona201c4c2011-03-20 17:59:11 +00003125 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003126 // We're only interested in calls. Theoretically, we could handle invoke
3127 // instructions as well, but neither llvm-gcc nor clang generate invokes
3128 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003129 CallInst *CI = dyn_cast<CallInst>(*I++);
3130 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00003131 continue;
3132
Jakub Staszak582088c2012-12-06 21:57:16 +00003133 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00003134 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00003135 if (!DtorFn)
3136 continue;
3137
Anders Carlsson372ec6a2011-03-20 20:16:43 +00003138 SmallPtrSet<const Function *, 8> CalledFunctions;
3139 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00003140 continue;
3141
3142 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00003143 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3144 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00003145
Anders Carlssona201c4c2011-03-20 17:59:11 +00003146 ++NumCXXDtorsRemoved;
3147
3148 Changed |= true;
3149 }
3150
3151 return Changed;
3152}
3153
Chris Lattner7a90b682004-10-07 04:16:33 +00003154bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00003155 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003156
Micah Villmow3574eca2012-10-08 16:38:25 +00003157 TD = getAnalysisIfAvailable<DataLayout>();
Nick Lewycky6a7df9a2012-02-12 02:15:20 +00003158 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewycky6a577f82012-02-12 01:13:18 +00003159
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003160 // Try to find the llvm.globalctors list.
3161 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00003162
Chris Lattner7a90b682004-10-07 04:16:33 +00003163 bool LocalChange = true;
3164 while (LocalChange) {
3165 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003166
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003167 // Delete functions that are trivially dead, ccc -> fastcc
3168 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003169
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003170 // Optimize global_ctors list.
3171 if (GlobalCtors)
3172 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003173
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003174 // Optimize non-address-taken globals.
3175 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003176
3177 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00003178 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003179
Manman Ren51502702013-05-14 21:52:44 +00003180 // Try to remove trivial global destructors if they are not removed
3181 // already.
3182 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssona201c4c2011-03-20 17:59:11 +00003183 if (CXAAtExitFn)
3184 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3185
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00003186 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00003187 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003188
Chris Lattnerb1ab4582005-09-26 01:43:45 +00003189 // TODO: Move all global ctors functions to the end of the module for code
3190 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00003191
Chris Lattner079236d2004-02-25 21:34:36 +00003192 return Changed;
3193}