blob: 7b9015b2d7d4fa03de6fd57e582f9e06467f908c [file] [log] [blame]
Chris Lattner25db5802004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner25db5802004-10-07 04:16:33 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner25db5802004-10-07 04:16:33 +00008//===----------------------------------------------------------------------===//
9//
10// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "globalopt"
17#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/ConstantFolding.h"
24#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Operator.h"
Chris Lattner25db5802004-10-07 04:16:33 +000033#include "llvm/Pass.h"
Duncan Sands85fab3a2008-02-18 17:32:13 +000034#include "llvm/Support/CallSite.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000035#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000036#include "llvm/Support/ErrorHandling.h"
Chris Lattner26fe7eb2008-01-14 02:09:12 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner67ca6f632008-04-26 07:40:11 +000038#include "llvm/Support/MathExtras.h"
Hal Finkelf59fd7d2013-12-12 20:45:24 +000039#include "llvm/Support/ValueHandle.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000040#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include "llvm/Target/TargetLibraryInfo.h"
Rafael Espindola3d7fc252013-10-21 17:14:55 +000042#include "llvm/Transforms/Utils/GlobalStatus.h"
Rafael Espindola17600e22013-07-25 03:23:25 +000043#include "llvm/Transforms/Utils/ModuleUtils.h"
Chris Lattner25db5802004-10-07 04:16:33 +000044#include <algorithm>
45using namespace llvm;
46
Chris Lattner1631bcb2006-12-19 22:09:18 +000047STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolafc355bc2011-01-19 16:32:21 +000048STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner1631bcb2006-12-19 22:09:18 +000049STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
50STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
51STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
52STATISTIC(NumDeleted , "Number of globals deleted");
53STATISTIC(NumFnDeleted , "Number of functions deleted");
54STATISTIC(NumGlobUses , "Number of global uses devirtualized");
Alexey Samsonova1944e62013-10-07 19:03:24 +000055STATISTIC(NumLocalized , "Number of globals localized");
Chris Lattner1631bcb2006-12-19 22:09:18 +000056STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
57STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
58STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands573b3f82008-02-16 20:56:04 +000059STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sandsb3f27882009-02-15 09:56:08 +000060STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
61STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssonee6bc702011-03-20 17:59:11 +000062STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner25db5802004-10-07 04:16:33 +000063
Chris Lattner1631bcb2006-12-19 22:09:18 +000064namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000065 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000066 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosiere6de63d2011-12-01 21:29:16 +000067 AU.addRequired<TargetLibraryInfo>();
Chris Lattner004e2502004-10-11 05:54:41 +000068 }
Nick Lewyckye7da2d62007-05-06 13:37:16 +000069 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000070 GlobalOpt() : ModulePass(ID) {
71 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
72 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000073
Chris Lattner25db5802004-10-07 04:16:33 +000074 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000075
76 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000077 GlobalVariable *FindGlobalCtors(Module &M);
78 bool OptimizeFunctions(Module &M);
79 bool OptimizeGlobalVars(Module &M);
Duncan Sandsed722832009-03-06 10:21:56 +000080 bool OptimizeGlobalAliases(Module &M);
Chris Lattner41b6a5a2005-09-26 01:43:45 +000081 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolafc355bc2011-01-19 16:32:21 +000082 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
83 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +000084 const GlobalStatus &GS);
Anders Carlssonee6bc702011-03-20 17:59:11 +000085 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Nick Lewyckycf6aae62012-02-12 01:13:18 +000086
Rafael Espindolaaeff8a92014-02-24 23:12:18 +000087 const DataLayout *DL;
Nick Lewyckycf6aae62012-02-12 01:13:18 +000088 TargetLibraryInfo *TLI;
Chris Lattner25db5802004-10-07 04:16:33 +000089 };
Chris Lattner25db5802004-10-07 04:16:33 +000090}
91
Dan Gohmand78c4002008-05-13 00:00:25 +000092char GlobalOpt::ID = 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +000093INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
94 "Global Variable Optimizer", false, false)
95INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
96INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersondf7a4f22010-10-07 22:25:06 +000097 "Global Variable Optimizer", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000098
Chris Lattner25db5802004-10-07 04:16:33 +000099ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
100
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000101/// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
102/// as a root? If so, we might not really want to eliminate the stores to it.
103static bool isLeakCheckerRoot(GlobalVariable *GV) {
104 // A global variable is a root if it is a pointer, or could plausibly contain
105 // a pointer. There are two challenges; one is that we could have a struct
106 // the has an inner member which is a pointer. We recurse through the type to
107 // detect these (up to a point). The other is that we may actually be a union
108 // of a pointer and another type, and so our LLVM type is an integer which
109 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
110 // potentially contained here.
111
112 if (GV->hasPrivateLinkage())
113 return false;
114
115 SmallVector<Type *, 4> Types;
116 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
117
118 unsigned Limit = 20;
119 do {
120 Type *Ty = Types.pop_back_val();
121 switch (Ty->getTypeID()) {
122 default: break;
123 case Type::PointerTyID: return true;
124 case Type::ArrayTyID:
125 case Type::VectorTyID: {
126 SequentialType *STy = cast<SequentialType>(Ty);
127 Types.push_back(STy->getElementType());
128 break;
129 }
130 case Type::StructTyID: {
131 StructType *STy = cast<StructType>(Ty);
132 if (STy->isOpaque()) return true;
133 for (StructType::element_iterator I = STy->element_begin(),
134 E = STy->element_end(); I != E; ++I) {
135 Type *InnerTy = *I;
136 if (isa<PointerType>(InnerTy)) return true;
137 if (isa<CompositeType>(InnerTy))
138 Types.push_back(InnerTy);
139 }
140 break;
141 }
142 }
143 if (--Limit == 0) return true;
144 } while (!Types.empty());
145 return false;
146}
147
148/// Given a value that is stored to a global but never read, determine whether
149/// it's safe to remove the store and the chain of computation that feeds the
150/// store.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000151static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000152 do {
153 if (isa<Constant>(V))
154 return true;
155 if (!V->hasOneUse())
156 return false;
Nick Lewycky7d0f1102012-07-25 21:19:40 +0000157 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
158 isa<GlobalValue>(V))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000159 return false;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000160 if (isAllocationFn(V, TLI))
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000161 return true;
162
163 Instruction *I = cast<Instruction>(V);
164 if (I->mayHaveSideEffects())
165 return false;
166 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
167 if (!GEP->hasAllConstantIndices())
168 return false;
169 } else if (I->getNumOperands() != 1) {
170 return false;
171 }
172
173 V = I->getOperand(0);
174 } while (1);
175}
176
177/// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
178/// of the global and clean up any that obviously don't assign the global a
179/// value that isn't dynamically allocated.
180///
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000181static bool CleanupPointerRootUsers(GlobalVariable *GV,
182 const TargetLibraryInfo *TLI) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000183 // A brief explanation of leak checkers. The goal is to find bugs where
184 // pointers are forgotten, causing an accumulating growth in memory
185 // usage over time. The common strategy for leak checkers is to whitelist the
186 // memory pointed to by globals at exit. This is popular because it also
187 // solves another problem where the main thread of a C++ program may shut down
188 // before other threads that are still expecting to use those globals. To
189 // handle that case, we expect the program may create a singleton and never
190 // destroy it.
191
192 bool Changed = false;
193
194 // If Dead[n].first is the only use of a malloc result, we can delete its
195 // chain of computation and the store to the global in Dead[n].second.
196 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
197
198 // Constants can't be pointers to dynamically allocated memory.
199 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
200 UI != E;) {
201 User *U = *UI++;
202 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
203 Value *V = SI->getValueOperand();
204 if (isa<Constant>(V)) {
205 Changed = true;
206 SI->eraseFromParent();
207 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
208 if (I->hasOneUse())
209 Dead.push_back(std::make_pair(I, SI));
210 }
211 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
212 if (isa<Constant>(MSI->getValue())) {
213 Changed = true;
214 MSI->eraseFromParent();
215 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
216 if (I->hasOneUse())
217 Dead.push_back(std::make_pair(I, MSI));
218 }
219 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
220 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
221 if (MemSrc && MemSrc->isConstant()) {
222 Changed = true;
223 MTI->eraseFromParent();
224 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
225 if (I->hasOneUse())
226 Dead.push_back(std::make_pair(I, MTI));
227 }
228 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
229 if (CE->use_empty()) {
230 CE->destroyConstant();
231 Changed = true;
232 }
233 } else if (Constant *C = dyn_cast<Constant>(U)) {
Rafael Espindola27797ba2013-10-17 18:06:32 +0000234 if (isSafeToDestroyConstant(C)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000235 C->destroyConstant();
236 // This could have invalidated UI, start over from scratch.
237 Dead.clear();
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000238 CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000239 return true;
240 }
241 }
242 }
243
244 for (int i = 0, e = Dead.size(); i != e; ++i) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000245 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000246 Dead[i].second->eraseFromParent();
247 Instruction *I = Dead[i].first;
248 do {
Michael Gottesman2a654272013-01-11 23:08:52 +0000249 if (isAllocationFn(I, TLI))
250 break;
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000251 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
252 if (!J)
253 break;
254 I->eraseFromParent();
255 I = J;
Nick Lewycky38be9312012-07-24 21:33:00 +0000256 } while (1);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000257 I->eraseFromParent();
258 }
259 }
260
261 return Changed;
262}
263
Chris Lattner25db5802004-10-07 04:16:33 +0000264/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
265/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000266/// quick scan over the use list to clean up the easy and obvious cruft. This
267/// returns true if it made a change.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000268static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000269 const DataLayout *DL,
270 TargetLibraryInfo *TLI) {
Chris Lattnercb9f1522004-10-10 16:43:46 +0000271 bool Changed = false;
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000272 // Note that we need to use a weak value handle for the worklist items. When
273 // we delete a constant array, we may also be holding pointer to one of its
274 // elements (or an element of one of its elements if we're dealing with an
275 // array of arrays) in the worklist.
276 SmallVector<WeakVH, 8> WorkList(V->use_begin(), V->use_end());
Bill Wendling88d06c32013-04-02 08:16:45 +0000277 while (!WorkList.empty()) {
Hal Finkelf59fd7d2013-12-12 20:45:24 +0000278 Value *UV = WorkList.pop_back_val();
279 if (!UV)
280 continue;
281
282 User *U = cast<User>(UV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000283
Chris Lattner25db5802004-10-07 04:16:33 +0000284 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000285 if (Init) {
286 // Replace the load with the initializer.
287 LI->replaceAllUsesWith(Init);
288 LI->eraseFromParent();
289 Changed = true;
290 }
Chris Lattner25db5802004-10-07 04:16:33 +0000291 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
292 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000293 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000294 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000295 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
296 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner46d9ff082005-09-26 07:34:35 +0000297 Constant *SubInit = 0;
298 if (Init)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000299 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000300 Changed |= CleanupConstantGlobalUsers(CE, SubInit, DL, TLI);
Matt Arsenault461c8e02014-01-02 20:01:43 +0000301 } else if ((CE->getOpcode() == Instruction::BitCast &&
302 CE->getType()->isPointerTy()) ||
303 CE->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000304 // Pointer cast, delete any stores and memsets to the global.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000305 Changed |= CleanupConstantGlobalUsers(CE, 0, DL, TLI);
Chris Lattner7561ca12005-02-27 18:58:52 +0000306 }
307
308 if (CE->use_empty()) {
309 CE->destroyConstant();
310 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000311 }
312 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000313 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
314 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
315 // and will invalidate our notion of what Init is.
Chris Lattner68f04fa2007-11-13 21:46:23 +0000316 Constant *SubInit = 0;
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000317 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000318 ConstantExpr *CE =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000319 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, DL, TLI));
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000320 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmane525d9d2009-10-05 16:36:26 +0000321 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Benjamin Krameraa9e4a52012-03-28 14:50:09 +0000322
323 // If the initializer is an all-null value and we have an inbounds GEP,
324 // we already know what the result of any load from that GEP is.
325 // TODO: Handle splats.
326 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
327 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
Chris Lattnerf9c0fd72007-11-09 17:33:02 +0000328 }
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000329 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, DL, TLI);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000330
Chris Lattnercb9f1522004-10-10 16:43:46 +0000331 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000332 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000333 Changed = true;
334 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000335 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
336 if (MI->getRawDest() == V) {
337 MI->eraseFromParent();
338 Changed = true;
339 }
340
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000341 } else if (Constant *C = dyn_cast<Constant>(U)) {
342 // If we have a chain of dead constantexprs or other things dangling from
343 // us, and if they are all dead, nuke them without remorse.
Rafael Espindola27797ba2013-10-17 18:06:32 +0000344 if (isSafeToDestroyConstant(C)) {
Devang Pateld926aaa2009-03-06 01:37:41 +0000345 C->destroyConstant();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000346 CleanupConstantGlobalUsers(V, Init, DL, TLI);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000347 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000348 }
Chris Lattner25db5802004-10-07 04:16:33 +0000349 }
350 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000351 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000352}
353
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000354/// isSafeSROAElementUse - Return true if the specified instruction is a safe
355/// user of a derived expression from a global that we want to SROA.
356static bool isSafeSROAElementUse(Value *V) {
357 // We might have a dead and dangling constant hanging off of here.
358 if (Constant *C = dyn_cast<Constant>(V))
Rafael Espindola27797ba2013-10-17 18:06:32 +0000359 return isSafeToDestroyConstant(C);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000360
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000361 Instruction *I = dyn_cast<Instruction>(V);
362 if (!I) return false;
363
364 // Loads are ok.
365 if (isa<LoadInst>(I)) return true;
366
367 // Stores *to* the pointer are ok.
368 if (StoreInst *SI = dyn_cast<StoreInst>(I))
369 return SI->getOperand(0) != V;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000370
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000371 // Otherwise, it must be a GEP.
372 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
373 if (GEPI == 0) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000374
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000375 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
376 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
377 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000378
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000379 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
380 I != E; ++I)
381 if (!isSafeSROAElementUse(*I))
382 return false;
Chris Lattnerab053722008-01-14 01:31:05 +0000383 return true;
384}
385
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000386
387/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
388/// Look at it and its uses and decide whether it is safe to SROA this global.
389///
390static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
391 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000392 if (!isa<GetElementPtrInst>(U) &&
393 (!isa<ConstantExpr>(U) ||
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000394 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
395 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000396
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000397 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
398 // don't like < 3 operand CE's, and we don't like non-constant integer
399 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
400 // value of C.
401 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
402 !cast<Constant>(U->getOperand(1))->isNullValue() ||
403 !isa<ConstantInt>(U->getOperand(2)))
404 return false;
405
406 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
407 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000408
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000409 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattner229907c2011-07-18 04:54:35 +0000410 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000411 uint64_t NumElements = AT->getNumElements();
412 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000413
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000414 // Check to make sure that index falls within the array. If not,
415 // something funny is going on, so we won't do the optimization.
416 //
417 if (Idx->getZExtValue() >= NumElements)
418 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000419
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000420 // We cannot scalar repl this level of the array unless any array
421 // sub-indices are in-range constants. In particular, consider:
422 // A[0][i]. We cannot know that the user isn't doing invalid things like
423 // allowing i to index an out-of-range subscript that accesses A[1].
424 //
425 // Scalar replacing *just* the outer index of the array is probably not
426 // going to be a win anyway, so just give up.
427 for (++GEPI; // Skip array index.
Dan Gohman82ac81b2009-08-18 14:58:19 +0000428 GEPI != E;
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000429 ++GEPI) {
430 uint64_t NumElements;
Chris Lattner229907c2011-07-18 04:54:35 +0000431 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000432 NumElements = SubArrayTy->getNumElements();
Chris Lattner229907c2011-07-18 04:54:35 +0000433 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman82ac81b2009-08-18 14:58:19 +0000434 NumElements = SubVectorTy->getNumElements();
435 else {
Duncan Sands19d0b472010-02-16 11:11:14 +0000436 assert((*GEPI)->isStructTy() &&
Dan Gohman82ac81b2009-08-18 14:58:19 +0000437 "Indexed GEP type is not array, vector, or struct!");
438 continue;
439 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000440
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000441 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
442 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
443 return false;
444 }
445 }
446
447 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
448 if (!isSafeSROAElementUse(*I))
449 return false;
450 return true;
451}
452
453/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
454/// is safe for us to perform this transformation.
455///
456static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
457 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
458 UI != E; ++UI) {
459 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
460 return false;
461 }
462 return true;
463}
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000464
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000465
Chris Lattnerabab0712004-10-08 17:32:09 +0000466/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
467/// variable. This opens the door for other optimizations by exposing the
468/// behavior of the program in a more fine-grained way. We have determined that
469/// this transformation is safe already. We return the first global variable we
470/// insert so that the caller can reprocess it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000471static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) {
Chris Lattnerab053722008-01-14 01:31:05 +0000472 // Make sure this global only has simple uses that we can SRA.
Chris Lattner26fe7eb2008-01-14 02:09:12 +0000473 if (!GlobalUsersSafeToSRA(GV))
Chris Lattnerab053722008-01-14 01:31:05 +0000474 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000475
Rafael Espindola6de96a12009-01-15 20:18:42 +0000476 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattnerabab0712004-10-08 17:32:09 +0000477 Constant *Init = GV->getInitializer();
Chris Lattner229907c2011-07-18 04:54:35 +0000478 Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000479
Chris Lattnerabab0712004-10-08 17:32:09 +0000480 std::vector<GlobalVariable*> NewGlobals;
481 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
482
Chris Lattner67ca6f632008-04-26 07:40:11 +0000483 // Get the alignment of the global, either explicit or target-specific.
484 unsigned StartAlignment = GV->getAlignment();
485 if (StartAlignment == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000486 StartAlignment = DL.getABITypeAlignment(GV->getType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000487
Chris Lattner229907c2011-07-18 04:54:35 +0000488 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000489 NewGlobals.reserve(STy->getNumElements());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000490 const StructLayout &Layout = *DL.getStructLayout(STy);
Chris Lattnerabab0712004-10-08 17:32:09 +0000491 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000492 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000493 assert(In && "Couldn't get element of initializer?");
Chris Lattner46b5c642009-11-06 04:27:31 +0000494 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000495 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000496 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000497 GV->getThreadLocalMode(),
Owen Anderson5948fdf2009-07-08 01:26:06 +0000498 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000499 Globals.insert(GV, NGV);
500 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000501
Chris Lattner67ca6f632008-04-26 07:40:11 +0000502 // Calculate the known alignment of the field. If the original aggregate
503 // had 256 byte alignment for example, something might depend on that:
504 // propagate info to each field.
505 uint64_t FieldOffset = Layout.getElementOffset(i);
506 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000507 if (NewAlign > DL.getABITypeAlignment(STy->getElementType(i)))
Chris Lattner67ca6f632008-04-26 07:40:11 +0000508 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000509 }
Chris Lattner229907c2011-07-18 04:54:35 +0000510 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000511 unsigned NumElements = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000512 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattnerabab0712004-10-08 17:32:09 +0000513 NumElements = ATy->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000514 else
Chris Lattner67ca6f632008-04-26 07:40:11 +0000515 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattnerabab0712004-10-08 17:32:09 +0000516
Chris Lattner25169ca2005-02-23 16:53:04 +0000517 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000518 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000519 NewGlobals.reserve(NumElements);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000520
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000521 uint64_t EltSize = DL.getTypeAllocSize(STy->getElementType());
522 unsigned EltAlign = DL.getABITypeAlignment(STy->getElementType());
Chris Lattnerabab0712004-10-08 17:32:09 +0000523 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +0000524 Constant *In = Init->getAggregateElement(i);
Chris Lattnerabab0712004-10-08 17:32:09 +0000525 assert(In && "Couldn't get element of initializer?");
526
Chris Lattner46b5c642009-11-06 04:27:31 +0000527 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattnerabab0712004-10-08 17:32:09 +0000528 GlobalVariable::InternalLinkage,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000529 In, GV->getName()+"."+Twine(i),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000530 GV->getThreadLocalMode(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000531 GV->getType()->getAddressSpace());
Chris Lattnerabab0712004-10-08 17:32:09 +0000532 Globals.insert(GV, NGV);
533 NewGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000534
Chris Lattner67ca6f632008-04-26 07:40:11 +0000535 // Calculate the known alignment of the field. If the original aggregate
536 // had 256 byte alignment for example, something might depend on that:
537 // propagate info to each field.
538 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
539 if (NewAlign > EltAlign)
540 NGV->setAlignment(NewAlign);
Chris Lattnerabab0712004-10-08 17:32:09 +0000541 }
542 }
543
544 if (NewGlobals.empty())
545 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000546
David Greene44cb8ad2010-01-05 01:28:05 +0000547 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner004e2502004-10-11 05:54:41 +0000548
Chris Lattner46b5c642009-11-06 04:27:31 +0000549 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattnerabab0712004-10-08 17:32:09 +0000550
551 // Loop over all of the uses of the global, replacing the constantexpr geps,
552 // with smaller constantexpr geps or direct references.
553 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000554 User *GEP = GV->use_back();
555 assert(((isa<ConstantExpr>(GEP) &&
556 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
557 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000558
Chris Lattnerabab0712004-10-08 17:32:09 +0000559 // Ignore the 1th operand, which has to be zero or else the program is quite
560 // broken (undefined). Get the 2nd operand, which is the structure or array
561 // index.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000562 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000563 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
564
Chris Lattner004e2502004-10-11 05:54:41 +0000565 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000566
567 // Form a shorter GEP if needed.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000568 if (GEP->getNumOperands() > 3) {
Chris Lattner004e2502004-10-11 05:54:41 +0000569 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000570 SmallVector<Constant*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000571 Idxs.push_back(NullInt);
572 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
573 Idxs.push_back(CE->getOperand(i));
Jay Foaded8db7d2011-07-21 14:31:17 +0000574 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner004e2502004-10-11 05:54:41 +0000575 } else {
576 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner927653f2007-01-31 19:59:55 +0000577 SmallVector<Value*, 8> Idxs;
Chris Lattner004e2502004-10-11 05:54:41 +0000578 Idxs.push_back(NullInt);
579 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
580 Idxs.push_back(GEPI->getOperand(i));
Jay Foadd1b78492011-07-25 09:48:08 +0000581 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbar132f7832009-07-30 17:37:43 +0000582 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner004e2502004-10-11 05:54:41 +0000583 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000584 }
Chris Lattner004e2502004-10-11 05:54:41 +0000585 GEP->replaceAllUsesWith(NewPtr);
586
587 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000588 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000589 else
590 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000591 }
592
Chris Lattner73ad73e2004-10-08 20:25:55 +0000593 // Delete the old global, now that it is dead.
594 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000595 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000596
597 // Loop over the new globals array deleting any globals that are obviously
598 // dead. This can arise due to scalarization of a structure or an array that
599 // has elements that are dead.
600 unsigned FirstGlobal = 0;
601 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
602 if (NewGlobals[i]->use_empty()) {
603 Globals.erase(NewGlobals[i]);
604 if (FirstGlobal == i) ++FirstGlobal;
605 }
606
607 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000608}
609
Chris Lattner09a52722004-10-09 21:48:45 +0000610/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000611/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner2d2892e2007-09-13 16:30:19 +0000612/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif67972872010-04-06 19:24:18 +0000613static bool AllUsesOfValueWillTrapIfNull(const Value *V,
614 SmallPtrSet<const PHINode*, 8> &PHIs) {
615 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greif08355d62010-04-06 19:14:05 +0000616 ++UI) {
Gabor Greif67972872010-04-06 19:24:18 +0000617 const User *U = *UI;
Gabor Greif08355d62010-04-06 19:14:05 +0000618
619 if (isa<LoadInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000620 // Will trap.
Gabor Greif67972872010-04-06 19:24:18 +0000621 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000622 if (SI->getOperand(0) == V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000623 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000624 return false; // Storing the value.
625 }
Gabor Greif67972872010-04-06 19:24:18 +0000626 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000627 if (CI->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000628 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000629 return false; // Not calling the ptr
630 }
Gabor Greif67972872010-04-06 19:24:18 +0000631 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000632 if (II->getCalledValue() != V) {
Gabor Greif08355d62010-04-06 19:14:05 +0000633 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000634 return false; // Not calling the ptr
635 }
Gabor Greif67972872010-04-06 19:24:18 +0000636 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000637 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000638 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000639 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif67972872010-04-06 19:24:18 +0000640 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner2d2892e2007-09-13 16:30:19 +0000641 // If we've already seen this phi node, ignore it, it has already been
642 // checked.
Jakob Stoklund Olesene27dc722010-01-29 23:54:14 +0000643 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
644 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000645 } else if (isa<ICmpInst>(U) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000646 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewycky614fb942010-02-25 06:39:10 +0000647 // Ignore icmp X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000648 } else {
Gabor Greif08355d62010-04-06 19:14:05 +0000649 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000650 return false;
651 }
Gabor Greif08355d62010-04-06 19:14:05 +0000652 }
Chris Lattner09a52722004-10-09 21:48:45 +0000653 return true;
654}
655
656/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000657/// from GV will trap if the loaded value is null. Note that this also permits
658/// comparisons of the loaded value against null, as a special case.
Gabor Greif67972872010-04-06 19:24:18 +0000659static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
660 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greif08355d62010-04-06 19:14:05 +0000661 UI != E; ++UI) {
Gabor Greif67972872010-04-06 19:24:18 +0000662 const User *U = *UI;
Gabor Greif08355d62010-04-06 19:14:05 +0000663
Gabor Greif67972872010-04-06 19:24:18 +0000664 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
665 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner2d2892e2007-09-13 16:30:19 +0000666 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner09a52722004-10-09 21:48:45 +0000667 return false;
Gabor Greif08355d62010-04-06 19:14:05 +0000668 } else if (isa<StoreInst>(U)) {
Chris Lattner09a52722004-10-09 21:48:45 +0000669 // Ignore stores to the global.
670 } else {
671 // We don't know or understand this user, bail out.
Gabor Greif08355d62010-04-06 19:14:05 +0000672 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner09a52722004-10-09 21:48:45 +0000673 return false;
674 }
Gabor Greif08355d62010-04-06 19:14:05 +0000675 }
Chris Lattner09a52722004-10-09 21:48:45 +0000676 return true;
677}
678
Chris Lattner46b5c642009-11-06 04:27:31 +0000679static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000680 bool Changed = false;
681 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
682 Instruction *I = cast<Instruction>(*UI++);
683 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
684 LI->setOperand(0, NewV);
685 Changed = true;
686 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
687 if (SI->getOperand(1) == V) {
688 SI->setOperand(1, NewV);
689 Changed = true;
690 }
691 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greif04397892010-04-06 18:45:08 +0000692 CallSite CS(I);
693 if (CS.getCalledValue() == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000694 // Calling through the pointer! Turn into a direct call, but be careful
695 // that the pointer is not also being passed as an argument.
Gabor Greif04397892010-04-06 18:45:08 +0000696 CS.setCalledFunction(NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000697 Changed = true;
698 bool PassedAsArg = false;
Gabor Greif04397892010-04-06 18:45:08 +0000699 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
700 if (CS.getArgument(i) == V) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000701 PassedAsArg = true;
Gabor Greif04397892010-04-06 18:45:08 +0000702 CS.setArgument(i, NewV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000703 }
704
705 if (PassedAsArg) {
706 // Being passed as an argument also. Be careful to not invalidate UI!
707 UI = V->use_begin();
708 }
709 }
710 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
711 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson487375e2009-07-29 18:55:55 +0000712 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner46b5c642009-11-06 04:27:31 +0000713 NewV, CI->getType()));
Chris Lattnere42eb312004-10-10 23:14:11 +0000714 if (CI->use_empty()) {
715 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000716 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000717 }
718 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
719 // Should handle GEP here.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000720 SmallVector<Constant*, 8> Idxs;
721 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif3a9fba52008-05-29 01:59:18 +0000722 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
723 i != e; ++i)
724 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000725 Idxs.push_back(C);
Chris Lattnere42eb312004-10-10 23:14:11 +0000726 else
727 break;
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000728 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattnere42eb312004-10-10 23:14:11 +0000729 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaded8db7d2011-07-21 14:31:17 +0000730 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattnere42eb312004-10-10 23:14:11 +0000731 if (GEPI->use_empty()) {
732 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000733 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000734 }
735 }
736 }
737
738 return Changed;
739}
740
741
742/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
743/// value stored into it. If there are uses of the loaded value that would trap
744/// if the loaded value is dynamically null, then we know that they cannot be
745/// reachable with a null optimize away the load.
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000746static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000747 const DataLayout *DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000748 TargetLibraryInfo *TLI) {
Chris Lattnere42eb312004-10-10 23:14:11 +0000749 bool Changed = false;
750
Chris Lattner2538eb62009-01-14 00:12:58 +0000751 // Keep track of whether we are able to remove all the uses of the global
752 // other than the store that defines it.
753 bool AllNonStoreUsesGone = true;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000754
Chris Lattnere42eb312004-10-10 23:14:11 +0000755 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner2538eb62009-01-14 00:12:58 +0000756 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
757 User *GlobalUser = *GUI++;
758 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner46b5c642009-11-06 04:27:31 +0000759 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner2538eb62009-01-14 00:12:58 +0000760 // If we were able to delete all uses of the loads
761 if (LI->use_empty()) {
762 LI->eraseFromParent();
763 Changed = true;
764 } else {
765 AllNonStoreUsesGone = false;
766 }
767 } else if (isa<StoreInst>(GlobalUser)) {
768 // Ignore the store that stores "LV" to the global.
769 assert(GlobalUser->getOperand(1) == GV &&
770 "Must be storing *to* the global");
Chris Lattnere42eb312004-10-10 23:14:11 +0000771 } else {
Chris Lattner2538eb62009-01-14 00:12:58 +0000772 AllNonStoreUsesGone = false;
773
774 // If we get here we could have other crazy uses that are transitively
775 // loaded.
776 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Benjamin Kramered843602012-09-28 10:01:27 +0000777 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
778 isa<BitCastInst>(GlobalUser) ||
779 isa<GetElementPtrInst>(GlobalUser)) &&
Chris Lattner1a1acc22011-05-22 07:15:13 +0000780 "Only expect load and stores!");
Chris Lattnere42eb312004-10-10 23:14:11 +0000781 }
Chris Lattner2538eb62009-01-14 00:12:58 +0000782 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000783
784 if (Changed) {
David Greene44cb8ad2010-01-05 01:28:05 +0000785 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattnere42eb312004-10-10 23:14:11 +0000786 ++NumGlobUses;
787 }
788
Chris Lattnere42eb312004-10-10 23:14:11 +0000789 // If we nuked all of the loads, then none of the stores are needed either,
790 // nor is the global.
Chris Lattner2538eb62009-01-14 00:12:58 +0000791 if (AllNonStoreUsesGone) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000792 if (isLeakCheckerRoot(GV)) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000793 Changed |= CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000794 } else {
795 Changed = true;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000796 CleanupConstantGlobalUsers(GV, 0, DL, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000797 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000798 if (GV->use_empty()) {
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +0000799 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
800 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000801 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000802 ++NumDeleted;
803 }
Chris Lattnere42eb312004-10-10 23:14:11 +0000804 }
805 return Changed;
806}
807
Chris Lattner004e2502004-10-11 05:54:41 +0000808/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
809/// instructions that are foldable.
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000810static void ConstantPropUsersOf(Value *V, const DataLayout *DL,
811 TargetLibraryInfo *TLI) {
Chris Lattner004e2502004-10-11 05:54:41 +0000812 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
813 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000814 if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) {
Chris Lattner004e2502004-10-11 05:54:41 +0000815 I->replaceAllUsesWith(NewC);
816
Chris Lattnerd6a44922005-02-01 01:23:31 +0000817 // Advance UI to the next non-I use to avoid invalidating it!
818 // Instructions could multiply use V.
819 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000820 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000821 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000822 }
823}
824
825/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
826/// variable, and transforms the program as if it always contained the result of
827/// the specified malloc. Because it is always the result of the specified
828/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner3ede00b2006-11-30 17:32:29 +0000829/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner004e2502004-10-11 05:54:41 +0000830static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +0000831 CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +0000832 Type *AllocTy,
Chris Lattner7939f792010-02-25 22:33:52 +0000833 ConstantInt *NElements,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000834 const DataLayout *DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +0000835 TargetLibraryInfo *TLI) {
Chris Lattner7939f792010-02-25 22:33:52 +0000836 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000837
Chris Lattner229907c2011-07-18 04:54:35 +0000838 Type *GlobalType;
Chris Lattner7939f792010-02-25 22:33:52 +0000839 if (NElements->getZExtValue() == 1)
840 GlobalType = AllocTy;
841 else
842 // If we have an array allocation, the global variable is of an array.
843 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez5d034492009-09-18 22:35:49 +0000844
845 // Create the new global variable. The contents of the malloc'd memory is
846 // undefined, so initialize with an undef value.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000847 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000848 GlobalType, false,
Chris Lattner7939f792010-02-25 22:33:52 +0000849 GlobalValue::InternalLinkage,
Chris Lattner65d3a0a2010-02-26 23:42:13 +0000850 UndefValue::get(GlobalType),
Victor Hernandez5d034492009-09-18 22:35:49 +0000851 GV->getName()+".body",
852 GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000853 GV->getThreadLocalMode());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000854
Chris Lattner7939f792010-02-25 22:33:52 +0000855 // If there are bitcast users of the malloc (which is typical, usually we have
856 // a malloc + bitcast) then replace them with uses of the new global. Update
857 // other users to use the global as well.
858 BitCastInst *TheBC = 0;
859 while (!CI->use_empty()) {
860 Instruction *User = cast<Instruction>(CI->use_back());
861 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
862 if (BCI->getType() == NewGV->getType()) {
863 BCI->replaceAllUsesWith(NewGV);
864 BCI->eraseFromParent();
865 } else {
866 BCI->setOperand(0, NewGV);
867 }
868 } else {
869 if (TheBC == 0)
870 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
871 User->replaceUsesOfWith(CI, TheBC);
872 }
873 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000874
Victor Hernandez5d034492009-09-18 22:35:49 +0000875 Constant *RepValue = NewGV;
876 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000877 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez5d034492009-09-18 22:35:49 +0000878 GV->getType()->getElementType());
879
880 // If there is a comparison against null, we will insert a global bool to
881 // keep track of whether the global was initialized yet or not.
882 GlobalVariable *InitBool =
Chris Lattner46b5c642009-11-06 04:27:31 +0000883 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez5d034492009-09-18 22:35:49 +0000884 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +0000885 ConstantInt::getFalse(GV->getContext()),
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000886 GV->getName()+".init", GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +0000887 bool InitBoolUsed = false;
888
889 // Loop over all uses of GV, processing them in turn.
Chris Lattner7939f792010-02-25 22:33:52 +0000890 while (!GV->use_empty()) {
891 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez5d034492009-09-18 22:35:49 +0000892 // The global is initialized when the store to it occurs.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000893 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
894 SI->getOrdering(), SI->getSynchScope(), SI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000895 SI->eraseFromParent();
Chris Lattner7939f792010-02-25 22:33:52 +0000896 continue;
Victor Hernandez5d034492009-09-18 22:35:49 +0000897 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000898
Chris Lattner7939f792010-02-25 22:33:52 +0000899 LoadInst *LI = cast<LoadInst>(GV->use_back());
900 while (!LI->use_empty()) {
901 Use &LoadUse = LI->use_begin().getUse();
902 if (!isa<ICmpInst>(LoadUse.getUser())) {
903 LoadUse = RepValue;
904 continue;
905 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000906
Chris Lattner7939f792010-02-25 22:33:52 +0000907 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
908 // Replace the cmp X, 0 with a use of the bool value.
Nick Lewycky52da72b2012-02-05 19:56:38 +0000909 // Sink the load to where the compare was, if atomic rules allow us to.
910 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
911 LI->getOrdering(), LI->getSynchScope(),
912 LI->isUnordered() ? (Instruction*)ICI : LI);
Chris Lattner7939f792010-02-25 22:33:52 +0000913 InitBoolUsed = true;
914 switch (ICI->getPredicate()) {
915 default: llvm_unreachable("Unknown ICmp Predicate!");
916 case ICmpInst::ICMP_ULT:
917 case ICmpInst::ICMP_SLT: // X < null -> always false
918 LV = ConstantInt::getFalse(GV->getContext());
919 break;
920 case ICmpInst::ICMP_ULE:
921 case ICmpInst::ICMP_SLE:
922 case ICmpInst::ICMP_EQ:
923 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
924 break;
925 case ICmpInst::ICMP_NE:
926 case ICmpInst::ICMP_UGE:
927 case ICmpInst::ICMP_SGE:
928 case ICmpInst::ICMP_UGT:
929 case ICmpInst::ICMP_SGT:
930 break; // no change.
931 }
932 ICI->replaceAllUsesWith(LV);
933 ICI->eraseFromParent();
934 }
935 LI->eraseFromParent();
936 }
Victor Hernandez5d034492009-09-18 22:35:49 +0000937
938 // If the initialization boolean was used, insert it, otherwise delete it.
939 if (!InitBoolUsed) {
940 while (!InitBool->use_empty()) // Delete initializations
Chris Lattner7939f792010-02-25 22:33:52 +0000941 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000942 delete InitBool;
943 } else
944 GV->getParent()->getGlobalList().insert(GV, InitBool);
945
Chris Lattner7939f792010-02-25 22:33:52 +0000946 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez5d034492009-09-18 22:35:49 +0000947 GV->eraseFromParent();
Victor Hernandez5d034492009-09-18 22:35:49 +0000948 CI->eraseFromParent();
949
950 // To further other optimizations, loop over all users of NewGV and try to
951 // constant prop them. This will promote GEP instructions with constant
952 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000953 ConstantPropUsersOf(NewGV, DL, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000954 if (RepValue != NewGV)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000955 ConstantPropUsersOf(RepValue, DL, TLI);
Victor Hernandez5d034492009-09-18 22:35:49 +0000956
957 return NewGV;
958}
959
Chris Lattnerc0677c02004-12-02 07:11:07 +0000960/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
961/// to make sure that there are no complex uses of V. We permit simple things
962/// like dereferencing the pointer, but not storing through the address, unless
963/// it is to the specified global.
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000964static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
965 const GlobalVariable *GV,
Gabor Greif08355d62010-04-06 19:14:05 +0000966 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000967 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greif08355d62010-04-06 19:14:05 +0000968 UI != E; ++UI) {
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000969 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greif08355d62010-04-06 19:14:05 +0000970
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000971 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
972 continue; // Fine, ignore.
973 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000974
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000975 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerc0677c02004-12-02 07:11:07 +0000976 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
977 return false; // Storing the pointer itself... bad.
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000978 continue; // Otherwise, storing through it, or storing into GV... fine.
979 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000980
Chris Lattnerb9801ff2010-04-10 18:19:22 +0000981 // Must index into the array and into the struct.
982 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000983 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerc0677c02004-12-02 07:11:07 +0000984 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000985 continue;
986 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000987
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000988 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattner6eed0e72007-09-13 16:37:20 +0000989 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
990 // cycles.
991 if (PHIs.insert(PN))
Chris Lattner5d13fb532007-09-14 03:41:21 +0000992 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
993 return false;
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000994 continue;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000995 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +0000996
Gabor Greifa21bc0f2010-04-06 18:58:22 +0000997 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattnerf0eb5682008-12-15 21:08:54 +0000998 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
999 return false;
1000 continue;
1001 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001002
Chris Lattnerf0eb5682008-12-15 21:08:54 +00001003 return false;
1004 }
Chris Lattnerc0677c02004-12-02 07:11:07 +00001005 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +00001006}
1007
Chris Lattner24d3d422006-09-30 23:32:09 +00001008/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1009/// somewhere. Transform all uses of the allocation into loads from the
1010/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001011/// GV. This assumes that these value pass the
Chris Lattner24d3d422006-09-30 23:32:09 +00001012/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001013static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001014 GlobalVariable *GV) {
1015 while (!Alloc->use_empty()) {
Chris Lattnerba98f892007-09-13 18:00:31 +00001016 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1017 Instruction *InsertPt = U;
Chris Lattner24d3d422006-09-30 23:32:09 +00001018 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1019 // If this is the store of the allocation into the global, remove it.
1020 if (SI->getOperand(1) == GV) {
1021 SI->eraseFromParent();
1022 continue;
1023 }
Chris Lattnerba98f892007-09-13 18:00:31 +00001024 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1025 // Insert the load in the corresponding predecessor, not right before the
1026 // PHI.
Gabor Greifeb61fcf2009-01-23 19:40:15 +00001027 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner49e3bdc2008-12-15 21:44:34 +00001028 } else if (isa<BitCastInst>(U)) {
1029 // Must be bitcast between the malloc and store to initialize the global.
1030 ReplaceUsesOfMallocWithGlobal(U, GV);
1031 U->eraseFromParent();
1032 continue;
1033 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1034 // If this is a "GEP bitcast" and the user is a store to the global, then
1035 // just process it as a bitcast.
1036 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1037 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1038 if (SI->getOperand(1) == GV) {
1039 // Must be bitcast GEP between the malloc and store to initialize
1040 // the global.
1041 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1042 GEPI->eraseFromParent();
1043 continue;
1044 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001045 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001046
Chris Lattner24d3d422006-09-30 23:32:09 +00001047 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnerba98f892007-09-13 18:00:31 +00001048 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner24d3d422006-09-30 23:32:09 +00001049 U->replaceUsesOfWith(Alloc, NL);
1050 }
1051}
1052
Chris Lattner56b55382008-12-16 21:24:51 +00001053/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1054/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1055/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greif5d5db532010-04-01 08:21:08 +00001056static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif08d85da2010-04-07 18:59:26 +00001057 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1058 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner56b55382008-12-16 21:24:51 +00001059 // We permit two users of the load: setcc comparing against the null
1060 // pointer, and a getelementptr of a specific form.
Gabor Greif08d85da2010-04-07 18:59:26 +00001061 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1062 ++UI) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001063 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001064
Chris Lattner56b55382008-12-16 21:24:51 +00001065 // Comparison against null is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001066 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001067 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1068 return false;
1069 continue;
1070 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001071
Chris Lattner56b55382008-12-16 21:24:51 +00001072 // getelementptr is also ok, but only a simple form.
Gabor Greif5d5db532010-04-01 08:21:08 +00001073 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner56b55382008-12-16 21:24:51 +00001074 // Must index into the array and into the struct.
1075 if (GEPI->getNumOperands() < 3)
1076 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001077
Chris Lattner56b55382008-12-16 21:24:51 +00001078 // Otherwise the GEP is ok.
1079 continue;
1080 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001081
Gabor Greif5d5db532010-04-01 08:21:08 +00001082 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng83689442009-06-02 00:56:07 +00001083 if (!LoadUsingPHIsPerLoad.insert(PN))
1084 // This means some phi nodes are dependent on each other.
1085 // Avoid infinite looping!
1086 return false;
1087 if (!LoadUsingPHIs.insert(PN))
1088 // If we have already analyzed this PHI, then it is safe.
Chris Lattner56b55382008-12-16 21:24:51 +00001089 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001090
Chris Lattner222ef4c2008-12-17 05:28:49 +00001091 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng83689442009-06-02 00:56:07 +00001092 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1093 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001094 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001095
Chris Lattner56b55382008-12-16 21:24:51 +00001096 continue;
Chris Lattner24d3d422006-09-30 23:32:09 +00001097 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001098
Chris Lattner56b55382008-12-16 21:24:51 +00001099 // Otherwise we don't know what this is, not ok.
1100 return false;
1101 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001102
Chris Lattner56b55382008-12-16 21:24:51 +00001103 return true;
1104}
1105
1106
1107/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1108/// GV are simple enough to perform HeapSRA, return true.
Gabor Greif5d5db532010-04-01 08:21:08 +00001109static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001110 Instruction *StoredVal) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001111 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1112 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif08d85da2010-04-07 18:59:26 +00001113 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1114 UI != E; ++UI)
Gabor Greif5d5db532010-04-01 08:21:08 +00001115 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng83689442009-06-02 00:56:07 +00001116 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1117 LoadUsingPHIsPerLoad))
Chris Lattner56b55382008-12-16 21:24:51 +00001118 return false;
Evan Cheng83689442009-06-02 00:56:07 +00001119 LoadUsingPHIsPerLoad.clear();
1120 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001121
Chris Lattner222ef4c2008-12-17 05:28:49 +00001122 // If we reach here, we know that all uses of the loads and transitive uses
1123 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001124 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001125 // Check to verify that all operands of the PHIs are either PHIS that can be
1126 // transformed, loads from GV, or MI itself.
Gabor Greif08d85da2010-04-07 18:59:26 +00001127 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1128 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greif5d5db532010-04-01 08:21:08 +00001129 const PHINode *PN = *I;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001130 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1131 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001132
Chris Lattner222ef4c2008-12-17 05:28:49 +00001133 // PHI of the stored value itself is ok.
Victor Hernandez5d034492009-09-18 22:35:49 +00001134 if (InVal == StoredVal) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001135
Gabor Greif5d5db532010-04-01 08:21:08 +00001136 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001137 // One of the PHIs in our set is (optimistically) ok.
1138 if (LoadUsingPHIs.count(InPN))
1139 continue;
1140 return false;
1141 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001142
Chris Lattner222ef4c2008-12-17 05:28:49 +00001143 // Load from GV is ok.
Gabor Greif5d5db532010-04-01 08:21:08 +00001144 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattner222ef4c2008-12-17 05:28:49 +00001145 if (LI->getOperand(0) == GV)
1146 continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001147
Chris Lattner222ef4c2008-12-17 05:28:49 +00001148 // UNDEF? NULL?
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001149
Chris Lattner222ef4c2008-12-17 05:28:49 +00001150 // Anything else is rejected.
1151 return false;
1152 }
1153 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001154
Chris Lattner24d3d422006-09-30 23:32:09 +00001155 return true;
1156}
1157
Chris Lattner222ef4c2008-12-17 05:28:49 +00001158static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1159 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001160 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001161 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001162
Chris Lattner222ef4c2008-12-17 05:28:49 +00001163 if (FieldNo >= FieldVals.size())
1164 FieldVals.resize(FieldNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001165
Chris Lattner222ef4c2008-12-17 05:28:49 +00001166 // If we already have this value, just reuse the previously scalarized
1167 // version.
1168 if (Value *FieldVal = FieldVals[FieldNo])
1169 return FieldVal;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001170
Chris Lattner222ef4c2008-12-17 05:28:49 +00001171 // Depending on what instruction this is, we have several cases.
1172 Value *Result;
1173 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1174 // This is a scalarized version of the load from the global. Just create
1175 // a new Load of the scalarized global.
1176 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1177 InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001178 PHIsToRewrite),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001179 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattner222ef4c2008-12-17 05:28:49 +00001180 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1181 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1182 // field.
Matt Arsenault404c60a2013-10-21 19:43:56 +00001183 StructType *ST = cast<StructType>(PN->getType()->getPointerElementType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001184
Jay Foade0938d82011-03-30 11:19:20 +00001185 PHINode *NewPN =
Owen Anderson4056ca92009-07-29 22:17:13 +00001186 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad52131342011-03-30 11:28:46 +00001187 PN->getNumIncomingValues(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001188 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foade0938d82011-03-30 11:19:20 +00001189 Result = NewPN;
Chris Lattner222ef4c2008-12-17 05:28:49 +00001190 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1191 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001192 llvm_unreachable("Unknown usable value");
Chris Lattner222ef4c2008-12-17 05:28:49 +00001193 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001194
Chris Lattner222ef4c2008-12-17 05:28:49 +00001195 return FieldVals[FieldNo] = Result;
Chris Lattnerba98f892007-09-13 18:00:31 +00001196}
1197
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001198/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1199/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001200static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001201 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001202 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001203 // If this is a comparison against null, handle it.
1204 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1205 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1206 // If we have a setcc of the loaded pointer, we can use a setcc of any
1207 // field.
Chris Lattner222ef4c2008-12-17 05:28:49 +00001208 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner46b5c642009-11-06 04:27:31 +00001209 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001210
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001211 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001212 Constant::getNullValue(NPtr->getType()),
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001213 SCI->getName());
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001214 SCI->replaceAllUsesWith(New);
1215 SCI->eraseFromParent();
1216 return;
1217 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001218
Chris Lattner222ef4c2008-12-17 05:28:49 +00001219 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnerba98f892007-09-13 18:00:31 +00001220 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1221 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1222 && "Unexpected GEPI!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001223
Chris Lattnerba98f892007-09-13 18:00:31 +00001224 // Load the pointer for this field.
1225 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner222ef4c2008-12-17 05:28:49 +00001226 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner46b5c642009-11-06 04:27:31 +00001227 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001228
Chris Lattnerba98f892007-09-13 18:00:31 +00001229 // Create the new GEP idx vector.
1230 SmallVector<Value*, 8> GEPIdx;
1231 GEPIdx.push_back(GEPI->getOperand(1));
1232 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001233
Jay Foadd1b78492011-07-25 09:48:08 +00001234 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greife9ecc682008-04-06 20:25:17 +00001235 GEPI->getName(), GEPI);
Chris Lattnerba98f892007-09-13 18:00:31 +00001236 GEPI->replaceAllUsesWith(NGEPI);
1237 GEPI->eraseFromParent();
1238 return;
1239 }
Chris Lattner011f91b2007-09-13 21:31:36 +00001240
Chris Lattner222ef4c2008-12-17 05:28:49 +00001241 // Recursively transform the users of PHI nodes. This will lazily create the
1242 // PHIs that are needed for individual elements. Keep track of what PHIs we
1243 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1244 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1245 // already been seen first by another load, so its uses have already been
1246 // processed.
1247 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattner5cf753c2011-07-21 06:21:31 +00001248 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1249 std::vector<Value*>())).second)
1250 return;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001251
Chris Lattner222ef4c2008-12-17 05:28:49 +00001252 // If this is the first time we've seen this PHI, recursively process all
1253 // users.
Chris Lattner0cdf5232008-12-17 05:42:08 +00001254 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1255 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001256 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001257 }
Chris Lattnerf315d4f2007-09-13 17:29:05 +00001258}
1259
Chris Lattner24d3d422006-09-30 23:32:09 +00001260/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1261/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1262/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner56b55382008-12-16 21:24:51 +00001263/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001264static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner222ef4c2008-12-17 05:28:49 +00001265 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001266 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner222ef4c2008-12-17 05:28:49 +00001267 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattner0cdf5232008-12-17 05:42:08 +00001268 UI != E; ) {
1269 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner46b5c642009-11-06 04:27:31 +00001270 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattner0cdf5232008-12-17 05:42:08 +00001271 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001272
Chris Lattner222ef4c2008-12-17 05:28:49 +00001273 if (Load->use_empty()) {
1274 Load->eraseFromParent();
1275 InsertedScalarizedValues.erase(Load);
1276 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001277}
1278
Victor Hernandez5d034492009-09-18 22:35:49 +00001279/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1280/// it up into multiple allocations of arrays of the fields.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001281static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +00001282 Value *NElems, const DataLayout *DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001283 const TargetLibraryInfo *TLI) {
David Greene44cb8ad2010-01-05 01:28:05 +00001284 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001285 Type *MAT = getMallocAllocatedType(CI, TLI);
Chris Lattner229907c2011-07-18 04:54:35 +00001286 StructType *STy = cast<StructType>(MAT);
Victor Hernandez5d034492009-09-18 22:35:49 +00001287
1288 // There is guaranteed to be at least one use of the malloc (storing
1289 // it into GV). If there are other uses, change them to be uses of
1290 // the global to simplify later code. This also deletes the store
1291 // into GV.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001292 ReplaceUsesOfMallocWithGlobal(CI, GV);
1293
Victor Hernandez5d034492009-09-18 22:35:49 +00001294 // Okay, at this point, there are no users of the malloc. Insert N
1295 // new mallocs at the same place as CI, and N globals.
1296 std::vector<Value*> FieldGlobals;
1297 std::vector<Value*> FieldMallocs;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001298
Victor Hernandez5d034492009-09-18 22:35:49 +00001299 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattner229907c2011-07-18 04:54:35 +00001300 Type *FieldTy = STy->getElementType(FieldNo);
1301 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001302
Victor Hernandez5d034492009-09-18 22:35:49 +00001303 GlobalVariable *NGV =
1304 new GlobalVariable(*GV->getParent(),
1305 PFieldTy, false, GlobalValue::InternalLinkage,
1306 Constant::getNullValue(PFieldTy),
1307 GV->getName() + ".f" + Twine(FieldNo), GV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001308 GV->getThreadLocalMode());
Victor Hernandez5d034492009-09-18 22:35:49 +00001309 FieldGlobals.push_back(NGV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001310
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001311 unsigned TypeSize = DL->getTypeAllocSize(FieldTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001312 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001313 TypeSize = DL->getStructLayout(ST)->getSizeInBytes();
1314 Type *IntPtrTy = DL->getIntPtrType(CI->getType());
Victor Hernandezf3db9152009-11-07 00:16:28 +00001315 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1316 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner601e390a2010-07-12 00:57:28 +00001317 NElems, 0,
Victor Hernandezf3db9152009-11-07 00:16:28 +00001318 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner0521c092010-02-26 18:23:13 +00001319 FieldMallocs.push_back(NMI);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001320 new StoreInst(NMI, NGV, CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001321 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001322
Victor Hernandez5d034492009-09-18 22:35:49 +00001323 // The tricky aspect of this transformation is handling the case when malloc
1324 // fails. In the original code, malloc failing would set the result pointer
1325 // of malloc to null. In this case, some mallocs could succeed and others
1326 // could fail. As such, we emit code that looks like this:
1327 // F0 = malloc(field0)
1328 // F1 = malloc(field1)
1329 // F2 = malloc(field2)
1330 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1331 // if (F0) { free(F0); F0 = 0; }
1332 // if (F1) { free(F1); F1 = 0; }
1333 // if (F2) { free(F2); F2 = 0; }
1334 // }
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001335 // The malloc can also fail if its argument is too large.
Gabor Greif218f5542010-06-24 14:42:01 +00001336 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1337 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001338 ConstantZero, "isneg");
Victor Hernandez5d034492009-09-18 22:35:49 +00001339 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandezf3db9152009-11-07 00:16:28 +00001340 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1341 Constant::getNullValue(FieldMallocs[i]->getType()),
1342 "isnull");
Victor Hernandezfcc77b12009-11-10 08:32:25 +00001343 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001344 }
1345
1346 // Split the basic block at the old malloc.
Victor Hernandezf3db9152009-11-07 00:16:28 +00001347 BasicBlock *OrigBB = CI->getParent();
1348 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001349
Victor Hernandez5d034492009-09-18 22:35:49 +00001350 // Create the block to check the first condition. Put all these blocks at the
1351 // end of the function as they are unlikely to be executed.
Chris Lattner46b5c642009-11-06 04:27:31 +00001352 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1353 "malloc_ret_null",
Victor Hernandez5d034492009-09-18 22:35:49 +00001354 OrigBB->getParent());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001355
Victor Hernandez5d034492009-09-18 22:35:49 +00001356 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1357 // branch on RunningOr.
1358 OrigBB->getTerminator()->eraseFromParent();
1359 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001360
Victor Hernandez5d034492009-09-18 22:35:49 +00001361 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1362 // pointer, because some may be null while others are not.
1363 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1364 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001365 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001366 Constant::getNullValue(GVVal->getType()));
Chris Lattner46b5c642009-11-06 04:27:31 +00001367 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez5d034492009-09-18 22:35:49 +00001368 OrigBB->getParent());
Chris Lattner46b5c642009-11-06 04:27:31 +00001369 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez5d034492009-09-18 22:35:49 +00001370 OrigBB->getParent());
Victor Hernandeze2971492009-10-24 04:23:03 +00001371 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1372 Cmp, NullPtrBlock);
Victor Hernandez5d034492009-09-18 22:35:49 +00001373
1374 // Fill in FreeBlock.
Victor Hernandeze2971492009-10-24 04:23:03 +00001375 CallInst::CreateFree(GVVal, BI);
Victor Hernandez5d034492009-09-18 22:35:49 +00001376 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1377 FreeBlock);
1378 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001379
Victor Hernandez5d034492009-09-18 22:35:49 +00001380 NullPtrBlock = NextBlock;
1381 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001382
Victor Hernandez5d034492009-09-18 22:35:49 +00001383 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandezf3db9152009-11-07 00:16:28 +00001384
1385 // CI is no longer needed, remove it.
Victor Hernandez5d034492009-09-18 22:35:49 +00001386 CI->eraseFromParent();
1387
1388 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1389 /// update all uses of the load, keep track of what scalarized loads are
1390 /// inserted for a given load.
1391 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1392 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001393
Victor Hernandez5d034492009-09-18 22:35:49 +00001394 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001395
Victor Hernandez5d034492009-09-18 22:35:49 +00001396 // Okay, the malloc site is completely handled. All of the uses of GV are now
1397 // loads, and all uses of those loads are simple. Rewrite them to use loads
1398 // of the per-field globals instead.
1399 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1400 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001401
Victor Hernandez5d034492009-09-18 22:35:49 +00001402 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001403 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001404 continue;
1405 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001406
Victor Hernandez5d034492009-09-18 22:35:49 +00001407 // Must be a store of null.
1408 StoreInst *SI = cast<StoreInst>(User);
1409 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1410 "Unexpected heap-sra user!");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001411
Victor Hernandez5d034492009-09-18 22:35:49 +00001412 // Insert a store of null into each global.
1413 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +00001414 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez5d034492009-09-18 22:35:49 +00001415 Constant *Null = Constant::getNullValue(PT->getElementType());
1416 new StoreInst(Null, FieldGlobals[i], SI);
1417 }
1418 // Erase the original store.
1419 SI->eraseFromParent();
1420 }
1421
1422 // While we have PHIs that are interesting to rewrite, do it.
1423 while (!PHIsToRewrite.empty()) {
1424 PHINode *PN = PHIsToRewrite.back().first;
1425 unsigned FieldNo = PHIsToRewrite.back().second;
1426 PHIsToRewrite.pop_back();
1427 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1428 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1429
1430 // Add all the incoming values. This can materialize more phis.
1431 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1432 Value *InVal = PN->getIncomingValue(i);
1433 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner46b5c642009-11-06 04:27:31 +00001434 PHIsToRewrite);
Victor Hernandez5d034492009-09-18 22:35:49 +00001435 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1436 }
1437 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001438
Victor Hernandez5d034492009-09-18 22:35:49 +00001439 // Drop all inter-phi links and any loads that made it this far.
1440 for (DenseMap<Value*, std::vector<Value*> >::iterator
1441 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1442 I != E; ++I) {
1443 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1444 PN->dropAllReferences();
1445 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1446 LI->dropAllReferences();
1447 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001448
Victor Hernandez5d034492009-09-18 22:35:49 +00001449 // Delete all the phis and loads now that inter-references are dead.
1450 for (DenseMap<Value*, std::vector<Value*> >::iterator
1451 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1452 I != E; ++I) {
1453 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1454 PN->eraseFromParent();
1455 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1456 LI->eraseFromParent();
1457 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001458
Victor Hernandez5d034492009-09-18 22:35:49 +00001459 // The old global is now dead, remove it.
1460 GV->eraseFromParent();
1461
1462 ++NumHeapSRA;
1463 return cast<GlobalVariable>(FieldGlobals[0]);
1464}
1465
Chris Lattnerc4274a72008-12-15 21:02:25 +00001466/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1467/// pointer global variable with a single value stored it that is a malloc or
1468/// cast of malloc.
1469static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez5d034492009-09-18 22:35:49 +00001470 CallInst *CI,
Chris Lattner229907c2011-07-18 04:54:35 +00001471 Type *AllocTy,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001472 AtomicOrdering Ordering,
Victor Hernandez5d034492009-09-18 22:35:49 +00001473 Module::global_iterator &GVI,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +00001474 const DataLayout *DL,
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001475 TargetLibraryInfo *TLI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001476 if (!DL)
Evan Cheng21b588b2010-04-14 20:52:55 +00001477 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001478
Victor Hernandez5d034492009-09-18 22:35:49 +00001479 // If this is a malloc of an abstract type, don't touch it.
1480 if (!AllocTy->isSized())
1481 return false;
1482
1483 // We can't optimize this global unless all uses of it are *known* to be
1484 // of the malloc value, not of the null initializer value (consider a use
1485 // that compares the global's value against zero to see if the malloc has
1486 // been reached). To do this, we check to see if all uses of the global
1487 // would trap if the global were null: this proves that they must all
1488 // happen after the malloc.
1489 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1490 return false;
1491
1492 // We can't optimize this if the malloc itself is used in a complex way,
1493 // for example, being stored into multiple globals. This allows the
Nick Lewyckybbd11562012-02-05 19:48:37 +00001494 // malloc to be stored into the specified global, loaded icmp'd, and
Victor Hernandez5d034492009-09-18 22:35:49 +00001495 // GEP'd. These are all things we could transform to using the global
1496 // for.
Evan Cheng21b588b2010-04-14 20:52:55 +00001497 SmallPtrSet<const PHINode*, 8> PHIs;
1498 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1499 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001500
1501 // If we have a global that is only initialized with a fixed size malloc,
1502 // transform the program to use global memory instead of malloc'd memory.
1503 // This eliminates dynamic allocation, avoids an indirection accessing the
1504 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez264da322009-10-16 23:12:25 +00001505 // We cannot optimize the malloc if we cannot determine malloc array size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001506 Value *NElems = getMallocArraySize(CI, DL, TLI, true);
Evan Cheng21b588b2010-04-14 20:52:55 +00001507 if (!NElems)
1508 return false;
Victor Hernandez5d034492009-09-18 22:35:49 +00001509
Evan Cheng21b588b2010-04-14 20:52:55 +00001510 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1511 // Restrict this transformation to only working on small allocations
1512 // (2048 bytes currently), as we don't want to introduce a 16M global or
1513 // something.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001514 if (NElements->getZExtValue() * DL->getTypeAllocSize(AllocTy) < 2048) {
1515 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001516 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001517 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001518
Evan Cheng21b588b2010-04-14 20:52:55 +00001519 // If the allocation is an array of structures, consider transforming this
1520 // into multiple malloc'd arrays, one for each field. This is basically
1521 // SRoA for malloc'd memory.
1522
Nick Lewycky52da72b2012-02-05 19:56:38 +00001523 if (Ordering != NotAtomic)
1524 return false;
1525
Evan Cheng21b588b2010-04-14 20:52:55 +00001526 // If this is an allocation of a fixed size array of structs, analyze as a
1527 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif218f5542010-06-24 14:42:01 +00001528 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattner229907c2011-07-18 04:54:35 +00001529 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng21b588b2010-04-14 20:52:55 +00001530 AllocTy = AT->getElementType();
Gabor Greif218f5542010-06-24 14:42:01 +00001531
Chris Lattner229907c2011-07-18 04:54:35 +00001532 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng21b588b2010-04-14 20:52:55 +00001533 if (!AllocSTy)
1534 return false;
1535
1536 // This the structure has an unreasonable number of fields, leave it
1537 // alone.
1538 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1539 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1540
1541 // If this is a fixed size array, transform the Malloc to be an alloc of
1542 // structs. malloc [100 x struct],1 -> malloc struct, 100
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001543 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001544 Type *IntPtrTy = DL->getIntPtrType(CI->getType());
1545 unsigned TypeSize = DL->getStructLayout(AllocSTy)->getSizeInBytes();
Evan Cheng21b588b2010-04-14 20:52:55 +00001546 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1547 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1548 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1549 AllocSize, NumElements,
Chris Lattner601e390a2010-07-12 00:57:28 +00001550 0, CI->getName());
Evan Cheng21b588b2010-04-14 20:52:55 +00001551 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1552 CI->replaceAllUsesWith(Cast);
1553 CI->eraseFromParent();
Nuno Lopes9792d682012-06-22 00:25:01 +00001554 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1555 CI = cast<CallInst>(BCI->getOperand(0));
1556 else
Nuno Lopes0b60ebb2012-06-22 00:29:58 +00001557 CI = cast<CallInst>(Malloc);
Evan Cheng21b588b2010-04-14 20:52:55 +00001558 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001559
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001560 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true),
1561 DL, TLI);
Evan Cheng21b588b2010-04-14 20:52:55 +00001562 return true;
Victor Hernandez5d034492009-09-18 22:35:49 +00001563 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001564
Victor Hernandez5d034492009-09-18 22:35:49 +00001565 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001566}
Victor Hernandez5d034492009-09-18 22:35:49 +00001567
Chris Lattner09a52722004-10-09 21:48:45 +00001568// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1569// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001570static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Nick Lewycky52da72b2012-02-05 19:56:38 +00001571 AtomicOrdering Ordering,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001572 Module::global_iterator &GVI,
Rafael Espindolaaeff8a92014-02-24 23:12:18 +00001573 const DataLayout *DL,
1574 TargetLibraryInfo *TLI) {
Chris Lattner1c731fa2008-12-15 21:20:32 +00001575 // Ignore no-op GEPs and bitcasts.
1576 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner09a52722004-10-09 21:48:45 +00001577
Chris Lattnere42eb312004-10-10 23:14:11 +00001578 // If we are dealing with a pointer global that is initialized to null and
1579 // only has one (non-null) value stored into it, then we can optimize any
1580 // users of the loaded value (often calls and loads) that would trap if the
1581 // value was null.
Duncan Sands19d0b472010-02-16 11:11:14 +00001582 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner09a52722004-10-09 21:48:45 +00001583 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001584 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1585 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner1a1acc22011-05-22 07:15:13 +00001586 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001587
Chris Lattnere42eb312004-10-10 23:14:11 +00001588 // Optimize away any trapping uses of the loaded value.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001589 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, TLI))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001590 return true;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001591 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1592 Type *MallocType = getMallocAllocatedType(CI, TLI);
Nick Lewyckycf6aae62012-02-12 01:13:18 +00001593 if (MallocType &&
1594 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001595 DL, TLI))
Victor Hernandezf3db9152009-11-07 00:16:28 +00001596 return true;
Chris Lattnere42eb312004-10-10 23:14:11 +00001597 }
Chris Lattner09a52722004-10-09 21:48:45 +00001598 }
Chris Lattner004e2502004-10-11 05:54:41 +00001599
Chris Lattner09a52722004-10-09 21:48:45 +00001600 return false;
1601}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001602
Chris Lattner20bbac32008-01-14 01:17:44 +00001603/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1604/// two values ever stored into GV are its initializer and OtherVal. See if we
1605/// can shrink the global into a boolean and select between the two values
1606/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner46b5c642009-11-06 04:27:31 +00001607static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00001608 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001609
Chris Lattner20bbac32008-01-14 01:17:44 +00001610 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattnere3132832009-03-07 23:32:02 +00001611 // an FP value, pointer or vector, don't do this optimization because a select
1612 // between them is very expensive and unlikely to lead to later
1613 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1614 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner46b5c642009-11-06 04:27:31 +00001615 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001616 GVElType->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001617 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner20bbac32008-01-14 01:17:44 +00001618 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001619
Chris Lattner20bbac32008-01-14 01:17:44 +00001620 // Walk the use list of the global seeing if all the uses are load or store.
1621 // If there is anything else, bail out.
Gabor Greifa75ed762010-07-12 14:13:15 +00001622 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1623 User *U = *I;
1624 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner20bbac32008-01-14 01:17:44 +00001625 return false;
Gabor Greifa75ed762010-07-12 14:13:15 +00001626 }
1627
David Greene44cb8ad2010-01-05 01:28:05 +00001628 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001629
Chris Lattner40e4cec2004-12-12 05:53:50 +00001630 // Create the new global, initializing it to false.
Chris Lattner46b5c642009-11-06 04:27:31 +00001631 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1632 false,
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001633 GlobalValue::InternalLinkage,
Chris Lattner46b5c642009-11-06 04:27:31 +00001634 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky431f97e2009-05-03 03:49:08 +00001635 GV->getName()+".b",
Joey Gouly58bf9512013-01-10 10:31:11 +00001636 GV->getThreadLocalMode(),
1637 GV->getType()->getAddressSpace());
Chris Lattner40e4cec2004-12-12 05:53:50 +00001638 GV->getParent()->getGlobalList().insert(GV, NewGV);
1639
1640 Constant *InitVal = GV->getInitializer();
Chris Lattner46b5c642009-11-06 04:27:31 +00001641 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson55f1c092009-08-13 21:58:54 +00001642 "No reason to shrink to bool!");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001643
1644 // If initialized to zero and storing one into the global, we can use a cast
1645 // instead of a select to synthesize the desired value.
1646 bool IsOneZero = false;
1647 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencer2e54a152007-03-02 00:28:52 +00001648 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001649
1650 while (!GV->use_empty()) {
Devang Patelfc507a12009-03-06 01:39:36 +00001651 Instruction *UI = cast<Instruction>(GV->use_back());
1652 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001653 // Change the store into a boolean store.
1654 bool StoringOther = SI->getOperand(0) == OtherVal;
1655 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +00001656 Value *StoreVal;
Bill Wendling7297b862013-02-13 23:00:51 +00001657 if (StoringOther || SI->getOperand(0) == InitVal) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001658 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1659 StoringOther);
Bill Wendling7297b862013-02-13 23:00:51 +00001660 } else {
Chris Lattner745196a2004-12-12 19:34:41 +00001661 // Otherwise, we are storing a previously loaded copy. To do this,
1662 // change the copy from copying the original value to just copying the
1663 // bool.
1664 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1665
Gabor Greif218f5542010-06-24 14:42:01 +00001666 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner745196a2004-12-12 19:34:41 +00001667 // select instruction. If not, it will be a load of the original
1668 // global.
1669 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1670 assert(LI->getOperand(0) == GV && "Not a copy!");
1671 // Insert a new load, to preserve the saved value.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001672 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1673 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner745196a2004-12-12 19:34:41 +00001674 } else {
1675 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1676 "This is not a form that we understand!");
1677 StoreVal = StoredVal->getOperand(0);
1678 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1679 }
1680 }
Nick Lewycky52da72b2012-02-05 19:56:38 +00001681 new StoreInst(StoreVal, NewGV, false, 0,
1682 SI->getOrdering(), SI->getSynchScope(), SI);
Devang Patelfc507a12009-03-06 01:39:36 +00001683 } else {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001684 // Change the load into a load of bool then a select.
Devang Patelfc507a12009-03-06 01:39:36 +00001685 LoadInst *LI = cast<LoadInst>(UI);
Nick Lewycky52da72b2012-02-05 19:56:38 +00001686 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1687 LI->getOrdering(), LI->getSynchScope(), LI);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001688 Value *NSI;
1689 if (IsOneZero)
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001690 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001691 else
Gabor Greife9ecc682008-04-06 20:25:17 +00001692 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00001693 NSI->takeName(LI);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001694 LI->replaceAllUsesWith(NSI);
Devang Patelfc507a12009-03-06 01:39:36 +00001695 }
1696 UI->eraseFromParent();
Chris Lattner40e4cec2004-12-12 05:53:50 +00001697 }
1698
Bill Wendling7297b862013-02-13 23:00:51 +00001699 // Retain the name of the old global variable. People who are debugging their
1700 // programs may expect these variables to be named the same.
1701 NewGV->takeName(GV);
Chris Lattner40e4cec2004-12-12 05:53:50 +00001702 GV->eraseFromParent();
Chris Lattner20bbac32008-01-14 01:17:44 +00001703 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001704}
1705
1706
Nick Lewycky1480f1d2012-02-12 00:52:26 +00001707/// ProcessGlobal - Analyze the specified global variable and optimize it if
1708/// possible. If we make a change, return true.
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001709bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1710 Module::global_iterator &GVI) {
Rafael Espindoladef1b092012-06-14 22:48:13 +00001711 if (!GV->isDiscardableIfUnused())
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001712 return false;
1713
1714 // Do more involved optimizations if the global is internal.
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001715 GV->removeDeadConstantUsers();
1716
1717 if (GV->use_empty()) {
David Greene44cb8ad2010-01-05 01:28:05 +00001718 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001719 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001720 ++NumDeleted;
1721 return true;
1722 }
1723
Rafael Espindola1821c6c2012-06-15 18:00:24 +00001724 if (!GV->hasLocalLinkage())
1725 return false;
1726
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001727 GlobalStatus GS;
1728
Rafael Espindola3d7fc252013-10-21 17:14:55 +00001729 if (GlobalStatus::analyzeGlobal(GV, GS))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001730 return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001731
Rafael Espindola045a78f2013-10-17 18:18:52 +00001732 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001733 GV->setUnnamedAddr(true);
1734 NumUnnamed++;
1735 }
1736
1737 if (GV->isConstant() || !GV->hasInitializer())
1738 return false;
1739
Rafael Espindolad21ac192013-09-05 19:15:21 +00001740 return ProcessInternalGlobal(GV, GVI, GS);
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001741}
1742
1743/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1744/// it if possible. If we make a change, return true.
1745bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1746 Module::global_iterator &GVI,
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001747 const GlobalStatus &GS) {
Alexey Samsonova1944e62013-10-07 19:03:24 +00001748 // If this is a first class global and has only one accessing function
1749 // and this function is main (which we know is not recursive), we replace
1750 // the global with a local alloca in this function.
1751 //
Alp Tokerf907b892013-12-05 05:44:44 +00001752 // NOTE: It doesn't make sense to promote non-single-value types since we
Alexey Samsonova1944e62013-10-07 19:03:24 +00001753 // are just replacing static memory to stack memory.
1754 //
1755 // If the global is in different address space, don't bring it to stack.
1756 if (!GS.HasMultipleAccessingFunctions &&
1757 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1758 GV->getType()->getElementType()->isSingleValueType() &&
1759 GS.AccessingFunction->getName() == "main" &&
1760 GS.AccessingFunction->hasExternalLinkage() &&
1761 GV->getType()->getAddressSpace() == 0) {
1762 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1763 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1764 ->getEntryBlock().begin());
1765 Type *ElemTy = GV->getType()->getElementType();
1766 // FIXME: Pass Global's alignment when globals have alignment
1767 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1768 if (!isa<UndefValue>(GV->getInitializer()))
1769 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1770
1771 GV->replaceAllUsesWith(Alloca);
1772 GV->eraseFromParent();
1773 ++NumLocalized;
1774 return true;
1775 }
1776
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001777 // If the global is never loaded (but may be stored to), it is dead.
1778 // Delete it now.
Rafael Espindola045a78f2013-10-17 18:18:52 +00001779 if (!GS.IsLoaded) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001780 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1781
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001782 bool Changed;
1783 if (isLeakCheckerRoot(GV)) {
1784 // Delete any constant stores to the global.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001785 Changed = CleanupPointerRootUsers(GV, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001786 } else {
1787 // Delete any stores we can find to the global. We may not be able to
1788 // make it completely dead though.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001789 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001790 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001791
1792 // If the global is dead now, delete it.
1793 if (GV->use_empty()) {
1794 GV->eraseFromParent();
1795 ++NumDeleted;
1796 Changed = true;
1797 }
1798 return Changed;
1799
Rafael Espindola045a78f2013-10-17 18:18:52 +00001800 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00001801 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001802 GV->setConstant(true);
1803
1804 // Clean up any obviously simplifiable users now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001805 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001806
1807 // If the global is dead now, just nuke it.
1808 if (GV->use_empty()) {
1809 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1810 << "all users and delete global!\n");
1811 GV->eraseFromParent();
1812 ++NumDeleted;
1813 }
1814
1815 ++NumMarked;
1816 return true;
1817 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Rafael Espindola93512512014-02-25 17:30:31 +00001818 if (DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>()) {
1819 const DataLayout &DL = DLP->getDataLayout();
1820 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001821 GVI = FirstNewGV; // Don't skip the newly produced globals!
1822 return true;
1823 }
Rafael Espindola93512512014-02-25 17:30:31 +00001824 }
Rafael Espindola045a78f2013-10-17 18:18:52 +00001825 } else if (GS.StoredType == GlobalStatus::StoredOnce) {
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001826 // If the initial value for the global was an undef value, and if only
1827 // one other value was stored into it, we can just change the
1828 // initializer to be the stored value, then delete all stores to the
1829 // global. This allows us to mark it constant.
1830 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1831 if (isa<UndefValue>(GV->getInitializer())) {
1832 // Change the initial value here.
1833 GV->setInitializer(SOVConstant);
1834
1835 // Clean up any obviously simplifiable users now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001836 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001837
1838 if (GV->use_empty()) {
1839 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
Nick Lewyckyfaa9c3b02012-07-24 07:21:08 +00001840 << "simplify all users and delete global!\n");
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001841 GV->eraseFromParent();
1842 ++NumDeleted;
1843 } else {
1844 GVI = GV;
1845 }
1846 ++NumSubstitute;
1847 return true;
1848 }
1849
1850 // Try to optimize globals based on the knowledge that only one value
1851 // (besides its initializer) is ever stored to the global.
Nick Lewycky52da72b2012-02-05 19:56:38 +00001852 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001853 DL, TLI))
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001854 return true;
1855
1856 // Otherwise, if the global was not a boolean, we can shrink it to be a
1857 // boolean.
Eli Friedman33d37002013-09-09 22:00:13 +00001858 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1859 if (GS.Ordering == NotAtomic) {
1860 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1861 ++NumShrunkToBool;
1862 return true;
1863 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001864 }
Eli Friedman33d37002013-09-09 22:00:13 +00001865 }
Rafael Espindolaecd5b9a2011-01-18 04:36:06 +00001866 }
1867
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001868 return false;
1869}
1870
Chris Lattnera4c80222005-05-08 22:18:06 +00001871/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1872/// function, changing them to FastCC.
1873static void ChangeCalleesToFastCall(Function *F) {
1874 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadca0c4992012-05-12 08:30:16 +00001875 if (isa<BlockAddress>(*UI))
1876 continue;
Duncan Sands85fab3a2008-02-18 17:32:13 +00001877 CallSite User(cast<Instruction>(*UI));
1878 User.setCallingConv(CallingConv::Fast);
Chris Lattnera4c80222005-05-08 22:18:06 +00001879 }
1880}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001881
Bill Wendlinge94d8432012-12-07 23:16:57 +00001882static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
Chris Lattner8a923e72008-03-12 17:45:29 +00001883 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Bill Wendling57625a42013-01-25 23:09:36 +00001884 unsigned Index = Attrs.getSlotIndex(i);
1885 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
Duncan Sands85fab3a2008-02-18 17:32:13 +00001886 continue;
1887
Duncan Sands85fab3a2008-02-18 17:32:13 +00001888 // There can be only one.
Bill Wendling57625a42013-01-25 23:09:36 +00001889 return Attrs.removeAttribute(C, Index, Attribute::Nest);
Duncan Sands573b3f82008-02-16 20:56:04 +00001890 }
1891
1892 return Attrs;
1893}
1894
1895static void RemoveNestAttribute(Function *F) {
Bill Wendling85a64c22012-10-14 06:39:53 +00001896 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001897 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Jay Foadca0c4992012-05-12 08:30:16 +00001898 if (isa<BlockAddress>(*UI))
1899 continue;
Duncan Sands85fab3a2008-02-18 17:32:13 +00001900 CallSite User(cast<Instruction>(*UI));
Bill Wendling85a64c22012-10-14 06:39:53 +00001901 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
Duncan Sands573b3f82008-02-16 20:56:04 +00001902 }
1903}
1904
Reid Kleckner22869372014-02-26 19:57:30 +00001905/// Return true if this is a calling convention that we'd like to change. The
1906/// idea here is that we don't want to mess with the convention if the user
1907/// explicitly requested something with performance implications like coldcc,
1908/// GHC, or anyregcc.
1909static bool isProfitableToMakeFastCC(Function *F) {
1910 CallingConv::ID CC = F->getCallingConv();
1911 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
1912 return CC == CallingConv::C || CC == CallingConv::X86_ThisCall;
1913}
1914
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001915bool GlobalOpt::OptimizeFunctions(Module &M) {
1916 bool Changed = false;
1917 // Optimize functions.
1918 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1919 Function *F = FI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001920 // Functions without names cannot be referenced outside this module.
1921 if (!F->hasName() && !F->isDeclaration())
1922 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001923 F->removeDeadConstantUsers();
Eli Friedman1923a332011-10-20 05:23:42 +00001924 if (F->isDefTriviallyDead()) {
Chris Lattnerb5d9c8c2009-11-01 19:03:42 +00001925 F->eraseFromParent();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001926 Changed = true;
1927 ++NumFnDeleted;
Rafael Espindola6de96a12009-01-15 20:18:42 +00001928 } else if (F->hasLocalLinkage()) {
Reid Kleckner22869372014-02-26 19:57:30 +00001929 if (isProfitableToMakeFastCC(F) && !F->isVarArg() && !F->hasAddressTaken()) {
1930 // If this function has a calling convention worth changing, is not a
1931 // varargs function, and is only called directly, promote it to use the
1932 // Fast calling convention.
Duncan Sands573b3f82008-02-16 20:56:04 +00001933 F->setCallingConv(CallingConv::Fast);
1934 ChangeCalleesToFastCall(F);
1935 ++NumFastCallFns;
1936 Changed = true;
1937 }
1938
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001939 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad557169d2009-06-10 08:41:11 +00001940 !F->hasAddressTaken()) {
Duncan Sands573b3f82008-02-16 20:56:04 +00001941 // The function is not used by a trampoline intrinsic, so it is safe
1942 // to remove the 'nest' attribute.
1943 RemoveNestAttribute(F);
1944 ++NumNestRemoved;
1945 Changed = true;
1946 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001947 }
1948 }
1949 return Changed;
1950}
1951
1952bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1953 bool Changed = false;
1954 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1955 GVI != E; ) {
1956 GlobalVariable *GV = GVI++;
Duncan Sandsed722832009-03-06 10:21:56 +00001957 // Global variables without names cannot be referenced outside this module.
1958 if (!GV->hasName() && !GV->isDeclaration())
1959 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman580b80d2009-11-23 16:22:21 +00001960 // Simplify the initializer.
1961 if (GV->hasInitializer())
1962 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001963 Constant *New = ConstantFoldConstantExpression(CE, DL, TLI);
Dan Gohman580b80d2009-11-23 16:22:21 +00001964 if (New && New != CE)
1965 GV->setInitializer(New);
1966 }
Rafael Espindolafc355bc2011-01-19 16:32:21 +00001967
1968 Changed |= ProcessGlobal(GV, GVI);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001969 }
1970 return Changed;
1971}
1972
Nick Lewycky466d0c12011-04-08 07:30:21 +00001973/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001974/// initializers have an init priority of 65535.
1975GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001976 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1977 if (GV == 0) return 0;
Jakub Staszak9525a772012-12-06 21:57:16 +00001978
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001979 // Verify that the initializer is simple enough for us to handle. We are
1980 // only allowed to optimize the initializer if it is unique.
1981 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky0f857892011-04-11 22:11:20 +00001982
1983 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1984 return GV;
1985 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman9cca0712011-04-09 09:11:09 +00001986
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001987 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky0f857892011-04-11 22:11:20 +00001988 if (isa<ConstantAggregateZero>(*i))
1989 continue;
1990 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001991 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1992 continue;
Chris Lattner838bdc12005-09-26 02:19:27 +00001993
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001994 // Must have a function or null ptr.
1995 if (!isa<Function>(CS->getOperand(1)))
1996 return 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00001997
Chris Lattner7ff0ba42010-12-06 21:53:07 +00001998 // Init priority must be standard.
Nick Lewycky466d0c12011-04-08 07:30:21 +00001999 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2000 if (CI->getZExtValue() != 65535)
Chris Lattner7ff0ba42010-12-06 21:53:07 +00002001 return 0;
2002 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002003
Chris Lattner7ff0ba42010-12-06 21:53:07 +00002004 return GV;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002005}
2006
Chris Lattner696beef2005-09-26 02:31:18 +00002007/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2008/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002009static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky0f857892011-04-11 22:11:20 +00002010 if (GV->getInitializer()->isNullValue())
2011 return std::vector<Function*>();
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002012 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2013 std::vector<Function*> Result;
2014 Result.reserve(CA->getNumOperands());
Gabor Greif3a9fba52008-05-29 01:59:18 +00002015 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2016 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002017 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2018 }
2019 return Result;
2020}
2021
Chris Lattner696beef2005-09-26 02:31:18 +00002022/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2023/// specified array, returning the new global to use.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002024static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner46b5c642009-11-06 04:27:31 +00002025 const std::vector<Function*> &Ctors) {
Chris Lattner696beef2005-09-26 02:31:18 +00002026 // If we made a change, reassemble the initializer list.
Chris Lattnercc19efa2011-06-20 04:01:31 +00002027 Constant *CSVals[2];
2028 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2029 CSVals[1] = 0;
2030
Chris Lattner229907c2011-07-18 04:54:35 +00002031 StructType *StructTy =
Matt Arsenault404c60a2013-10-21 19:43:56 +00002032 cast<StructType>(GCL->getType()->getElementType()->getArrayElementType());
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002033
Chris Lattner696beef2005-09-26 02:31:18 +00002034 // Create the new init list.
2035 std::vector<Constant*> CAList;
2036 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002037 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00002038 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00002039 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002040 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner46b5c642009-11-06 04:27:31 +00002041 false);
Chris Lattner229907c2011-07-18 04:54:35 +00002042 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Anderson5a1acd92009-07-31 20:28:14 +00002043 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner46b5c642009-11-06 04:27:31 +00002044 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky0f857892011-04-11 22:11:20 +00002045 0x7fffffff);
Chris Lattner696beef2005-09-26 02:31:18 +00002046 }
Chris Lattnercc19efa2011-06-20 04:01:31 +00002047 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattner696beef2005-09-26 02:31:18 +00002048 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002049
Chris Lattner696beef2005-09-26 02:31:18 +00002050 // Create the array initializer.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002051 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewycky1303c0a2009-09-19 20:30:26 +00002052 CAList.size()), CAList);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002053
Chris Lattner696beef2005-09-26 02:31:18 +00002054 // If we didn't change the number of elements, don't create a new GV.
2055 if (CA->getType() == GCL->getInitializer()->getType()) {
2056 GCL->setInitializer(CA);
2057 return GCL;
2058 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002059
Chris Lattner696beef2005-09-26 02:31:18 +00002060 // Create the new global and insert it next to the existing list.
Chris Lattner46b5c642009-11-06 04:27:31 +00002061 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +00002062 GCL->getLinkage(), CA, "",
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002063 GCL->getThreadLocalMode());
Chris Lattner696beef2005-09-26 02:31:18 +00002064 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner8d4c36b2007-02-11 01:08:35 +00002065 NGV->takeName(GCL);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002066
Chris Lattner696beef2005-09-26 02:31:18 +00002067 // Nuke the old list, replacing any uses with the new one.
2068 if (!GCL->use_empty()) {
2069 Constant *V = NGV;
2070 if (V->getType() != GCL->getType())
Owen Anderson487375e2009-07-29 18:55:55 +00002071 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattner696beef2005-09-26 02:31:18 +00002072 GCL->replaceAllUsesWith(V);
2073 }
2074 GCL->eraseFromParent();
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002075
Chris Lattner696beef2005-09-26 02:31:18 +00002076 if (Ctors.size())
2077 return NGV;
2078 else
2079 return 0;
2080}
Chris Lattner99e23fa2005-09-26 04:44:35 +00002081
2082
Jakub Staszak9525a772012-12-06 21:57:16 +00002083static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002084isSimpleEnoughValueToCommit(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002085 SmallPtrSet<Constant*, 8> &SimpleConstants,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002086 const DataLayout *DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002087
2088
2089/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2090/// handled by the code generator. We don't want to generate something like:
2091/// void *X = &X/42;
2092/// because the code generator doesn't have a relocation that can handle that.
2093///
2094/// This function should be called if C was not found (but just got inserted)
2095/// in SimpleConstants to avoid having to rescan the same constants all the
2096/// time.
2097static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002098 SmallPtrSet<Constant*, 8> &SimpleConstants,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002099 const DataLayout *DL) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002100 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2101 // all supported.
2102 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2103 isa<GlobalValue>(C))
2104 return true;
Jakub Staszak9525a772012-12-06 21:57:16 +00002105
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002106 // Aggregate values are safe if all their elements are.
2107 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2108 isa<ConstantVector>(C)) {
2109 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2110 Constant *Op = cast<Constant>(C->getOperand(i));
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002111 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, DL))
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002112 return false;
2113 }
2114 return true;
2115 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002116
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002117 // We don't know exactly what relocations are allowed in constant expressions,
2118 // so we allow &global+constantoffset, which is safe and uniformly supported
2119 // across targets.
2120 ConstantExpr *CE = cast<ConstantExpr>(C);
2121 switch (CE->getOpcode()) {
2122 case Instruction::BitCast:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002123 // Bitcast is fine if the casted value is fine.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002124 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Eli Friedman55fa49f32012-01-05 23:03:32 +00002125
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002126 case Instruction::IntToPtr:
2127 case Instruction::PtrToInt:
Eli Friedman55fa49f32012-01-05 23:03:32 +00002128 // int <=> ptr is fine if the int type is the same size as the
2129 // pointer type.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002130 if (!DL || DL->getTypeSizeInBits(CE->getType()) !=
2131 DL->getTypeSizeInBits(CE->getOperand(0)->getType()))
Eli Friedman55fa49f32012-01-05 23:03:32 +00002132 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002133 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Jakub Staszak9525a772012-12-06 21:57:16 +00002134
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002135 // GEP is fine if it is simple + constant offset.
2136 case Instruction::GetElementPtr:
2137 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2138 if (!isa<ConstantInt>(CE->getOperand(i)))
2139 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002140 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Jakub Staszak9525a772012-12-06 21:57:16 +00002141
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002142 case Instruction::Add:
2143 // We allow simple+cst.
2144 if (!isa<ConstantInt>(CE->getOperand(1)))
2145 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002146 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002147 }
2148 return false;
2149}
2150
Jakub Staszak9525a772012-12-06 21:57:16 +00002151static inline bool
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002152isSimpleEnoughValueToCommit(Constant *C,
Eli Friedman55fa49f32012-01-05 23:03:32 +00002153 SmallPtrSet<Constant*, 8> &SimpleConstants,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002154 const DataLayout *DL) {
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002155 // If we already checked this constant, we win.
2156 if (!SimpleConstants.insert(C)) return true;
2157 // Check the constant.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002158 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002159}
2160
2161
Chris Lattner99e23fa2005-09-26 04:44:35 +00002162/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002163/// enough for us to understand. In particular, if it is a cast to anything
2164/// other than from one pointer type to another pointer type, we punt.
2165/// We basically just support direct accesses to globals and GEP's of
Chris Lattner99e23fa2005-09-26 04:44:35 +00002166/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner46b5c642009-11-06 04:27:31 +00002167static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohman82e74752009-09-07 22:42:05 +00002168 // Conservatively, avoid aggregate types. This is because we don't
2169 // want to worry about them partially overlapping other stores.
2170 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2171 return false;
2172
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002173 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002174 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002175 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002176 return GV->hasUniqueInitializer();
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002177
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002178 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002179 // Handle a constantexpr gep.
2180 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanbeee35a2009-09-07 22:40:13 +00002181 isa<GlobalVariable>(CE->getOperand(0)) &&
2182 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002183 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002184 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002185 // external globals.
Mikhail Glushenkov2072db22010-10-19 16:47:23 +00002186 if (!GV->hasUniqueInitializer())
Dan Gohmanf7f3fb12009-09-07 22:31:26 +00002187 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002188
Dan Gohman161429f2009-09-07 22:44:55 +00002189 // The first index must be zero.
Oscar Fuentes40b31ad2010-08-02 06:00:15 +00002190 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman161429f2009-09-07 22:44:55 +00002191 if (!CI || !CI->isZero()) return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002192
2193 // The remaining indices must be compile-time known integers within the
Dan Gohman7190d482009-09-10 23:37:55 +00002194 // notional bounds of the corresponding static array types.
2195 if (!CE->isGEPWithNoNotionalOverIndexing())
2196 return false;
Dan Gohman161429f2009-09-07 22:44:55 +00002197
Dan Gohmane525d9d2009-10-05 16:36:26 +00002198 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Jakub Staszak9525a772012-12-06 21:57:16 +00002199
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002200 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2201 // and we know how to evaluate it by moving the bitcast from the pointer
2202 // operand to the value operand.
2203 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner8b4952f2011-01-16 02:05:10 +00002204 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002205 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2206 // external globals.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002207 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner46af55e2005-09-26 06:52:44 +00002208 }
Owen Anderson3e2f6cf2011-01-14 22:31:13 +00002209 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002210
Chris Lattner99e23fa2005-09-26 04:44:35 +00002211 return false;
2212}
2213
Chris Lattner46af55e2005-09-26 06:52:44 +00002214/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2215/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2216/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2217static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002218 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002219 // Base case of the recursion.
2220 if (OpNo == Addr->getNumOperands()) {
2221 assert(Val->getType() == Init->getType() && "Type mismatch!");
2222 return Val;
2223 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002224
Chris Lattner0256be92012-01-27 03:08:05 +00002225 SmallVector<Constant*, 32> Elts;
Chris Lattner229907c2011-07-18 04:54:35 +00002226 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002227 // Break up the constant into its elements.
Chris Lattnerfa775002012-01-26 02:32:04 +00002228 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2229 Elts.push_back(Init->getAggregateElement(i));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002230
Chris Lattner46af55e2005-09-26 06:52:44 +00002231 // Replace the element that we are supposed to.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002232 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2233 unsigned Idx = CU->getZExtValue();
2234 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002235 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002236
Chris Lattner46af55e2005-09-26 06:52:44 +00002237 // Return the modified struct.
Chris Lattnercc19efa2011-06-20 04:01:31 +00002238 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002239 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002240
Chris Lattnercc19efa2011-06-20 04:01:31 +00002241 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattner229907c2011-07-18 04:54:35 +00002242 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnercc19efa2011-06-20 04:01:31 +00002243
2244 uint64_t NumElts;
Chris Lattner229907c2011-07-18 04:54:35 +00002245 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnercc19efa2011-06-20 04:01:31 +00002246 NumElts = ATy->getNumElements();
2247 else
Chris Lattnerfa775002012-01-26 02:32:04 +00002248 NumElts = InitTy->getVectorNumElements();
Chris Lattnercc19efa2011-06-20 04:01:31 +00002249
2250 // Break up the array into elements.
Chris Lattnerfa775002012-01-26 02:32:04 +00002251 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2252 Elts.push_back(Init->getAggregateElement(i));
Chris Lattnercc19efa2011-06-20 04:01:31 +00002253
2254 assert(CI->getZExtValue() < NumElts);
2255 Elts[CI->getZExtValue()] =
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002256 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattnercc19efa2011-06-20 04:01:31 +00002257
2258 if (Init->getType()->isArrayTy())
2259 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2260 return ConstantVector::get(Elts);
Chris Lattner46af55e2005-09-26 06:52:44 +00002261}
2262
Chris Lattner99e23fa2005-09-26 04:44:35 +00002263/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2264/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner46b5c642009-11-06 04:27:31 +00002265static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00002266 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2267 assert(GV->hasInitializer());
2268 GV->setInitializer(Val);
2269 return;
2270 }
Chris Lattner64ecc462010-01-07 01:16:21 +00002271
Chris Lattner46af55e2005-09-26 06:52:44 +00002272 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2273 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Zhou Sheng8e6d64a2012-12-01 10:54:28 +00002274 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner99e23fa2005-09-26 04:44:35 +00002275}
2276
Nick Lewycky60829a582012-02-20 03:25:59 +00002277namespace {
2278
2279/// Evaluator - This class evaluates LLVM IR, producing the Constant
2280/// representing each SSA instruction. Changes to global variables are stored
2281/// in a mapping that can be iterated over after the evaluation is complete.
2282/// Once an evaluation call fails, the evaluation object should not be reused.
2283class Evaluator {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002284public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002285 Evaluator(const DataLayout *DL, const TargetLibraryInfo *TLI)
2286 : DL(DL), TLI(TLI) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002287 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2288 }
2289
Nick Lewycky60829a582012-02-20 03:25:59 +00002290 ~Evaluator() {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002291 DeleteContainerPointers(ValueStack);
2292 while (!AllocaTmps.empty()) {
2293 GlobalVariable *Tmp = AllocaTmps.back();
2294 AllocaTmps.pop_back();
2295
2296 // If there are still users of the alloca, the program is doing something
2297 // silly, e.g. storing the address of the alloca somewhere and using it
2298 // later. Since this is undefined, we'll just make it be null.
2299 if (!Tmp->use_empty())
2300 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2301 delete Tmp;
2302 }
2303 }
2304
2305 /// EvaluateFunction - Evaluate a call to function F, returning true if
2306 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2307 /// arguments for the function.
2308 bool EvaluateFunction(Function *F, Constant *&RetVal,
2309 const SmallVectorImpl<Constant*> &ActualArgs);
2310
2311 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2312 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2313 /// control flows into, or null upon return.
2314 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2315
2316 Constant *getVal(Value *V) {
2317 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2318 Constant *R = ValueStack.back()->lookup(V);
2319 assert(R && "Reference to an uncomputed value!");
2320 return R;
2321 }
2322
2323 void setVal(Value *V, Constant *C) {
2324 ValueStack.back()->operator[](V) = C;
2325 }
2326
2327 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2328 return MutatedMemory;
2329 }
2330
2331 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2332 return Invariants;
2333 }
2334
2335private:
2336 Constant *ComputeLoadResult(Constant *P);
2337
2338 /// ValueStack - As we compute SSA register values, we store their contents
2339 /// here. The back of the vector contains the current function and the stack
2340 /// contains the values in the calling frames.
2341 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2342
2343 /// CallStack - This is used to detect recursion. In pathological situations
2344 /// we could hit exponential behavior, but at least there is nothing
2345 /// unbounded.
2346 SmallVector<Function*, 4> CallStack;
2347
2348 /// MutatedMemory - For each store we execute, we update this map. Loads
2349 /// check this to get the most up-to-date value. If evaluation is successful,
2350 /// this state is committed to the process.
2351 DenseMap<Constant*, Constant*> MutatedMemory;
2352
2353 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2354 /// to represent its body. This vector is needed so we can delete the
2355 /// temporary globals when we are done.
2356 SmallVector<GlobalVariable*, 32> AllocaTmps;
2357
2358 /// Invariants - These global variables have been marked invariant by the
2359 /// static constructor.
2360 SmallPtrSet<GlobalVariable*, 8> Invariants;
2361
2362 /// SimpleConstants - These are constants we have checked and know to be
2363 /// simple enough to live in a static initializer of a global.
2364 SmallPtrSet<Constant*, 8> SimpleConstants;
2365
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002366 const DataLayout *DL;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002367 const TargetLibraryInfo *TLI;
2368};
2369
Nick Lewycky60829a582012-02-20 03:25:59 +00002370} // anonymous namespace
2371
Chris Lattnerb0096632005-09-26 05:16:34 +00002372/// ComputeLoadResult - Return the value that would be computed by a load from
2373/// P after the stores reflected by 'memory' have been performed. If we can't
2374/// decide, return null.
Nick Lewycky60829a582012-02-20 03:25:59 +00002375Constant *Evaluator::ComputeLoadResult(Constant *P) {
Chris Lattner4b05c322005-09-26 05:15:37 +00002376 // If this memory location has been recently stored, use the stored value: it
2377 // is the most up-to-date.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002378 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2379 if (I != MutatedMemory.end()) return I->second;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002380
Chris Lattner4b05c322005-09-26 05:15:37 +00002381 // Access it.
2382 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002383 if (GV->hasDefinitiveInitializer())
Chris Lattner4b05c322005-09-26 05:15:37 +00002384 return GV->getInitializer();
2385 return 0;
Chris Lattner4b05c322005-09-26 05:15:37 +00002386 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002387
Chris Lattner46af55e2005-09-26 06:52:44 +00002388 // Handle a constantexpr getelementptr.
2389 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2390 if (CE->getOpcode() == Instruction::GetElementPtr &&
2391 isa<GlobalVariable>(CE->getOperand(0))) {
2392 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002393 if (GV->hasDefinitiveInitializer())
Dan Gohmane525d9d2009-10-05 16:36:26 +00002394 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner46af55e2005-09-26 06:52:44 +00002395 }
2396
2397 return 0; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00002398}
2399
Nick Lewycky239fdf02012-02-06 08:24:44 +00002400/// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2401/// successful, false if we can't evaluate it. NewBB returns the next BB that
2402/// control flows into, or null upon return.
Nick Lewycky60829a582012-02-20 03:25:59 +00002403bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2404 BasicBlock *&NextBB) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002405 // This is the main evaluation loop.
2406 while (1) {
2407 Constant *InstResult = 0;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002408
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002409 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2410
Chris Lattner99e23fa2005-09-26 04:44:35 +00002411 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002412 if (!SI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002413 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2414 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002415 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002416 Constant *Ptr = getVal(SI->getOperand(1));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002417 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002418 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002419 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002420 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002421 }
2422 if (!isSimpleEnoughPointerToCommit(Ptr)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002423 // If this is too complex for us to commit, reject it.
Michael Gottesman2a654272013-01-11 23:08:52 +00002424 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002425 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002426 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002427
Nick Lewycky73be5e32012-02-19 23:26:27 +00002428 Constant *Val = getVal(SI->getOperand(0));
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002429
2430 // If this might be too difficult for the backend to handle (e.g. the addr
2431 // of one global variable divided by another) then we can't commit it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002432 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002433 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2434 << "\n");
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002435 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002436 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002437
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002438 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002439 if (CE->getOpcode() == Instruction::BitCast) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002440 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002441 // If we're evaluating a store through a bitcast, then we need
2442 // to pull the bitcast off the pointer type and push it onto the
2443 // stored value.
Chris Lattner8b4952f2011-01-16 02:05:10 +00002444 Ptr = CE->getOperand(0);
Jakub Staszak9525a772012-12-06 21:57:16 +00002445
Nick Lewycky239fdf02012-02-06 08:24:44 +00002446 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
Jakub Staszak9525a772012-12-06 21:57:16 +00002447
Owen Anderson4e54efd2011-01-16 04:33:33 +00002448 // In order to push the bitcast onto the stored value, a bitcast
2449 // from NewTy to Val's type must be legal. If it's not, we can try
2450 // introspecting NewTy to find a legal conversion.
2451 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2452 // If NewTy is a struct, we can convert the pointer to the struct
2453 // into a pointer to its first member.
2454 // FIXME: This could be extended to support arrays as well.
Chris Lattner229907c2011-07-18 04:54:35 +00002455 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson4e54efd2011-01-16 04:33:33 +00002456 NewTy = STy->getTypeAtIndex(0U);
2457
Nick Lewycky239fdf02012-02-06 08:24:44 +00002458 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
Owen Anderson4e54efd2011-01-16 04:33:33 +00002459 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2460 Constant * const IdxList[] = {IdxZero, IdxZero};
2461
Jay Foad17bab442011-07-22 08:52:50 +00002462 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002463 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002464 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Nick Lewycky9d0da182012-02-21 22:08:06 +00002465
Owen Anderson4e54efd2011-01-16 04:33:33 +00002466 // If we can't improve the situation by introspecting NewTy,
2467 // we have to give up.
2468 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002469 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2470 "evaluate.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002471 return false;
Owen Anderson4e54efd2011-01-16 04:33:33 +00002472 }
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002473 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002474
Owen Anderson4e54efd2011-01-16 04:33:33 +00002475 // If we found compatible types, go ahead and push the bitcast
2476 // onto the stored value.
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002477 Val = ConstantExpr::getBitCast(Val, NewTy);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002478
Michael Gottesman2a654272013-01-11 23:08:52 +00002479 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Owen Anderson9eb7cb482011-01-14 22:19:20 +00002480 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002481 }
Jakub Staszak9525a772012-12-06 21:57:16 +00002482
Chris Lattner99e23fa2005-09-26 04:44:35 +00002483 MutatedMemory[Ptr] = Val;
2484 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002485 InstResult = ConstantExpr::get(BO->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002486 getVal(BO->getOperand(0)),
2487 getVal(BO->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002488 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002489 << "\n");
Reid Spencer266e42b2006-12-23 06:05:41 +00002490 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002491 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002492 getVal(CI->getOperand(0)),
2493 getVal(CI->getOperand(1)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002494 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002495 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002496 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson487375e2009-07-29 18:55:55 +00002497 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Nick Lewycky73be5e32012-02-19 23:26:27 +00002498 getVal(CI->getOperand(0)),
Chris Lattner99e23fa2005-09-26 04:44:35 +00002499 CI->getType());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002500 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002501 << "\n");
Chris Lattner99e23fa2005-09-26 04:44:35 +00002502 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002503 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2504 getVal(SI->getOperand(1)),
2505 getVal(SI->getOperand(2)));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002506 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002507 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002508 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002509 Constant *P = getVal(GEP->getOperand(0));
Chris Lattnerf96f4a82007-01-31 04:40:53 +00002510 SmallVector<Constant*, 8> GEPOps;
Gabor Greif3a9fba52008-05-29 01:59:18 +00002511 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2512 i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002513 GEPOps.push_back(getVal(*i));
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002514 InstResult =
2515 ConstantExpr::getGetElementPtr(P, GEPOps,
2516 cast<GEPOperator>(GEP)->isInBounds());
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002517 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
Michael Gottesman2a654272013-01-11 23:08:52 +00002518 << "\n");
Chris Lattner4b05c322005-09-26 05:15:37 +00002519 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002520
2521 if (!LI->isSimple()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002522 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2523 return false; // no volatile/atomic accesses.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002524 }
2525
Nick Lewycky9d0da182012-02-21 22:08:06 +00002526 Constant *Ptr = getVal(LI->getOperand(0));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002527 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002528 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
Michael Gottesman2a654272013-01-11 23:08:52 +00002529 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2530 "folding: " << *Ptr << "\n");
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002531 }
Nick Lewycky9d0da182012-02-21 22:08:06 +00002532 InstResult = ComputeLoadResult(Ptr);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002533 if (InstResult == 0) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002534 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2535 "\n");
2536 return false; // Could not evaluate load.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002537 }
2538
2539 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002540 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002541 if (AI->isArrayAllocation()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002542 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2543 return false; // Cannot handle array allocs.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002544 }
Chris Lattner229907c2011-07-18 04:54:35 +00002545 Type *Ty = AI->getType()->getElementType();
Chris Lattner46b5c642009-11-06 04:27:31 +00002546 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002547 GlobalValue::InternalLinkage,
Owen Andersonb292b8c2009-07-30 23:03:37 +00002548 UndefValue::get(Ty),
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002549 AI->getName()));
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002550 InstResult = AllocaTmps.back();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002551 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002552 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2553 CallSite CS(CurInst);
Devang Patel04852aa2009-03-09 23:04:12 +00002554
2555 // Debug info can safely be ignored here.
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002556 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002557 DEBUG(dbgs() << "Ignoring debug info.\n");
Devang Patel04852aa2009-03-09 23:04:12 +00002558 ++CurInst;
2559 continue;
2560 }
2561
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002562 // Cannot handle inline asm.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002563 if (isa<InlineAsm>(CS.getCalledValue())) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002564 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2565 return false;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002566 }
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00002567
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002568 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2569 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002570 if (MSI->isVolatile()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002571 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2572 "intrinsic.\n");
2573 return false;
2574 }
Nick Lewycky73be5e32012-02-19 23:26:27 +00002575 Constant *Ptr = getVal(MSI->getDest());
2576 Constant *Val = getVal(MSI->getValue());
2577 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002578 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2579 // This memset is a no-op.
Michael Gottesman2a654272013-01-11 23:08:52 +00002580 DEBUG(dbgs() << "Ignoring no-op memset.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002581 ++CurInst;
2582 continue;
2583 }
2584 }
2585
2586 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2587 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002588 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002589 ++CurInst;
2590 continue;
2591 }
2592
2593 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2594 // We don't insert an entry into Values, as it doesn't have a
2595 // meaningful return value.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002596 if (!II->use_empty()) {
Alp Tokerf907b892013-12-05 05:44:44 +00002597 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002598 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002599 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002600 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
Nick Lewycky519561f2012-02-20 23:32:26 +00002601 Value *PtrArg = getVal(II->getArgOperand(1));
2602 Value *Ptr = PtrArg->stripPointerCasts();
2603 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2604 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002605 if (DL && !Size->isAllOnesValue() &&
Nick Lewycky519561f2012-02-20 23:32:26 +00002606 Size->getValue().getLimitedValue() >=
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002607 DL->getTypeStoreSize(ElemTy)) {
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002608 Invariants.insert(GV);
Michael Gottesman2a654272013-01-11 23:08:52 +00002609 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2610 << "\n");
2611 } else {
2612 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2613 "invariant.\n");
2614 }
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002615 }
2616 // Continue even if we do nothing.
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002617 ++CurInst;
2618 continue;
2619 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002620
Michael Gottesman2a654272013-01-11 23:08:52 +00002621 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Nick Lewyckya3bb03e2011-05-29 18:41:56 +00002622 return false;
2623 }
2624
Chris Lattner65a3a092005-09-27 04:45:34 +00002625 // Resolve function pointers.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002626 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002627 if (!Callee || Callee->mayBeOverridden()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002628 DEBUG(dbgs() << "Can not resolve function pointer.\n");
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002629 return false; // Cannot resolve.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002630 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002631
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002632 SmallVector<Constant*, 8> Formals;
Nick Lewyckyc1572e42012-02-12 05:09:35 +00002633 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002634 Formals.push_back(getVal(*i));
Duncan Sandsc4ce58d82009-08-17 14:33:27 +00002635
Reid Spencer5301e7c2007-01-30 20:08:39 +00002636 if (Callee->isDeclaration()) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002637 // If this is a function we can constant fold, do it.
Chad Rosiere6de63d2011-12-01 21:29:16 +00002638 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002639 InstResult = C;
Michael Gottesman2a654272013-01-11 23:08:52 +00002640 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2641 *InstResult << "\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002642 } else {
Michael Gottesman2a654272013-01-11 23:08:52 +00002643 DEBUG(dbgs() << "Can not constant fold function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002644 return false;
2645 }
2646 } else {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002647 if (Callee->getFunctionType()->isVarArg()) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002648 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002649 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002650 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002651
Benjamin Kramer64a857a2013-01-12 15:34:31 +00002652 Constant *RetVal = 0;
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002653 // Execute the call, if successful, use the return value.
Nick Lewycky73be5e32012-02-19 23:26:27 +00002654 ValueStack.push_back(new DenseMap<Value*, Constant*>);
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002655 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Michael Gottesman2a654272013-01-11 23:08:52 +00002656 DEBUG(dbgs() << "Failed to evaluate function.\n");
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002657 return false;
Michael Gottesman2a654272013-01-11 23:08:52 +00002658 }
Benjamin Kramer93887632012-02-27 12:48:24 +00002659 delete ValueStack.pop_back_val();
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002660 InstResult = RetVal;
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002661
Michael Gottesman2a654272013-01-11 23:08:52 +00002662 if (InstResult != NULL) {
2663 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2664 InstResult << "\n\n");
2665 } else {
2666 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2667 }
Chris Lattner3d27e7f2005-09-27 05:02:43 +00002668 }
Reid Spencerde46e482006-11-02 20:25:50 +00002669 } else if (isa<TerminatorInst>(CurInst)) {
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002670 DEBUG(dbgs() << "Found a terminator instruction.\n");
2671
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002672 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2673 if (BI->isUnconditional()) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002674 NextBB = BI->getSuccessor(0);
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002675 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002676 ConstantInt *Cond =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002677 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
Chris Lattner15649082007-01-12 18:30:11 +00002678 if (!Cond) return false; // Cannot determine.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002679
Nick Lewycky239fdf02012-02-06 08:24:44 +00002680 NextBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002681 }
2682 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2683 ConstantInt *Val =
Nick Lewycky73be5e32012-02-19 23:26:27 +00002684 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00002685 if (!Val) return false; // Cannot determine.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002686 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
Chris Lattner31274882009-10-29 05:51:50 +00002687 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
Nick Lewycky73be5e32012-02-19 23:26:27 +00002688 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
Chris Lattner31274882009-10-29 05:51:50 +00002689 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002690 NextBB = BA->getBasicBlock();
Chris Lattneraa99c942009-11-01 01:27:45 +00002691 else
2692 return false; // Cannot determine.
Nick Lewycky239fdf02012-02-06 08:24:44 +00002693 } else if (isa<ReturnInst>(CurInst)) {
2694 NextBB = 0;
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002695 } else {
Bill Wendlingf891bf82011-07-31 06:30:59 +00002696 // invoke, unwind, resume, unreachable.
Michael Gottesman2a654272013-01-11 23:08:52 +00002697 DEBUG(dbgs() << "Can not handle terminator.");
Chris Lattner65a3a092005-09-27 04:45:34 +00002698 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00002699 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002700
Nick Lewycky239fdf02012-02-06 08:24:44 +00002701 // We succeeded at evaluating this block!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002702 DEBUG(dbgs() << "Successfully evaluated block.\n");
Nick Lewycky239fdf02012-02-06 08:24:44 +00002703 return true;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002704 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002705 // Did not know how to evaluate this!
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002706 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
Michael Gottesman2a654272013-01-11 23:08:52 +00002707 "\n");
Chris Lattner65a3a092005-09-27 04:45:34 +00002708 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002709 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002710
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002711 if (!CurInst->use_empty()) {
2712 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002713 InstResult = ConstantFoldConstantExpression(CE, DL, TLI);
Jakub Staszak9525a772012-12-06 21:57:16 +00002714
Nick Lewycky73be5e32012-02-19 23:26:27 +00002715 setVal(CurInst, InstResult);
Chris Lattner0d71c4f2010-12-07 04:33:29 +00002716 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002717
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002718 // If we just processed an invoke, we finished evaluating the block.
2719 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2720 NextBB = II->getNormalDest();
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002721 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Dan Gohmaneab06fa2012-03-13 18:01:37 +00002722 return true;
2723 }
2724
Chris Lattner99e23fa2005-09-26 04:44:35 +00002725 // Advance program counter.
2726 ++CurInst;
2727 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00002728}
2729
Nick Lewycky239fdf02012-02-06 08:24:44 +00002730/// EvaluateFunction - Evaluate a call to function F, returning true if
2731/// successful, false if we can't evaluate it. ActualArgs contains the formal
2732/// arguments for the function.
Nick Lewycky60829a582012-02-20 03:25:59 +00002733bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2734 const SmallVectorImpl<Constant*> &ActualArgs) {
Nick Lewycky239fdf02012-02-06 08:24:44 +00002735 // Check to see if this function is already executing (recursion). If so,
2736 // bail out. TODO: we might want to accept limited recursion.
2737 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2738 return false;
2739
2740 CallStack.push_back(F);
2741
Nick Lewycky239fdf02012-02-06 08:24:44 +00002742 // Initialize arguments to the incoming values specified.
2743 unsigned ArgNo = 0;
2744 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2745 ++AI, ++ArgNo)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002746 setVal(AI, ActualArgs[ArgNo]);
Nick Lewycky239fdf02012-02-06 08:24:44 +00002747
2748 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2749 // we can only evaluate any one basic block at most once. This set keeps
2750 // track of what we have executed so we can detect recursive cases etc.
2751 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2752
2753 // CurBB - The current basic block we're evaluating.
2754 BasicBlock *CurBB = F->begin();
2755
Nick Lewycky4231c412012-02-12 00:47:24 +00002756 BasicBlock::iterator CurInst = CurBB->begin();
2757
Nick Lewycky239fdf02012-02-06 08:24:44 +00002758 while (1) {
Duncan Sands4730cb92012-02-23 08:23:06 +00002759 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002760 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2761
Nick Lewycky73be5e32012-02-19 23:26:27 +00002762 if (!EvaluateBlock(CurInst, NextBB))
Nick Lewycky239fdf02012-02-06 08:24:44 +00002763 return false;
2764
2765 if (NextBB == 0) {
2766 // Successfully running until there's no next block means that we found
2767 // the return. Fill it the return value and pop the call stack.
2768 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2769 if (RI->getNumOperands())
Nick Lewycky73be5e32012-02-19 23:26:27 +00002770 RetVal = getVal(RI->getOperand(0));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002771 CallStack.pop_back();
2772 return true;
2773 }
2774
2775 // Okay, we succeeded in evaluating this control flow. See if we have
2776 // executed the new block before. If so, we have a looping function,
2777 // which we cannot evaluate in reasonable time.
2778 if (!ExecutedBlocks.insert(NextBB))
2779 return false; // looped!
2780
2781 // Okay, we have never been in this block before. Check to see if there
2782 // are any PHI nodes. If so, evaluate them with information about where
2783 // we came from.
2784 PHINode *PN = 0;
Nick Lewycky4231c412012-02-12 00:47:24 +00002785 for (CurInst = NextBB->begin();
2786 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Nick Lewycky73be5e32012-02-19 23:26:27 +00002787 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
Nick Lewycky239fdf02012-02-06 08:24:44 +00002788
2789 // Advance to the next block.
2790 CurBB = NextBB;
2791 }
2792}
2793
Chris Lattnerda1889b2005-09-27 04:27:01 +00002794/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2795/// we can. Return true if we can, false otherwise.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002796static bool EvaluateStaticConstructor(Function *F, const DataLayout *DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00002797 const TargetLibraryInfo *TLI) {
Chris Lattnerda1889b2005-09-27 04:27:01 +00002798 // Call the function.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002799 Evaluator Eval(DL, TLI);
Chris Lattner65a3a092005-09-27 04:45:34 +00002800 Constant *RetValDummy;
Nick Lewycky73be5e32012-02-19 23:26:27 +00002801 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2802 SmallVector<Constant*, 0>());
Jakub Staszak9525a772012-12-06 21:57:16 +00002803
Chris Lattnerda1889b2005-09-27 04:27:01 +00002804 if (EvalSuccess) {
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002805 // We succeeded at evaluation: commit the result.
David Greene44cb8ad2010-01-05 01:28:05 +00002806 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Nick Lewycky73be5e32012-02-19 23:26:27 +00002807 << F->getName() << "' to " << Eval.getMutatedMemory().size()
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00002808 << " stores.\n");
Nick Lewycky73be5e32012-02-19 23:26:27 +00002809 for (DenseMap<Constant*, Constant*>::const_iterator I =
2810 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
Nick Lewyckyb74ae9c2012-06-24 04:07:14 +00002811 I != E; ++I)
Chris Lattner46b5c642009-11-06 04:27:31 +00002812 CommitValueTo(I->second, I->first);
Nick Lewycky73be5e32012-02-19 23:26:27 +00002813 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2814 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2815 I != E; ++I)
Nick Lewycky68f9f9d2012-02-17 06:59:21 +00002816 (*I)->setConstant(true);
Chris Lattner6bf2cd52005-09-26 17:07:09 +00002817 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002818
Chris Lattnerda1889b2005-09-27 04:27:01 +00002819 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00002820}
2821
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002822/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2823/// Return true if anything changed.
2824bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2825 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2826 bool MadeChange = false;
2827 if (Ctors.empty()) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002828
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002829 // Loop over global ctors, optimizing them when we can.
2830 for (unsigned i = 0; i != Ctors.size(); ++i) {
2831 Function *F = Ctors[i];
2832 // Found a null terminator in the middle of the list, prune off the rest of
2833 // the list.
Chris Lattner838bdc12005-09-26 02:19:27 +00002834 if (F == 0) {
2835 if (i != Ctors.size()-1) {
2836 Ctors.resize(i+1);
2837 MadeChange = true;
2838 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002839 break;
2840 }
Michael Gottesmand1a46f22013-01-11 20:07:53 +00002841 DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002842
Chris Lattner99e23fa2005-09-26 04:44:35 +00002843 // We cannot simplify external ctor functions.
2844 if (F->empty()) continue;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002845
Chris Lattner99e23fa2005-09-26 04:44:35 +00002846 // If we can evaluate the ctor at compile time, do.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002847 if (EvaluateStaticConstructor(F, DL, TLI)) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00002848 Ctors.erase(Ctors.begin()+i);
2849 MadeChange = true;
2850 --i;
2851 ++NumCtorsEvaluated;
2852 continue;
2853 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002854 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002855
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002856 if (!MadeChange) return false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00002857
Chris Lattner46b5c642009-11-06 04:27:31 +00002858 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00002859 return true;
2860}
2861
Benjamin Kramer8817cca2013-09-22 14:09:50 +00002862static int compareNames(Constant *const *A, Constant *const *B) {
2863 return (*A)->getName().compare((*B)->getName());
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002864}
Rafael Espindola00752162013-05-09 17:22:59 +00002865
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002866static void setUsedInitializer(GlobalVariable &V,
2867 SmallPtrSet<GlobalValue *, 8> Init) {
Rafael Espindolac2bb73f2013-07-20 23:33:15 +00002868 if (Init.empty()) {
2869 V.eraseFromParent();
2870 return;
2871 }
2872
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002873 // Type of pointer to the array of pointers.
2874 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
Rafael Espindola00752162013-05-09 17:22:59 +00002875
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002876 SmallVector<llvm::Constant *, 8> UsedArray;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002877 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Init.begin(), E = Init.end();
2878 I != E; ++I) {
Matt Arsenaultda1deab2014-01-02 19:53:49 +00002879 Constant *Cast
2880 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(*I, Int8PtrTy);
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002881 UsedArray.push_back(Cast);
Rafael Espindola00752162013-05-09 17:22:59 +00002882 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002883 // Sort to get deterministic order.
2884 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
2885 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
Rafael Espindola00752162013-05-09 17:22:59 +00002886
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002887 Module *M = V.getParent();
2888 V.removeFromParent();
2889 GlobalVariable *NV =
2890 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2891 llvm::ConstantArray::get(ATy, UsedArray), "");
2892 NV->takeName(&V);
2893 NV->setSection("llvm.metadata");
2894 delete &V;
Rafael Espindola00752162013-05-09 17:22:59 +00002895}
2896
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002897namespace {
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002898/// \brief An easy to access representation of llvm.used and llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002899class LLVMUsed {
2900 SmallPtrSet<GlobalValue *, 8> Used;
2901 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2902 GlobalVariable *UsedV;
2903 GlobalVariable *CompilerUsedV;
2904
2905public:
Rafael Espindolaec2375f2013-07-25 02:50:08 +00002906 LLVMUsed(Module &M) {
Rafael Espindola17600e22013-07-25 03:23:25 +00002907 UsedV = collectUsedGlobalVariables(M, Used, false);
2908 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
Rafael Espindola00752162013-05-09 17:22:59 +00002909 }
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002910 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
2911 iterator usedBegin() { return Used.begin(); }
2912 iterator usedEnd() { return Used.end(); }
2913 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2914 iterator compilerUsedEnd() { return CompilerUsed.end(); }
2915 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2916 bool compilerUsedCount(GlobalValue *GV) const {
2917 return CompilerUsed.count(GV);
2918 }
2919 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2920 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2921 bool usedInsert(GlobalValue *GV) { return Used.insert(GV); }
2922 bool compilerUsedInsert(GlobalValue *GV) { return CompilerUsed.insert(GV); }
Rafael Espindola00752162013-05-09 17:22:59 +00002923
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002924 void syncVariablesAndSets() {
2925 if (UsedV)
2926 setUsedInitializer(*UsedV, Used);
2927 if (CompilerUsedV)
2928 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2929 }
2930};
Rafael Espindola00752162013-05-09 17:22:59 +00002931}
2932
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002933static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2934 if (GA.use_empty()) // No use at all.
2935 return false;
2936
2937 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2938 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002939 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002940 if (!GA.hasOneUse())
2941 // Strictly more than one use. So at least one is not in llvm.used and
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002942 // llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002943 return true;
2944
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002945 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002946 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
Rafael Espindola00752162013-05-09 17:22:59 +00002947}
2948
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002949static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2950 const LLVMUsed &U) {
2951 unsigned N = 2;
2952 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2953 "We should have removed the duplicated "
Rafael Espindola9aadcc42013-07-19 18:44:51 +00002954 "element from llvm.compiler.used");
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002955 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2956 ++N;
2957 return V.hasNUsesOrMore(N);
2958}
2959
2960static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2961 if (!GA.hasLocalLinkage())
2962 return true;
2963
2964 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2965}
2966
2967static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget) {
2968 RenameTarget = false;
Rafael Espindola00752162013-05-09 17:22:59 +00002969 bool Ret = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002970 if (hasUseOtherThanLLVMUsed(GA, U))
Rafael Espindola00752162013-05-09 17:22:59 +00002971 Ret = true;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00002972
2973 // If the alias is externally visible, we may still be able to simplify it.
2974 if (!mayHaveOtherReferences(GA, U))
2975 return Ret;
2976
2977 // If the aliasee has internal linkage, give it the name and linkage
2978 // of the alias, and delete the alias. This turns:
2979 // define internal ... @f(...)
2980 // @a = alias ... @f
2981 // into:
2982 // define ... @a(...)
2983 Constant *Aliasee = GA.getAliasee();
2984 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2985 if (!Target->hasLocalLinkage())
2986 return Ret;
2987
2988 // Do not perform the transform if multiple aliases potentially target the
2989 // aliasee. This check also ensures that it is safe to replace the section
2990 // and other attributes of the aliasee with those of the alias.
2991 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2992 return Ret;
2993
2994 RenameTarget = true;
2995 return true;
Rafael Espindola00752162013-05-09 17:22:59 +00002996}
2997
Duncan Sandsed722832009-03-06 10:21:56 +00002998bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00002999 bool Changed = false;
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003000 LLVMUsed Used(M);
3001
3002 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.usedBegin(),
3003 E = Used.usedEnd();
3004 I != E; ++I)
3005 Used.compilerUsedErase(*I);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003006
Duncan Sands0bcf0852009-01-07 20:01:06 +00003007 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandsb3f27882009-02-15 09:56:08 +00003008 I != E;) {
3009 Module::alias_iterator J = I++;
Duncan Sandsed722832009-03-06 10:21:56 +00003010 // Aliases without names cannot be referenced outside this module.
3011 if (!J->hasName() && !J->isDeclaration())
3012 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandsb3f27882009-02-15 09:56:08 +00003013 // If the aliasee may change at link time, nothing can be done - bail out.
3014 if (J->mayBeOverridden())
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003015 continue;
3016
Duncan Sandsb3f27882009-02-15 09:56:08 +00003017 Constant *Aliasee = J->getAliasee();
3018 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands7a1db332009-02-18 17:55:38 +00003019 Target->removeDeadConstantUsers();
Duncan Sandsb3f27882009-02-15 09:56:08 +00003020
3021 // Make all users of the alias use the aliasee instead.
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003022 bool RenameTarget;
3023 if (!hasUsesToReplace(*J, Used, RenameTarget))
Rafael Espindola00752162013-05-09 17:22:59 +00003024 continue;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003025
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003026 J->replaceAllUsesWith(Aliasee);
3027 ++NumAliasesResolved;
3028 Changed = true;
Duncan Sandsb3f27882009-02-15 09:56:08 +00003029
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003030 if (RenameTarget) {
Duncan Sands6a3df7b2009-12-08 10:10:20 +00003031 // Give the aliasee the name, linkage and other attributes of the alias.
3032 Target->takeName(J);
3033 Target->setLinkage(J->getLinkage());
Reid Kleckner22b19da2014-02-13 02:18:36 +00003034 Target->setVisibility(J->getVisibility());
3035 Target->setDLLStorageClass(J->getDLLStorageClass());
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003036
3037 if (Used.usedErase(J))
3038 Used.usedInsert(Target);
3039
3040 if (Used.compilerUsedErase(J))
3041 Used.compilerUsedInsert(Target);
Rafael Espindola8d304802013-06-12 16:45:47 +00003042 } else if (mayHaveOtherReferences(*J, Used))
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003043 continue;
3044
Duncan Sandsb3f27882009-02-15 09:56:08 +00003045 // Delete the alias.
3046 M.getAliasList().erase(J);
3047 ++NumAliasesRemoved;
3048 Changed = true;
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003049 }
3050
Rafael Espindolaa82555c2013-06-11 17:48:06 +00003051 Used.syncVariablesAndSets();
3052
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003053 return Changed;
3054}
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003055
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003056static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3057 if (!TLI->has(LibFunc::cxa_atexit))
Nick Lewyckyf2852562012-02-12 02:17:18 +00003058 return 0;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003059
3060 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
Jakub Staszak9525a772012-12-06 21:57:16 +00003061
Anders Carlssonee6bc702011-03-20 17:59:11 +00003062 if (!Fn)
3063 return 0;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003064
Chris Lattner229907c2011-07-18 04:54:35 +00003065 FunctionType *FTy = Fn->getFunctionType();
Jakub Staszak9525a772012-12-06 21:57:16 +00003066
3067 // Checking that the function has the right return type, the right number of
Anders Carlsson48a44912011-03-20 19:51:13 +00003068 // parameters and that they all have pointer types should be enough.
3069 if (!FTy->getReturnType()->isIntegerTy() ||
3070 FTy->getNumParams() != 3 ||
Anders Carlssonee6bc702011-03-20 17:59:11 +00003071 !FTy->getParamType(0)->isPointerTy() ||
3072 !FTy->getParamType(1)->isPointerTy() ||
3073 !FTy->getParamType(2)->isPointerTy())
3074 return 0;
3075
3076 return Fn;
3077}
3078
3079/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3080/// destructor and can therefore be eliminated.
3081/// Note that we assume that other optimization passes have already simplified
3082/// the code so we only look for a function with a single basic block, where
Benjamin Kramer1a4695a2012-02-09 16:28:15 +00003083/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3084/// other side-effect free instructions.
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003085static bool cxxDtorIsEmpty(const Function &Fn,
3086 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson48a44912011-03-20 19:51:13 +00003087 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewyckyd0781832011-03-21 02:26:01 +00003088 // nounwind, but that doesn't seem worth doing.
Anders Carlsson48a44912011-03-20 19:51:13 +00003089 if (Fn.isDeclaration())
3090 return false;
Anders Carlssonee6bc702011-03-20 17:59:11 +00003091
3092 if (++Fn.begin() != Fn.end())
3093 return false;
3094
3095 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3096 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3097 I != E; ++I) {
3098 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003099 // Ignore debug intrinsics.
3100 if (isa<DbgInfoIntrinsic>(CI))
3101 continue;
3102
Anders Carlssonee6bc702011-03-20 17:59:11 +00003103 const Function *CalledFn = CI->getCalledFunction();
3104
3105 if (!CalledFn)
3106 return false;
3107
Anders Carlsson1cc80732011-03-22 03:21:01 +00003108 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3109
Anders Carlsson48a44912011-03-20 19:51:13 +00003110 // Don't treat recursive functions as empty.
Anders Carlsson1cc80732011-03-22 03:21:01 +00003111 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson48a44912011-03-20 19:51:13 +00003112 return false;
3113
Anders Carlsson1cc80732011-03-22 03:21:01 +00003114 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003115 return false;
3116 } else if (isa<ReturnInst>(*I))
Benjamin Kramer487a3962012-02-09 14:26:06 +00003117 return true; // We're done.
3118 else if (I->mayHaveSideEffects())
3119 return false; // Destructor with side effects, bail.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003120 }
3121
3122 return false;
3123}
3124
3125bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3126 /// Itanium C++ ABI p3.3.5:
3127 ///
3128 /// After constructing a global (or local static) object, that will require
3129 /// destruction on exit, a termination function is registered as follows:
3130 ///
3131 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3132 ///
3133 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3134 /// call f(p) when DSO d is unloaded, before all such termination calls
3135 /// registered before this one. It returns zero if registration is
Nick Lewyckyd0781832011-03-21 02:26:01 +00003136 /// successful, nonzero on failure.
Anders Carlssonee6bc702011-03-20 17:59:11 +00003137
3138 // This pass will look for calls to __cxa_atexit where the function is trivial
3139 // and remove them.
3140 bool Changed = false;
3141
Jakub Staszak9525a772012-12-06 21:57:16 +00003142 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
Anders Carlssonee6bc702011-03-20 17:59:11 +00003143 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson336fd902011-03-20 20:21:33 +00003144 // We're only interested in calls. Theoretically, we could handle invoke
3145 // instructions as well, but neither llvm-gcc nor clang generate invokes
3146 // to __cxa_atexit.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003147 CallInst *CI = dyn_cast<CallInst>(*I++);
3148 if (!CI)
Anders Carlsson336fd902011-03-20 20:21:33 +00003149 continue;
3150
Jakub Staszak9525a772012-12-06 21:57:16 +00003151 Function *DtorFn =
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003152 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssonee6bc702011-03-20 17:59:11 +00003153 if (!DtorFn)
3154 continue;
3155
Anders Carlssonfcec2f52011-03-20 20:16:43 +00003156 SmallPtrSet<const Function *, 8> CalledFunctions;
3157 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssonee6bc702011-03-20 17:59:11 +00003158 continue;
3159
3160 // Just remove the call.
Anders Carlsson4dd420f2011-03-21 14:54:40 +00003161 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3162 CI->eraseFromParent();
Anders Carlsson48a44912011-03-20 19:51:13 +00003163
Anders Carlssonee6bc702011-03-20 17:59:11 +00003164 ++NumCXXDtorsRemoved;
3165
3166 Changed |= true;
3167 }
3168
3169 return Changed;
3170}
3171
Chris Lattner25db5802004-10-07 04:16:33 +00003172bool GlobalOpt::runOnModule(Module &M) {
3173 bool Changed = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003174
Rafael Espindola93512512014-02-25 17:30:31 +00003175 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3176 DL = DLP ? &DLP->getDataLayout() : 0;
Nick Lewycky4b273cb2012-02-12 02:15:20 +00003177 TLI = &getAnalysis<TargetLibraryInfo>();
Nick Lewyckycf6aae62012-02-12 01:13:18 +00003178
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003179 // Try to find the llvm.globalctors list.
3180 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner25db5802004-10-07 04:16:33 +00003181
Chris Lattner25db5802004-10-07 04:16:33 +00003182 bool LocalChange = true;
3183 while (LocalChange) {
3184 LocalChange = false;
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003185
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003186 // Delete functions that are trivially dead, ccc -> fastcc
3187 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003188
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003189 // Optimize global_ctors list.
3190 if (GlobalCtors)
3191 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003192
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003193 // Optimize non-address-taken globals.
3194 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003195
3196 // Resolve aliases, when possible.
Duncan Sandsed722832009-03-06 10:21:56 +00003197 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003198
Manman Renb3c52fb2013-05-14 21:52:44 +00003199 // Try to remove trivial global destructors if they are not removed
3200 // already.
3201 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
Anders Carlssonee6bc702011-03-20 17:59:11 +00003202 if (CXAAtExitFn)
3203 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3204
Anton Korobeynikova9b60ee2008-09-09 19:04:59 +00003205 Changed |= LocalChange;
Chris Lattner25db5802004-10-07 04:16:33 +00003206 }
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003207
Chris Lattner41b6a5a2005-09-26 01:43:45 +00003208 // TODO: Move all global ctors functions to the end of the module for code
3209 // layout.
Mikhail Glushenkovcf2afe02010-10-18 21:16:00 +00003210
Chris Lattner25db5802004-10-07 04:16:33 +00003211 return Changed;
3212}