blob: f705d2d50c5425c3ff3cac3fc575c8538c41bb96 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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"
Chris Lattnera4c80222005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner25db5802004-10-07 04:16:33 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Instructions.h"
Chris Lattner7561ca12005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner25db5802004-10-07 04:16:33 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/Debug.h"
Chris Lattner004e2502004-10-11 05:54:41 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Transforms/Utils/Local.h"
Chris Lattner25db5802004-10-07 04:16:33 +000028#include "llvm/ADT/Statistic.h"
Chris Lattnerabab0712004-10-08 17:32:09 +000029#include "llvm/ADT/StringExtras.h"
Chris Lattner25db5802004-10-07 04:16:33 +000030#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000031#include <iostream>
32#include <set>
Chris Lattner25db5802004-10-07 04:16:33 +000033using namespace llvm;
34
35namespace {
Chris Lattnerabab0712004-10-08 17:32:09 +000036 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
37 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
38 "into scalars");
Chris Lattner24d3d422006-09-30 23:32:09 +000039 Statistic<> NumHeapSRA ("globalopt", "Number of heap objects SRA'd");
Chris Lattner8e71c6a2004-10-16 18:09:00 +000040 Statistic<> NumSubstitute("globalopt",
41 "Number of globals with initializers stored into them");
Chris Lattnerabab0712004-10-08 17:32:09 +000042 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner25db5802004-10-07 04:16:33 +000043 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
Chris Lattnere42eb312004-10-10 23:14:11 +000044 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +000045 Statistic<> NumLocalized("globalopt", "Number of globals localized");
Chris Lattner40e4cec2004-12-12 05:53:50 +000046 Statistic<> NumShrunkToBool("globalopt",
47 "Number of global vars shrunk to booleans");
Chris Lattnera4c80222005-05-08 22:18:06 +000048 Statistic<> NumFastCallFns("globalopt",
49 "Number of functions converted to fastcc");
Chris Lattner99e23fa2005-09-26 04:44:35 +000050 Statistic<> NumCtorsEvaluated("globalopt","Number of static ctors evaluated");
Chris Lattner25db5802004-10-07 04:16:33 +000051
52 struct GlobalOpt : public ModulePass {
Chris Lattner004e2502004-10-11 05:54:41 +000053 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 AU.addRequired<TargetData>();
55 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000056
Chris Lattner25db5802004-10-07 04:16:33 +000057 bool runOnModule(Module &M);
Chris Lattner004e2502004-10-11 05:54:41 +000058
59 private:
Chris Lattner41b6a5a2005-09-26 01:43:45 +000060 GlobalVariable *FindGlobalCtors(Module &M);
61 bool OptimizeFunctions(Module &M);
62 bool OptimizeGlobalVars(Module &M);
63 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattnerc2d3d312006-08-27 22:42:52 +000064 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner25db5802004-10-07 04:16:33 +000065 };
66
Chris Lattnerc2d3d312006-08-27 22:42:52 +000067 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
Chris Lattner25db5802004-10-07 04:16:33 +000068}
69
70ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
71
72/// GlobalStatus - As we analyze each global, keep track of some information
73/// about it. If we find out that the address of the global is taken, none of
Chris Lattner617f1a32004-10-07 21:30:30 +000074/// this info will be accurate.
Chris Lattner25db5802004-10-07 04:16:33 +000075struct GlobalStatus {
Chris Lattner617f1a32004-10-07 21:30:30 +000076 /// isLoaded - True if the global is ever loaded. If the global isn't ever
77 /// loaded it can be deleted.
Chris Lattner25db5802004-10-07 04:16:33 +000078 bool isLoaded;
Chris Lattner617f1a32004-10-07 21:30:30 +000079
80 /// StoredType - Keep track of what stores to the global look like.
81 ///
Chris Lattner25db5802004-10-07 04:16:33 +000082 enum StoredType {
Chris Lattner617f1a32004-10-07 21:30:30 +000083 /// NotStored - There is no store to this global. It can thus be marked
84 /// constant.
85 NotStored,
86
87 /// isInitializerStored - This global is stored to, but the only thing
88 /// stored is the constant it was initialized with. This is only tracked
89 /// for scalar globals.
90 isInitializerStored,
91
92 /// isStoredOnce - This global is stored to, but only its initializer and
93 /// one other value is ever stored to it. If this global isStoredOnce, we
94 /// track the value stored to it in StoredOnceValue below. This is only
95 /// tracked for scalar globals.
96 isStoredOnce,
97
98 /// isStored - This global is stored to by multiple values or something else
99 /// that we cannot track.
100 isStored
Chris Lattner25db5802004-10-07 04:16:33 +0000101 } StoredType;
Chris Lattner617f1a32004-10-07 21:30:30 +0000102
103 /// StoredOnceValue - If only one value (besides the initializer constant) is
104 /// ever stored to this global, keep track of what value it is.
105 Value *StoredOnceValue;
106
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000107 // AccessingFunction/HasMultipleAccessingFunctions - These start out
108 // null/false. When the first accessing function is noticed, it is recorded.
109 // When a second different accessing function is noticed,
110 // HasMultipleAccessingFunctions is set to true.
111 Function *AccessingFunction;
112 bool HasMultipleAccessingFunctions;
113
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000114 // HasNonInstructionUser - Set to true if this global has a user that is not
115 // an instruction (e.g. a constant expr or GV initializer).
116 bool HasNonInstructionUser;
117
Chris Lattner617f1a32004-10-07 21:30:30 +0000118 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
119 /// the global exist. Such users include GEP instruction with variable
120 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner25db5802004-10-07 04:16:33 +0000121 bool isNotSuitableForSRA;
122
Chris Lattner617f1a32004-10-07 21:30:30 +0000123 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000124 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000125 HasNonInstructionUser(false), isNotSuitableForSRA(false) {}
Chris Lattner25db5802004-10-07 04:16:33 +0000126};
127
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000128
129
130/// ConstantIsDead - Return true if the specified constant is (transitively)
131/// dead. The constant may be used by other constants (e.g. constant arrays and
132/// constant exprs) as long as they are dead, but it cannot be used by anything
133/// else.
134static bool ConstantIsDead(Constant *C) {
135 if (isa<GlobalValue>(C)) return false;
136
137 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
138 if (Constant *CU = dyn_cast<Constant>(*UI)) {
139 if (!ConstantIsDead(CU)) return false;
140 } else
141 return false;
142 return true;
143}
144
145
Chris Lattner25db5802004-10-07 04:16:33 +0000146/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
147/// structure. If the global has its address taken, return true to indicate we
148/// can't do anything with it.
149///
150static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
151 std::set<PHINode*> &PHIUsers) {
152 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
153 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000154 GS.HasNonInstructionUser = true;
155
Chris Lattner25db5802004-10-07 04:16:33 +0000156 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
157 if (CE->getOpcode() != Instruction::GetElementPtr)
158 GS.isNotSuitableForSRA = true;
Chris Lattnerabab0712004-10-08 17:32:09 +0000159 else if (!GS.isNotSuitableForSRA) {
160 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
161 // don't like < 3 operand CE's, and we don't like non-constant integer
162 // indices.
163 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
164 GS.isNotSuitableForSRA = true;
165 else {
166 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
167 if (!isa<ConstantInt>(CE->getOperand(i))) {
168 GS.isNotSuitableForSRA = true;
169 break;
170 }
171 }
172 }
173
Chris Lattner25db5802004-10-07 04:16:33 +0000174 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +0000175 if (!GS.HasMultipleAccessingFunctions) {
176 Function *F = I->getParent()->getParent();
177 if (GS.AccessingFunction == 0)
178 GS.AccessingFunction = F;
179 else if (GS.AccessingFunction != F)
180 GS.HasMultipleAccessingFunctions = true;
181 }
Chris Lattner25db5802004-10-07 04:16:33 +0000182 if (isa<LoadInst>(I)) {
183 GS.isLoaded = true;
184 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner02b6c912004-10-07 06:01:25 +0000185 // Don't allow a store OF the address, only stores TO the address.
186 if (SI->getOperand(0) == V) return true;
187
Chris Lattner617f1a32004-10-07 21:30:30 +0000188 // If this is a direct store to the global (i.e., the global is a scalar
189 // value, not an aggregate), keep more specific information about
190 // stores.
191 if (GS.StoredType != GlobalStatus::isStored)
192 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattner28eeb732004-11-14 20:50:30 +0000193 Value *StoredVal = SI->getOperand(0);
194 if (StoredVal == GV->getInitializer()) {
195 if (GS.StoredType < GlobalStatus::isInitializerStored)
196 GS.StoredType = GlobalStatus::isInitializerStored;
197 } else if (isa<LoadInst>(StoredVal) &&
198 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
199 // G = G
Chris Lattner617f1a32004-10-07 21:30:30 +0000200 if (GS.StoredType < GlobalStatus::isInitializerStored)
201 GS.StoredType = GlobalStatus::isInitializerStored;
202 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
203 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattner28eeb732004-11-14 20:50:30 +0000204 GS.StoredOnceValue = StoredVal;
Chris Lattner617f1a32004-10-07 21:30:30 +0000205 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattner28eeb732004-11-14 20:50:30 +0000206 GS.StoredOnceValue == StoredVal) {
Chris Lattner617f1a32004-10-07 21:30:30 +0000207 // noop.
208 } else {
209 GS.StoredType = GlobalStatus::isStored;
210 }
211 } else {
Chris Lattner25db5802004-10-07 04:16:33 +0000212 GS.StoredType = GlobalStatus::isStored;
Chris Lattner617f1a32004-10-07 21:30:30 +0000213 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000214 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000215 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner004e2502004-10-11 05:54:41 +0000216
217 // If the first two indices are constants, this can be SRA'd.
218 if (isa<GlobalVariable>(I->getOperand(0))) {
219 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
Misha Brukmanb1c93172005-04-21 23:48:37 +0000220 !cast<Constant>(I->getOperand(1))->isNullValue() ||
Chris Lattner004e2502004-10-11 05:54:41 +0000221 !isa<ConstantInt>(I->getOperand(2)))
222 GS.isNotSuitableForSRA = true;
223 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
224 if (CE->getOpcode() != Instruction::GetElementPtr ||
225 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
226 !isa<Constant>(I->getOperand(0)) ||
227 !cast<Constant>(I->getOperand(0))->isNullValue())
228 GS.isNotSuitableForSRA = true;
229 } else {
230 GS.isNotSuitableForSRA = true;
231 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000232 } else if (isa<SelectInst>(I)) {
Chris Lattner25db5802004-10-07 04:16:33 +0000233 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
234 GS.isNotSuitableForSRA = true;
235 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
236 // PHI nodes we can check just like select or GEP instructions, but we
237 // have to be careful about infinite recursion.
238 if (PHIUsers.insert(PN).second) // Not already visited.
239 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
240 GS.isNotSuitableForSRA = true;
241 } else if (isa<SetCondInst>(I)) {
242 GS.isNotSuitableForSRA = true;
Chris Lattner7561ca12005-02-27 18:58:52 +0000243 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
244 if (I->getOperand(1) == V)
245 GS.StoredType = GlobalStatus::isStored;
246 if (I->getOperand(2) == V)
247 GS.isLoaded = true;
248 GS.isNotSuitableForSRA = true;
249 } else if (isa<MemSetInst>(I)) {
250 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
251 GS.StoredType = GlobalStatus::isStored;
252 GS.isNotSuitableForSRA = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000253 } else {
254 return true; // Any other non-load instruction might take address!
255 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000256 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000257 GS.HasNonInstructionUser = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000258 // We might have a dead and dangling constant hanging off of here.
259 if (!ConstantIsDead(C))
260 return true;
Chris Lattner25db5802004-10-07 04:16:33 +0000261 } else {
Chris Lattner50bdfcb2005-06-15 21:11:48 +0000262 GS.HasNonInstructionUser = true;
263 // Otherwise must be some other user.
Chris Lattner25db5802004-10-07 04:16:33 +0000264 return true;
265 }
266
267 return false;
268}
269
Chris Lattnerabab0712004-10-08 17:32:09 +0000270static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
271 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
272 if (!CI) return 0;
Chris Lattner46fa04b2005-01-08 19:45:31 +0000273 unsigned IdxV = (unsigned)CI->getRawValue();
Chris Lattner25db5802004-10-07 04:16:33 +0000274
Chris Lattnerabab0712004-10-08 17:32:09 +0000275 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
276 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
277 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
278 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
279 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
280 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000281 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattnerabab0712004-10-08 17:32:09 +0000282 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
283 if (IdxV < STy->getNumElements())
284 return Constant::getNullValue(STy->getElementType(IdxV));
285 } else if (const SequentialType *STy =
286 dyn_cast<SequentialType>(Agg->getType())) {
287 return Constant::getNullValue(STy->getElementType());
288 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000289 } else if (isa<UndefValue>(Agg)) {
290 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
291 if (IdxV < STy->getNumElements())
292 return UndefValue::get(STy->getElementType(IdxV));
293 } else if (const SequentialType *STy =
294 dyn_cast<SequentialType>(Agg->getType())) {
295 return UndefValue::get(STy->getElementType());
296 }
Chris Lattnerabab0712004-10-08 17:32:09 +0000297 }
298 return 0;
299}
Chris Lattner25db5802004-10-07 04:16:33 +0000300
Chris Lattner25db5802004-10-07 04:16:33 +0000301
302/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
303/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattnercb9f1522004-10-10 16:43:46 +0000304/// quick scan over the use list to clean up the easy and obvious cruft. This
305/// returns true if it made a change.
306static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
307 bool Changed = false;
Chris Lattner25db5802004-10-07 04:16:33 +0000308 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
309 User *U = *UI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000310
Chris Lattner25db5802004-10-07 04:16:33 +0000311 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner7561ca12005-02-27 18:58:52 +0000312 if (Init) {
313 // Replace the load with the initializer.
314 LI->replaceAllUsesWith(Init);
315 LI->eraseFromParent();
316 Changed = true;
317 }
Chris Lattner25db5802004-10-07 04:16:33 +0000318 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
319 // Store must be unreachable or storing Init into the global.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000320 SI->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000321 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000322 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
323 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner46d9ff082005-09-26 07:34:35 +0000324 Constant *SubInit = 0;
325 if (Init)
326 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000327 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
328 } else if (CE->getOpcode() == Instruction::Cast &&
329 isa<PointerType>(CE->getType())) {
330 // Pointer cast, delete any stores and memsets to the global.
331 Changed |= CleanupConstantGlobalUsers(CE, 0);
332 }
333
334 if (CE->use_empty()) {
335 CE->destroyConstant();
336 Changed = true;
Chris Lattner25db5802004-10-07 04:16:33 +0000337 }
338 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner61ff32c2005-09-26 05:34:07 +0000339 Constant *SubInit = 0;
Chris Lattner46af55e2005-09-26 06:52:44 +0000340 ConstantExpr *CE =
341 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattnereb953f02005-09-27 22:28:11 +0000342 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner61ff32c2005-09-26 05:34:07 +0000343 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7561ca12005-02-27 18:58:52 +0000344 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnera0e769c2004-10-10 16:47:33 +0000345
Chris Lattnercb9f1522004-10-10 16:43:46 +0000346 if (GEP->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000347 GEP->eraseFromParent();
Chris Lattnercb9f1522004-10-10 16:43:46 +0000348 Changed = true;
349 }
Chris Lattner7561ca12005-02-27 18:58:52 +0000350 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
351 if (MI->getRawDest() == V) {
352 MI->eraseFromParent();
353 Changed = true;
354 }
355
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000356 } else if (Constant *C = dyn_cast<Constant>(U)) {
357 // If we have a chain of dead constantexprs or other things dangling from
358 // us, and if they are all dead, nuke them without remorse.
359 if (ConstantIsDead(C)) {
360 C->destroyConstant();
Chris Lattner7561ca12005-02-27 18:58:52 +0000361 // This could have invalidated UI, start over from scratch.
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000362 CleanupConstantGlobalUsers(V, Init);
Chris Lattnercb9f1522004-10-10 16:43:46 +0000363 return true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +0000364 }
Chris Lattner25db5802004-10-07 04:16:33 +0000365 }
366 }
Chris Lattnercb9f1522004-10-10 16:43:46 +0000367 return Changed;
Chris Lattner25db5802004-10-07 04:16:33 +0000368}
369
Chris Lattnerabab0712004-10-08 17:32:09 +0000370/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
371/// variable. This opens the door for other optimizations by exposing the
372/// behavior of the program in a more fine-grained way. We have determined that
373/// this transformation is safe already. We return the first global variable we
374/// insert so that the caller can reprocess it.
375static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
376 assert(GV->hasInternalLinkage() && !GV->isConstant());
377 Constant *Init = GV->getInitializer();
378 const Type *Ty = Init->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000379
Chris Lattnerabab0712004-10-08 17:32:09 +0000380 std::vector<GlobalVariable*> NewGlobals;
381 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
382
383 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
384 NewGlobals.reserve(STy->getNumElements());
385 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
386 Constant *In = getAggregateConstantElement(Init,
387 ConstantUInt::get(Type::UIntTy, i));
388 assert(In && "Couldn't get element of initializer?");
389 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
390 GlobalVariable::InternalLinkage,
391 In, GV->getName()+"."+utostr(i));
392 Globals.insert(GV, NGV);
393 NewGlobals.push_back(NGV);
394 }
395 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
396 unsigned NumElements = 0;
397 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
398 NumElements = ATy->getNumElements();
399 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
400 NumElements = PTy->getNumElements();
401 else
402 assert(0 && "Unknown aggregate sequential type!");
403
Chris Lattner25169ca2005-02-23 16:53:04 +0000404 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd6a44922005-02-01 01:23:31 +0000405 return 0; // It's not worth it.
Chris Lattnerabab0712004-10-08 17:32:09 +0000406 NewGlobals.reserve(NumElements);
407 for (unsigned i = 0, e = NumElements; i != e; ++i) {
408 Constant *In = getAggregateConstantElement(Init,
409 ConstantUInt::get(Type::UIntTy, i));
410 assert(In && "Couldn't get element of initializer?");
411
412 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
413 GlobalVariable::InternalLinkage,
414 In, GV->getName()+"."+utostr(i));
415 Globals.insert(GV, NGV);
416 NewGlobals.push_back(NGV);
417 }
418 }
419
420 if (NewGlobals.empty())
421 return 0;
422
Chris Lattner004e2502004-10-11 05:54:41 +0000423 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
424
Chris Lattnerabab0712004-10-08 17:32:09 +0000425 Constant *NullInt = Constant::getNullValue(Type::IntTy);
426
427 // Loop over all of the uses of the global, replacing the constantexpr geps,
428 // with smaller constantexpr geps or direct references.
429 while (!GV->use_empty()) {
Chris Lattner004e2502004-10-11 05:54:41 +0000430 User *GEP = GV->use_back();
431 assert(((isa<ConstantExpr>(GEP) &&
432 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
433 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000434
Chris Lattnerabab0712004-10-08 17:32:09 +0000435 // Ignore the 1th operand, which has to be zero or else the program is quite
436 // broken (undefined). Get the 2nd operand, which is the structure or array
437 // index.
Chris Lattner46fa04b2005-01-08 19:45:31 +0000438 unsigned Val =
439 (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
Chris Lattnerabab0712004-10-08 17:32:09 +0000440 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
441
Chris Lattner004e2502004-10-11 05:54:41 +0000442 Value *NewPtr = NewGlobals[Val];
Chris Lattnerabab0712004-10-08 17:32:09 +0000443
444 // Form a shorter GEP if needed.
Chris Lattner004e2502004-10-11 05:54:41 +0000445 if (GEP->getNumOperands() > 3)
446 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
447 std::vector<Constant*> Idxs;
448 Idxs.push_back(NullInt);
449 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
450 Idxs.push_back(CE->getOperand(i));
451 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
452 } else {
453 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
454 std::vector<Value*> Idxs;
455 Idxs.push_back(NullInt);
456 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
457 Idxs.push_back(GEPI->getOperand(i));
458 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
459 GEPI->getName()+"."+utostr(Val), GEPI);
460 }
461 GEP->replaceAllUsesWith(NewPtr);
462
463 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000464 GEPI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000465 else
466 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattnerabab0712004-10-08 17:32:09 +0000467 }
468
Chris Lattner73ad73e2004-10-08 20:25:55 +0000469 // Delete the old global, now that it is dead.
470 Globals.erase(GV);
Chris Lattnerabab0712004-10-08 17:32:09 +0000471 ++NumSRA;
Chris Lattner004e2502004-10-11 05:54:41 +0000472
473 // Loop over the new globals array deleting any globals that are obviously
474 // dead. This can arise due to scalarization of a structure or an array that
475 // has elements that are dead.
476 unsigned FirstGlobal = 0;
477 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
478 if (NewGlobals[i]->use_empty()) {
479 Globals.erase(NewGlobals[i]);
480 if (FirstGlobal == i) ++FirstGlobal;
481 }
482
483 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattnerabab0712004-10-08 17:32:09 +0000484}
485
Chris Lattner09a52722004-10-09 21:48:45 +0000486/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
487/// value will trap if the value is dynamically null.
488static bool AllUsesOfValueWillTrapIfNull(Value *V) {
489 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
490 if (isa<LoadInst>(*UI)) {
491 // Will trap.
492 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
493 if (SI->getOperand(0) == V) {
494 //std::cerr << "NONTRAPPING USE: " << **UI;
495 return false; // Storing the value.
496 }
497 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
498 if (CI->getOperand(0) != V) {
499 //std::cerr << "NONTRAPPING USE: " << **UI;
500 return false; // Not calling the ptr
501 }
502 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
503 if (II->getOperand(0) != V) {
504 //std::cerr << "NONTRAPPING USE: " << **UI;
505 return false; // Not calling the ptr
506 }
507 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
508 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
509 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
510 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000511 } else if (isa<SetCondInst>(*UI) &&
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000512 isa<ConstantPointerNull>(UI->getOperand(1))) {
513 // Ignore setcc X, null
Chris Lattner09a52722004-10-09 21:48:45 +0000514 } else {
515 //std::cerr << "NONTRAPPING USE: " << **UI;
516 return false;
517 }
518 return true;
519}
520
521/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000522/// from GV will trap if the loaded value is null. Note that this also permits
523/// comparisons of the loaded value against null, as a special case.
Chris Lattner09a52722004-10-09 21:48:45 +0000524static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
525 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
526 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
527 if (!AllUsesOfValueWillTrapIfNull(LI))
528 return false;
529 } else if (isa<StoreInst>(*UI)) {
530 // Ignore stores to the global.
531 } else {
532 // We don't know or understand this user, bail out.
533 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
534 return false;
535 }
536
537 return true;
538}
539
Chris Lattnere42eb312004-10-10 23:14:11 +0000540static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
541 bool Changed = false;
542 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
543 Instruction *I = cast<Instruction>(*UI++);
544 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
545 LI->setOperand(0, NewV);
546 Changed = true;
547 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
548 if (SI->getOperand(1) == V) {
549 SI->setOperand(1, NewV);
550 Changed = true;
551 }
552 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
553 if (I->getOperand(0) == V) {
554 // Calling through the pointer! Turn into a direct call, but be careful
555 // that the pointer is not also being passed as an argument.
556 I->setOperand(0, NewV);
557 Changed = true;
558 bool PassedAsArg = false;
559 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
560 if (I->getOperand(i) == V) {
561 PassedAsArg = true;
562 I->setOperand(i, NewV);
563 }
564
565 if (PassedAsArg) {
566 // Being passed as an argument also. Be careful to not invalidate UI!
567 UI = V->use_begin();
568 }
569 }
570 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
571 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
572 ConstantExpr::getCast(NewV, CI->getType()));
573 if (CI->use_empty()) {
574 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000575 CI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000576 }
577 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
578 // Should handle GEP here.
579 std::vector<Constant*> Indices;
580 Indices.reserve(GEPI->getNumOperands()-1);
581 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
582 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
583 Indices.push_back(C);
584 else
585 break;
586 if (Indices.size() == GEPI->getNumOperands()-1)
587 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
588 ConstantExpr::getGetElementPtr(NewV, Indices));
589 if (GEPI->use_empty()) {
590 Changed = true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000591 GEPI->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000592 }
593 }
594 }
595
596 return Changed;
597}
598
599
600/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
601/// value stored into it. If there are uses of the loaded value that would trap
602/// if the loaded value is dynamically null, then we know that they cannot be
603/// reachable with a null optimize away the load.
604static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
605 std::vector<LoadInst*> Loads;
606 bool Changed = false;
607
608 // Replace all uses of loads with uses of uses of the stored value.
609 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
610 GUI != E; ++GUI)
611 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
612 Loads.push_back(LI);
613 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
614 } else {
615 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
616 }
617
618 if (Changed) {
619 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
620 ++NumGlobUses;
621 }
622
623 // Delete all of the loads we can, keeping track of whether we nuked them all!
624 bool AllLoadsGone = true;
625 while (!Loads.empty()) {
626 LoadInst *L = Loads.back();
627 if (L->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000628 L->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000629 Changed = true;
630 } else {
631 AllLoadsGone = false;
632 }
633 Loads.pop_back();
634 }
635
636 // If we nuked all of the loads, then none of the stores are needed either,
637 // nor is the global.
638 if (AllLoadsGone) {
639 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
640 CleanupConstantGlobalUsers(GV, 0);
641 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000642 GV->eraseFromParent();
Chris Lattnere42eb312004-10-10 23:14:11 +0000643 ++NumDeleted;
644 }
645 Changed = true;
646 }
647 return Changed;
648}
649
Chris Lattner004e2502004-10-11 05:54:41 +0000650/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
651/// instructions that are foldable.
652static void ConstantPropUsersOf(Value *V) {
653 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
654 if (Instruction *I = dyn_cast<Instruction>(*UI++))
655 if (Constant *NewC = ConstantFoldInstruction(I)) {
656 I->replaceAllUsesWith(NewC);
657
Chris Lattnerd6a44922005-02-01 01:23:31 +0000658 // Advance UI to the next non-I use to avoid invalidating it!
659 // Instructions could multiply use V.
660 while (UI != E && *UI == I)
Chris Lattner004e2502004-10-11 05:54:41 +0000661 ++UI;
Chris Lattnerd6a44922005-02-01 01:23:31 +0000662 I->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000663 }
664}
665
666/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
667/// variable, and transforms the program as if it always contained the result of
668/// the specified malloc. Because it is always the result of the specified
669/// malloc, there is no reason to actually DO the malloc. Instead, turn the
670/// malloc into a global, and any laods of GV as uses of the new global.
671static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
672 MallocInst *MI) {
673 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
674 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
675
676 if (NElements->getRawValue() != 1) {
677 // If we have an array allocation, transform it to a single element
678 // allocation to make the code below simpler.
679 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Chris Lattner46fa04b2005-01-08 19:45:31 +0000680 (unsigned)NElements->getRawValue());
Chris Lattner004e2502004-10-11 05:54:41 +0000681 MallocInst *NewMI =
682 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
Nate Begeman848622f2005-11-05 09:21:28 +0000683 MI->getAlignment(), MI->getName(), MI);
Chris Lattner004e2502004-10-11 05:54:41 +0000684 std::vector<Value*> Indices;
685 Indices.push_back(Constant::getNullValue(Type::IntTy));
686 Indices.push_back(Indices[0]);
687 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
688 NewMI->getName()+".el0", MI);
689 MI->replaceAllUsesWith(NewGEP);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000690 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000691 MI = NewMI;
692 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000693
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000694 // Create the new global variable. The contents of the malloc'd memory is
695 // undefined, so initialize with an undef value.
696 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner004e2502004-10-11 05:54:41 +0000697 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
698 GlobalValue::InternalLinkage, Init,
699 GV->getName()+".body");
700 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000701
Chris Lattner004e2502004-10-11 05:54:41 +0000702 // Anything that used the malloc now uses the global directly.
703 MI->replaceAllUsesWith(NewGV);
Chris Lattner004e2502004-10-11 05:54:41 +0000704
705 Constant *RepValue = NewGV;
706 if (NewGV->getType() != GV->getType()->getElementType())
707 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
708
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000709 // If there is a comparison against null, we will insert a global bool to
710 // keep track of whether the global was initialized yet or not.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000711 GlobalVariable *InitBool =
712 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
Chris Lattner6ab03f62006-09-28 23:35:22 +0000713 ConstantBool::getFalse(), GV->getName()+".init");
Chris Lattner3b181392004-12-02 06:25:58 +0000714 bool InitBoolUsed = false;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000715
Chris Lattner004e2502004-10-11 05:54:41 +0000716 // Loop over all uses of GV, processing them in turn.
Chris Lattner3b181392004-12-02 06:25:58 +0000717 std::vector<StoreInst*> Stores;
Chris Lattner004e2502004-10-11 05:54:41 +0000718 while (!GV->use_empty())
719 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000720 while (!LI->use_empty()) {
Chris Lattnerd6a44922005-02-01 01:23:31 +0000721 Use &LoadUse = LI->use_begin().getUse();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000722 if (!isa<SetCondInst>(LoadUse.getUser()))
723 LoadUse = RepValue;
724 else {
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000725 // Replace the setcc X, 0 with a use of the bool value.
726 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
727 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattner3b181392004-12-02 06:25:58 +0000728 InitBoolUsed = true;
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000729 switch (SCI->getOpcode()) {
730 default: assert(0 && "Unknown opcode!");
731 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +0000732 LV = ConstantBool::getFalse(); // X < null -> always false
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000733 break;
734 case Instruction::SetEQ:
735 case Instruction::SetLE:
736 LV = BinaryOperator::createNot(LV, "notinit", SCI);
737 break;
738 case Instruction::SetNE:
739 case Instruction::SetGE:
740 case Instruction::SetGT:
741 break; // no change.
742 }
743 SCI->replaceAllUsesWith(LV);
744 SCI->eraseFromParent();
745 }
746 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000747 LI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000748 } else {
749 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattner3b181392004-12-02 06:25:58 +0000750 // The global is initialized when the store to it occurs.
Chris Lattner6ab03f62006-09-28 23:35:22 +0000751 new StoreInst(ConstantBool::getTrue(), InitBool, SI);
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000752 SI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000753 }
754
Chris Lattner3b181392004-12-02 06:25:58 +0000755 // If the initialization boolean was used, insert it, otherwise delete it.
756 if (!InitBoolUsed) {
757 while (!InitBool->use_empty()) // Delete initializations
758 cast<Instruction>(InitBool->use_back())->eraseFromParent();
759 delete InitBool;
760 } else
761 GV->getParent()->getGlobalList().insert(GV, InitBool);
762
763
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000764 // Now the GV is dead, nuke it and the malloc.
Chris Lattner8e71c6a2004-10-16 18:09:00 +0000765 GV->eraseFromParent();
Chris Lattnerfe9abf92004-10-22 06:43:28 +0000766 MI->eraseFromParent();
Chris Lattner004e2502004-10-11 05:54:41 +0000767
768 // To further other optimizations, loop over all users of NewGV and try to
769 // constant prop them. This will promote GEP instructions with constant
770 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
771 ConstantPropUsersOf(NewGV);
772 if (RepValue != NewGV)
773 ConstantPropUsersOf(RepValue);
774
775 return NewGV;
776}
Chris Lattnere42eb312004-10-10 23:14:11 +0000777
Chris Lattnerc0677c02004-12-02 07:11:07 +0000778/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
779/// to make sure that there are no complex uses of V. We permit simple things
780/// like dereferencing the pointer, but not storing through the address, unless
781/// it is to the specified global.
782static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
783 GlobalVariable *GV) {
784 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
785 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
786 // Fine, ignore.
787 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
788 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
789 return false; // Storing the pointer itself... bad.
790 // Otherwise, storing through it, or storing into GV... fine.
791 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
792 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
793 return false;
794 } else {
795 return false;
796 }
797 return true;
Chris Lattnerc0677c02004-12-02 07:11:07 +0000798}
799
Chris Lattner24d3d422006-09-30 23:32:09 +0000800/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
801/// somewhere. Transform all uses of the allocation into loads from the
802/// global and uses of the resultant pointer. Further, delete the store into
803/// GV. This assumes that these value pass the
804/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
805static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
806 GlobalVariable *GV) {
807 while (!Alloc->use_empty()) {
808 Instruction *U = Alloc->use_back();
809 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
810 // If this is the store of the allocation into the global, remove it.
811 if (SI->getOperand(1) == GV) {
812 SI->eraseFromParent();
813 continue;
814 }
815 }
816
817 // Insert a load from the global, and use it instead of the malloc.
818 Value *NL = new LoadInst(GV, GV->getName()+".val", U);
819 U->replaceUsesOfWith(Alloc, NL);
820 }
821}
822
823/// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
824/// GV are simple enough to perform HeapSRA, return true.
825static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
826 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
827 ++UI)
828 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
829 // We permit two users of the load: setcc comparing against the null
830 // pointer, and a getelementptr of a specific form.
831 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
832 ++UI) {
833 // Comparison against null is ok.
834 if (SetCondInst *SCI = dyn_cast<SetCondInst>(*UI)) {
835 if (!isa<ConstantPointerNull>(SCI->getOperand(1)))
836 return false;
837 continue;
838 }
839
840 // getelementptr is also ok, but only a simple form.
841 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
842 if (!GEPI) return false;
843
844 // Must index into the array and into the struct.
845 if (GEPI->getNumOperands() < 3)
846 return false;
847
848 // Otherwise the GEP is ok.
849 continue;
850 }
851 }
852 return true;
853}
854
855/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
856/// is a value loaded from the global. Eliminate all uses of Ptr, making them
857/// use FieldGlobals instead. All uses of loaded values satisfy
858/// GlobalLoadUsesSimpleEnoughForHeapSRA.
859static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr,
860 const std::vector<GlobalVariable*> &FieldGlobals) {
861 std::vector<Value *> InsertedLoadsForPtr;
862 //InsertedLoadsForPtr.resize(FieldGlobals.size());
863 while (!Ptr->use_empty()) {
864 Instruction *User = Ptr->use_back();
865
866 // If this is a comparison against null, handle it.
867 if (SetCondInst *SCI = dyn_cast<SetCondInst>(User)) {
868 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
869 // If we have a setcc of the loaded pointer, we can use a setcc of any
870 // field.
871 Value *NPtr;
872 if (InsertedLoadsForPtr.empty()) {
873 NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
874 InsertedLoadsForPtr.push_back(Ptr);
875 } else {
876 NPtr = InsertedLoadsForPtr.back();
877 }
878
879 Value *New = new SetCondInst(SCI->getOpcode(), NPtr,
880 Constant::getNullValue(NPtr->getType()),
881 SCI->getName(), SCI);
882 SCI->replaceAllUsesWith(New);
883 SCI->eraseFromParent();
884 continue;
885 }
886
887 // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
888 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
889 assert(GEPI->getNumOperands() >= 3 && isa<ConstantUInt>(GEPI->getOperand(2))
890 && "Unexpected GEPI!");
891
892 // Load the pointer for this field.
893 unsigned FieldNo = cast<ConstantUInt>(GEPI->getOperand(2))->getValue();
894 if (InsertedLoadsForPtr.size() <= FieldNo)
895 InsertedLoadsForPtr.resize(FieldNo+1);
896 if (InsertedLoadsForPtr[FieldNo] == 0)
897 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
898 Ptr->getName()+".f" +
899 utostr(FieldNo), Ptr);
900 Value *NewPtr = InsertedLoadsForPtr[FieldNo];
901
902 // Create the new GEP idx vector.
903 std::vector<Value*> GEPIdx;
904 GEPIdx.push_back(GEPI->getOperand(1));
905 GEPIdx.insert(GEPIdx.end(), GEPI->op_begin()+3, GEPI->op_end());
906
907 Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx, GEPI->getName(), GEPI);
908 GEPI->replaceAllUsesWith(NGEPI);
909 GEPI->eraseFromParent();
910 }
911}
912
913/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
914/// it up into multiple allocations of arrays of the fields.
915static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
916 /*DEBUG*/(std::cerr << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI);
917 const StructType *STy = cast<StructType>(MI->getAllocatedType());
918
919 // There is guaranteed to be at least one use of the malloc (storing
920 // it into GV). If there are other uses, change them to be uses of
921 // the global to simplify later code. This also deletes the store
922 // into GV.
923 ReplaceUsesOfMallocWithGlobal(MI, GV);
924
925 // Okay, at this point, there are no users of the malloc. Insert N
926 // new mallocs at the same place as MI, and N globals.
927 std::vector<GlobalVariable*> FieldGlobals;
928 std::vector<MallocInst*> FieldMallocs;
929
930 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
931 const Type *FieldTy = STy->getElementType(FieldNo);
932 const Type *PFieldTy = PointerType::get(FieldTy);
933
934 GlobalVariable *NGV =
935 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
936 Constant::getNullValue(PFieldTy),
937 GV->getName() + ".f" + utostr(FieldNo), GV);
938 FieldGlobals.push_back(NGV);
939
940 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
941 MI->getName() + ".f" + utostr(FieldNo),MI);
942 FieldMallocs.push_back(NMI);
943 new StoreInst(NMI, NGV, MI);
944 }
945
946 // The tricky aspect of this transformation is handling the case when malloc
947 // fails. In the original code, malloc failing would set the result pointer
948 // of malloc to null. In this case, some mallocs could succeed and others
949 // could fail. As such, we emit code that looks like this:
950 // F0 = malloc(field0)
951 // F1 = malloc(field1)
952 // F2 = malloc(field2)
953 // if (F0 == 0 || F1 == 0 || F2 == 0) {
954 // if (F0) { free(F0); F0 = 0; }
955 // if (F1) { free(F1); F1 = 0; }
956 // if (F2) { free(F2); F2 = 0; }
957 // }
958 Value *RunningOr = 0;
959 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
960 Value *Cond = new SetCondInst(Instruction::SetEQ, FieldMallocs[i],
961 Constant::getNullValue(FieldMallocs[i]->getType()),
962 "isnull", MI);
963 if (!RunningOr)
964 RunningOr = Cond; // First seteq
965 else
966 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
967 }
968
969 // Split the basic block at the old malloc.
970 BasicBlock *OrigBB = MI->getParent();
971 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
972
973 // Create the block to check the first condition. Put all these blocks at the
974 // end of the function as they are unlikely to be executed.
975 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
976 OrigBB->getParent());
977
978 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
979 // branch on RunningOr.
980 OrigBB->getTerminator()->eraseFromParent();
981 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
982
983 // Within the NullPtrBlock, we need to emit a comparison and branch for each
984 // pointer, because some may be null while others are not.
985 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
986 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
987 Value *Cmp = new SetCondInst(Instruction::SetNE, GVVal,
988 Constant::getNullValue(GVVal->getType()),
989 "tmp", NullPtrBlock);
990 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
991 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
992 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
993
994 // Fill in FreeBlock.
995 new FreeInst(GVVal, FreeBlock);
996 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
997 FreeBlock);
998 new BranchInst(NextBlock, FreeBlock);
999
1000 NullPtrBlock = NextBlock;
1001 }
1002
1003 new BranchInst(ContBB, NullPtrBlock);
1004
1005
1006 // MI is no longer needed, remove it.
1007 MI->eraseFromParent();
1008
1009
1010 // Okay, the malloc site is completely handled. All of the uses of GV are now
1011 // loads, and all uses of those loads are simple. Rewrite them to use loads
1012 // of the per-field globals instead.
1013 while (!GV->use_empty()) {
1014 LoadInst *LI = cast<LoadInst>(GV->use_back());
1015 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1016 LI->eraseFromParent();
1017 }
1018
1019 // The old global is now dead, remove it.
1020 GV->eraseFromParent();
1021
1022 ++NumHeapSRA;
1023 return FieldGlobals[0];
1024}
1025
1026
Chris Lattner09a52722004-10-09 21:48:45 +00001027// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1028// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001029static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001030 Module::global_iterator &GVI,
1031 TargetData &TD) {
Chris Lattner09a52722004-10-09 21:48:45 +00001032 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1033 StoredOnceVal = CI->getOperand(0);
1034 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattnere42eb312004-10-10 23:14:11 +00001035 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner09a52722004-10-09 21:48:45 +00001036 bool IsJustACast = true;
1037 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1038 if (!isa<Constant>(GEPI->getOperand(i)) ||
1039 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1040 IsJustACast = false;
1041 break;
1042 }
1043 if (IsJustACast)
1044 StoredOnceVal = GEPI->getOperand(0);
1045 }
1046
Chris Lattnere42eb312004-10-10 23:14:11 +00001047 // If we are dealing with a pointer global that is initialized to null and
1048 // only has one (non-null) value stored into it, then we can optimize any
1049 // users of the loaded value (often calls and loads) that would trap if the
1050 // value was null.
Chris Lattner09a52722004-10-09 21:48:45 +00001051 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1052 GV->getInitializer()->isNullValue()) {
Chris Lattnere42eb312004-10-10 23:14:11 +00001053 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1054 if (GV->getInitializer()->getType() != SOVC->getType())
1055 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001056
Chris Lattnere42eb312004-10-10 23:14:11 +00001057 // Optimize away any trapping uses of the loaded value.
1058 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner604ed7a2004-10-10 17:07:12 +00001059 return true;
Chris Lattner004e2502004-10-11 05:54:41 +00001060 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattner80a01ef2006-09-30 19:40:30 +00001061 // If this is a malloc of an abstract type, don't touch it.
1062 if (!MI->getAllocatedType()->isSized())
1063 return false;
1064
Chris Lattner24d3d422006-09-30 23:32:09 +00001065 // We can't optimize this global unless all uses of it are *known* to be
1066 // of the malloc value, not of the null initializer value (consider a use
1067 // that compares the global's value against zero to see if the malloc has
1068 // been reached). To do this, we check to see if all uses of the global
1069 // would trap if the global were null: this proves that they must all
1070 // happen after the malloc.
1071 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1072 return false;
1073
1074 // We can't optimize this if the malloc itself is used in a complex way,
1075 // for example, being stored into multiple globals. This allows the
1076 // malloc to be stored into the specified global, loaded setcc'd, and
1077 // GEP'd. These are all things we could transform to using the global
1078 // for.
1079 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1080 return false;
1081
1082
Chris Lattner004e2502004-10-11 05:54:41 +00001083 // If we have a global that is only initialized with a fixed size malloc,
Chris Lattner24d3d422006-09-30 23:32:09 +00001084 // transform the program to use global memory instead of malloc'd memory.
1085 // This eliminates dynamic allocation, avoids an indirection accessing the
1086 // data, and exposes the resultant global to further GlobalOpt.
Chris Lattner80a01ef2006-09-30 19:40:30 +00001087 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
Chris Lattner24d3d422006-09-30 23:32:09 +00001088 // Restrict this transformation to only working on small allocations
1089 // (2048 bytes currently), as we don't want to introduce a 16M global or
1090 // something.
Chris Lattner80a01ef2006-09-30 19:40:30 +00001091 if (NElements->getRawValue()*
Chris Lattner24d3d422006-09-30 23:32:09 +00001092 TD.getTypeSize(MI->getAllocatedType()) < 2048) {
Chris Lattner004e2502004-10-11 05:54:41 +00001093 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1094 return true;
1095 }
Chris Lattner80a01ef2006-09-30 19:40:30 +00001096 }
Chris Lattner24d3d422006-09-30 23:32:09 +00001097
1098 // If the allocation is an array of structures, consider transforming this
1099 // into multiple malloc'd arrays, one for each field. This is basically
1100 // SRoA for malloc'd memory.
1101 if (const StructType *AllocTy =
1102 dyn_cast<StructType>(MI->getAllocatedType())) {
1103 // This the structure has an unreasonable number of fields, leave it
1104 // alone.
1105 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1106 GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1107 GVI = PerformHeapAllocSRoA(GV, MI);
1108 return true;
1109 }
1110 }
Chris Lattnere42eb312004-10-10 23:14:11 +00001111 }
Chris Lattner09a52722004-10-09 21:48:45 +00001112 }
Chris Lattner004e2502004-10-11 05:54:41 +00001113
Chris Lattner09a52722004-10-09 21:48:45 +00001114 return false;
1115}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001116
Chris Lattner40e4cec2004-12-12 05:53:50 +00001117/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
Misha Brukmanb1c93172005-04-21 23:48:37 +00001118/// values ever stored into GV are its initializer and OtherVal.
Chris Lattner40e4cec2004-12-12 05:53:50 +00001119static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1120 // Create the new global, initializing it to false.
1121 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
Chris Lattner6ab03f62006-09-28 23:35:22 +00001122 GlobalValue::InternalLinkage, ConstantBool::getFalse(),
1123 GV->getName()+".b");
Chris Lattner40e4cec2004-12-12 05:53:50 +00001124 GV->getParent()->getGlobalList().insert(GV, NewGV);
1125
1126 Constant *InitVal = GV->getInitializer();
1127 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
1128
1129 // If initialized to zero and storing one into the global, we can use a cast
1130 // instead of a select to synthesize the desired value.
1131 bool IsOneZero = false;
1132 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1133 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
1134
1135 while (!GV->use_empty()) {
1136 Instruction *UI = cast<Instruction>(GV->use_back());
1137 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1138 // Change the store into a boolean store.
1139 bool StoringOther = SI->getOperand(0) == OtherVal;
1140 // Only do this if we weren't storing a loaded value.
Chris Lattner745196a2004-12-12 19:34:41 +00001141 Value *StoreVal;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001142 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner745196a2004-12-12 19:34:41 +00001143 StoreVal = ConstantBool::get(StoringOther);
1144 else {
1145 // Otherwise, we are storing a previously loaded copy. To do this,
1146 // change the copy from copying the original value to just copying the
1147 // bool.
1148 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1149
1150 // If we're already replaced the input, StoredVal will be a cast or
1151 // select instruction. If not, it will be a load of the original
1152 // global.
1153 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1154 assert(LI->getOperand(0) == GV && "Not a copy!");
1155 // Insert a new load, to preserve the saved value.
1156 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1157 } else {
1158 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1159 "This is not a form that we understand!");
1160 StoreVal = StoredVal->getOperand(0);
1161 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1162 }
1163 }
1164 new StoreInst(StoreVal, NewGV, SI);
1165 } else if (!UI->use_empty()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001166 // Change the load into a load of bool then a select.
1167 LoadInst *LI = cast<LoadInst>(UI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001168
Chris Lattner40e4cec2004-12-12 05:53:50 +00001169 std::string Name = LI->getName(); LI->setName("");
1170 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
1171 Value *NSI;
1172 if (IsOneZero)
1173 NSI = new CastInst(NLI, LI->getType(), Name, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001174 else
Chris Lattner40e4cec2004-12-12 05:53:50 +00001175 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
1176 LI->replaceAllUsesWith(NSI);
1177 }
1178 UI->eraseFromParent();
1179 }
1180
1181 GV->eraseFromParent();
1182}
1183
1184
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001185/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1186/// it if possible. If we make a change, return true.
Chris Lattner004e2502004-10-11 05:54:41 +00001187bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattner531f9e92005-03-15 04:54:21 +00001188 Module::global_iterator &GVI) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001189 std::set<PHINode*> PHIUsers;
1190 GlobalStatus GS;
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001191 GV->removeDeadConstantUsers();
1192
1193 if (GV->use_empty()) {
1194 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001195 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001196 ++NumDeleted;
1197 return true;
1198 }
1199
1200 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattner80a01ef2006-09-30 19:40:30 +00001201#if 0
1202 std::cerr << "Global: " << *GV;
1203 std::cerr << " isLoaded = " << GS.isLoaded << "\n";
1204 std::cerr << " StoredType = ";
1205 switch (GS.StoredType) {
1206 case GlobalStatus::NotStored: std::cerr << "NEVER STORED\n"; break;
1207 case GlobalStatus::isInitializerStored: std::cerr << "INIT STORED\n"; break;
1208 case GlobalStatus::isStoredOnce: std::cerr << "STORED ONCE\n"; break;
1209 case GlobalStatus::isStored: std::cerr << "stored\n"; break;
1210 }
1211 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1212 std::cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1213 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1214 std::cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1215 << "\n";
1216 std::cerr << " HasMultipleAccessingFunctions = "
1217 << GS.HasMultipleAccessingFunctions << "\n";
1218 std::cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1219 std::cerr << " isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1220 std::cerr << "\n";
1221#endif
1222
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001223 // If this is a first class global and has only one accessing function
1224 // and this function is main (which we know is not recursive we can make
1225 // this global a local variable) we replace the global with a local alloca
1226 // in this function.
1227 //
1228 // NOTE: It doesn't make sense to promote non first class types since we
1229 // are just replacing static memory to stack memory.
1230 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner50bdfcb2005-06-15 21:11:48 +00001231 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001232 GV->getType()->getElementType()->isFirstClassType() &&
1233 GS.AccessingFunction->getName() == "main" &&
1234 GS.AccessingFunction->hasExternalLinkage()) {
1235 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
1236 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1237 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman848622f2005-11-05 09:21:28 +00001238 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001239 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1240 if (!isa<UndefValue>(GV->getInitializer()))
1241 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001242
Alkis Evlogimenosc4a44c62005-02-10 18:36:30 +00001243 GV->replaceAllUsesWith(Alloca);
1244 GV->eraseFromParent();
1245 ++NumLocalized;
1246 return true;
1247 }
Chris Lattner80a01ef2006-09-30 19:40:30 +00001248
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001249 // If the global is never loaded (but may be stored to), it is dead.
1250 // Delete it now.
1251 if (!GS.isLoaded) {
1252 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
Chris Lattnerf369b382004-10-09 03:32:52 +00001253
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001254 // Delete any stores we can find to the global. We may not be able to
1255 // make it completely dead though.
Chris Lattnercb9f1522004-10-10 16:43:46 +00001256 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattnerf369b382004-10-09 03:32:52 +00001257
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001258 // If the global is dead now, delete it.
1259 if (GV->use_empty()) {
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001260 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001261 ++NumDeleted;
Chris Lattnerf369b382004-10-09 03:32:52 +00001262 Changed = true;
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001263 }
Chris Lattnerf369b382004-10-09 03:32:52 +00001264 return Changed;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001265
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001266 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1267 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
1268 GV->setConstant(true);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001269
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001270 // Clean up any obviously simplifiable users now.
1271 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001272
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001273 // If the global is dead now, just nuke it.
1274 if (GV->use_empty()) {
1275 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
1276 "all users and delete global!\n");
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001277 GV->eraseFromParent();
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001278 ++NumDeleted;
1279 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001280
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001281 ++NumMarked;
1282 return true;
1283 } else if (!GS.isNotSuitableForSRA &&
1284 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001285 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1286 GVI = FirstNewGV; // Don't skip the newly produced globals!
1287 return true;
1288 }
Chris Lattner09a52722004-10-09 21:48:45 +00001289 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001290 // If the initial value for the global was an undef value, and if only
1291 // one other value was stored into it, we can just change the
1292 // initializer to be an undef value, then delete all stores to the
1293 // global. This allows us to mark it constant.
1294 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1295 if (isa<UndefValue>(GV->getInitializer())) {
1296 // Change the initial value here.
1297 GV->setInitializer(SOVConstant);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001298
Chris Lattner40e4cec2004-12-12 05:53:50 +00001299 // Clean up any obviously simplifiable users now.
1300 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001301
Chris Lattner40e4cec2004-12-12 05:53:50 +00001302 if (GV->use_empty()) {
1303 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
1304 "simplify all users and delete global!\n");
1305 GV->eraseFromParent();
1306 ++NumDeleted;
1307 } else {
1308 GVI = GV;
1309 }
1310 ++NumSubstitute;
1311 return true;
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001312 }
Chris Lattner8e71c6a2004-10-16 18:09:00 +00001313
Chris Lattner09a52722004-10-09 21:48:45 +00001314 // Try to optimize globals based on the knowledge that only one value
1315 // (besides its initializer) is ever stored to the global.
Chris Lattner004e2502004-10-11 05:54:41 +00001316 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1317 getAnalysis<TargetData>()))
Chris Lattner09a52722004-10-09 21:48:45 +00001318 return true;
Chris Lattner40e4cec2004-12-12 05:53:50 +00001319
1320 // Otherwise, if the global was not a boolean, we can shrink it to be a
1321 // boolean.
1322 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner1cbd5be2004-12-12 06:03:06 +00001323 if (GV->getType()->getElementType() != Type::BoolTy &&
1324 !GV->getType()->getElementType()->isFloatingPoint()) {
Chris Lattner40e4cec2004-12-12 05:53:50 +00001325 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
1326 ShrinkGlobalToBoolean(GV, SOVConstant);
1327 ++NumShrunkToBool;
1328 return true;
1329 }
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001330 }
1331 }
1332 return false;
1333}
1334
Chris Lattnera4c80222005-05-08 22:18:06 +00001335/// OnlyCalledDirectly - Return true if the specified function is only called
1336/// directly. In other words, its address is never taken.
1337static bool OnlyCalledDirectly(Function *F) {
1338 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1339 Instruction *User = dyn_cast<Instruction>(*UI);
1340 if (!User) return false;
1341 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1342
1343 // See if the function address is passed as an argument.
1344 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1345 if (User->getOperand(i) == F) return false;
1346 }
1347 return true;
1348}
1349
1350/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1351/// function, changing them to FastCC.
1352static void ChangeCalleesToFastCall(Function *F) {
1353 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1354 Instruction *User = cast<Instruction>(*UI);
1355 if (CallInst *CI = dyn_cast<CallInst>(User))
1356 CI->setCallingConv(CallingConv::Fast);
1357 else
1358 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1359 }
1360}
Chris Lattner1c4bddc2004-10-08 20:59:28 +00001361
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001362bool GlobalOpt::OptimizeFunctions(Module &M) {
1363 bool Changed = false;
1364 // Optimize functions.
1365 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1366 Function *F = FI++;
1367 F->removeDeadConstantUsers();
1368 if (F->use_empty() && (F->hasInternalLinkage() ||
1369 F->hasLinkOnceLinkage())) {
1370 M.getFunctionList().erase(F);
1371 Changed = true;
1372 ++NumFnDeleted;
1373 } else if (F->hasInternalLinkage() &&
1374 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1375 OnlyCalledDirectly(F)) {
1376 // If this function has C calling conventions, is not a varargs
1377 // function, and is only called directly, promote it to use the Fast
1378 // calling convention.
1379 F->setCallingConv(CallingConv::Fast);
1380 ChangeCalleesToFastCall(F);
1381 ++NumFastCallFns;
1382 Changed = true;
1383 }
1384 }
1385 return Changed;
1386}
1387
1388bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1389 bool Changed = false;
1390 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1391 GVI != E; ) {
1392 GlobalVariable *GV = GVI++;
1393 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1394 GV->hasInitializer())
1395 Changed |= ProcessInternalGlobal(GV, GVI);
1396 }
1397 return Changed;
1398}
1399
1400/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1401/// initializers have an init priority of 65535.
1402GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenoscb67b652005-10-25 11:18:06 +00001403 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1404 I != E; ++I)
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001405 if (I->getName() == "llvm.global_ctors") {
1406 // Found it, verify it's an array of { int, void()* }.
1407 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1408 if (!ATy) return 0;
1409 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1410 if (!STy || STy->getNumElements() != 2 ||
1411 STy->getElementType(0) != Type::IntTy) return 0;
1412 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1413 if (!PFTy) return 0;
1414 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1415 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1416 FTy->getNumParams() != 0)
1417 return 0;
1418
1419 // Verify that the initializer is simple enough for us to handle.
1420 if (!I->hasInitializer()) return 0;
1421 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1422 if (!CA) return 0;
1423 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1424 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
Chris Lattner838bdc12005-09-26 02:19:27 +00001425 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1426 continue;
1427
1428 // Must have a function or null ptr.
1429 if (!isa<Function>(CS->getOperand(1)))
1430 return 0;
1431
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001432 // Init priority must be standard.
1433 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1434 if (!CI || CI->getRawValue() != 65535)
1435 return 0;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001436 } else {
1437 return 0;
1438 }
1439
1440 return I;
1441 }
1442 return 0;
1443}
1444
Chris Lattner696beef2005-09-26 02:31:18 +00001445/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1446/// return a list of the functions and null terminator as a vector.
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001447static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1448 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1449 std::vector<Function*> Result;
1450 Result.reserve(CA->getNumOperands());
1451 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1452 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1453 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1454 }
1455 return Result;
1456}
1457
Chris Lattner696beef2005-09-26 02:31:18 +00001458/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1459/// specified array, returning the new global to use.
1460static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1461 const std::vector<Function*> &Ctors) {
1462 // If we made a change, reassemble the initializer list.
1463 std::vector<Constant*> CSVals;
1464 CSVals.push_back(ConstantSInt::get(Type::IntTy, 65535));
1465 CSVals.push_back(0);
1466
1467 // Create the new init list.
1468 std::vector<Constant*> CAList;
1469 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001470 if (Ctors[i]) {
Chris Lattner696beef2005-09-26 02:31:18 +00001471 CSVals[1] = Ctors[i];
Chris Lattner99e23fa2005-09-26 04:44:35 +00001472 } else {
Chris Lattner696beef2005-09-26 02:31:18 +00001473 const Type *FTy = FunctionType::get(Type::VoidTy,
1474 std::vector<const Type*>(), false);
1475 const PointerType *PFTy = PointerType::get(FTy);
1476 CSVals[1] = Constant::getNullValue(PFTy);
1477 CSVals[0] = ConstantSInt::get(Type::IntTy, 2147483647);
1478 }
1479 CAList.push_back(ConstantStruct::get(CSVals));
1480 }
1481
1482 // Create the array initializer.
1483 const Type *StructTy =
1484 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1485 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1486 CAList);
1487
1488 // If we didn't change the number of elements, don't create a new GV.
1489 if (CA->getType() == GCL->getInitializer()->getType()) {
1490 GCL->setInitializer(CA);
1491 return GCL;
1492 }
1493
1494 // Create the new global and insert it next to the existing list.
1495 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1496 GCL->getLinkage(), CA,
1497 GCL->getName());
1498 GCL->setName("");
1499 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1500
1501 // Nuke the old list, replacing any uses with the new one.
1502 if (!GCL->use_empty()) {
1503 Constant *V = NGV;
1504 if (V->getType() != GCL->getType())
1505 V = ConstantExpr::getCast(V, GCL->getType());
1506 GCL->replaceAllUsesWith(V);
1507 }
1508 GCL->eraseFromParent();
1509
1510 if (Ctors.size())
1511 return NGV;
1512 else
1513 return 0;
1514}
Chris Lattner99e23fa2005-09-26 04:44:35 +00001515
1516
1517static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1518 Value *V) {
1519 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1520 Constant *R = ComputedValues[V];
1521 assert(R && "Reference to an uncomputed value!");
1522 return R;
1523}
1524
1525/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1526/// enough for us to understand. In particular, if it is a cast of something,
1527/// we punt. We basically just support direct accesses to globals and GEP's of
1528/// globals. This should be kept up to date with CommitValueTo.
1529static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner29b27802005-09-27 04:50:03 +00001530 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1531 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001532 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001533 return !GV->isExternal(); // reject external globals.
Chris Lattner29b27802005-09-27 04:50:03 +00001534 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001535 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1536 // Handle a constantexpr gep.
1537 if (CE->getOpcode() == Instruction::GetElementPtr &&
1538 isa<GlobalVariable>(CE->getOperand(0))) {
1539 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattner29b27802005-09-27 04:50:03 +00001540 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001541 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner46af55e2005-09-26 06:52:44 +00001542 return GV->hasInitializer() &&
1543 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1544 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001545 return false;
1546}
1547
Chris Lattner46af55e2005-09-26 06:52:44 +00001548/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1549/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1550/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1551static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1552 ConstantExpr *Addr, unsigned OpNo) {
1553 // Base case of the recursion.
1554 if (OpNo == Addr->getNumOperands()) {
1555 assert(Val->getType() == Init->getType() && "Type mismatch!");
1556 return Val;
1557 }
1558
1559 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1560 std::vector<Constant*> Elts;
1561
1562 // Break up the constant into its elements.
1563 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1564 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1565 Elts.push_back(CS->getOperand(i));
1566 } else if (isa<ConstantAggregateZero>(Init)) {
1567 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1568 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1569 } else if (isa<UndefValue>(Init)) {
1570 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1571 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1572 } else {
1573 assert(0 && "This code is out of sync with "
1574 " ConstantFoldLoadThroughGEPConstantExpr");
1575 }
1576
1577 // Replace the element that we are supposed to.
1578 ConstantUInt *CU = cast<ConstantUInt>(Addr->getOperand(OpNo));
1579 assert(CU->getValue() < STy->getNumElements() &&
1580 "Struct index out of range!");
1581 unsigned Idx = (unsigned)CU->getValue();
1582 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1583
1584 // Return the modified struct.
1585 return ConstantStruct::get(Elts);
1586 } else {
1587 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1588 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1589
1590 // Break up the array into elements.
1591 std::vector<Constant*> Elts;
1592 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1593 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1594 Elts.push_back(CA->getOperand(i));
1595 } else if (isa<ConstantAggregateZero>(Init)) {
1596 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1597 Elts.assign(ATy->getNumElements(), Elt);
1598 } else if (isa<UndefValue>(Init)) {
1599 Constant *Elt = UndefValue::get(ATy->getElementType());
1600 Elts.assign(ATy->getNumElements(), Elt);
1601 } else {
1602 assert(0 && "This code is out of sync with "
1603 " ConstantFoldLoadThroughGEPConstantExpr");
1604 }
1605
1606 assert((uint64_t)CI->getRawValue() < ATy->getNumElements());
1607 Elts[(uint64_t)CI->getRawValue()] =
1608 EvaluateStoreInto(Elts[(uint64_t)CI->getRawValue()], Val, Addr, OpNo+1);
1609 return ConstantArray::get(ATy, Elts);
1610 }
1611}
1612
Chris Lattner99e23fa2005-09-26 04:44:35 +00001613/// CommitValueTo - We have decided that Addr (which satisfies the predicate
1614/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1615static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner46af55e2005-09-26 06:52:44 +00001616 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1617 assert(GV->hasInitializer());
1618 GV->setInitializer(Val);
1619 return;
1620 }
1621
1622 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1623 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1624
1625 Constant *Init = GV->getInitializer();
1626 Init = EvaluateStoreInto(Init, Val, CE, 2);
1627 GV->setInitializer(Init);
Chris Lattner99e23fa2005-09-26 04:44:35 +00001628}
1629
Chris Lattnerb0096632005-09-26 05:16:34 +00001630/// ComputeLoadResult - Return the value that would be computed by a load from
1631/// P after the stores reflected by 'memory' have been performed. If we can't
1632/// decide, return null.
Chris Lattner4b05c322005-09-26 05:15:37 +00001633static Constant *ComputeLoadResult(Constant *P,
1634 const std::map<Constant*, Constant*> &Memory) {
1635 // If this memory location has been recently stored, use the stored value: it
1636 // is the most up-to-date.
1637 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1638 if (I != Memory.end()) return I->second;
1639
1640 // Access it.
1641 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1642 if (GV->hasInitializer())
1643 return GV->getInitializer();
1644 return 0;
Chris Lattner4b05c322005-09-26 05:15:37 +00001645 }
Chris Lattner46af55e2005-09-26 06:52:44 +00001646
1647 // Handle a constantexpr getelementptr.
1648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1649 if (CE->getOpcode() == Instruction::GetElementPtr &&
1650 isa<GlobalVariable>(CE->getOperand(0))) {
1651 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1652 if (GV->hasInitializer())
1653 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1654 }
1655
1656 return 0; // don't know how to evaluate.
Chris Lattner4b05c322005-09-26 05:15:37 +00001657}
1658
Chris Lattnerda1889b2005-09-27 04:27:01 +00001659/// EvaluateFunction - Evaluate a call to function F, returning true if
1660/// successful, false if we can't evaluate it. ActualArgs contains the formal
1661/// arguments for the function.
Chris Lattner65a3a092005-09-27 04:45:34 +00001662static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattnerda1889b2005-09-27 04:27:01 +00001663 const std::vector<Constant*> &ActualArgs,
1664 std::vector<Function*> &CallStack,
1665 std::map<Constant*, Constant*> &MutatedMemory,
1666 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001667 // Check to see if this function is already executing (recursion). If so,
1668 // bail out. TODO: we might want to accept limited recursion.
1669 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1670 return false;
1671
1672 CallStack.push_back(F);
1673
Chris Lattner99e23fa2005-09-26 04:44:35 +00001674 /// Values - As we compute SSA register values, we store their contents here.
1675 std::map<Value*, Constant*> Values;
Chris Lattner65a3a092005-09-27 04:45:34 +00001676
1677 // Initialize arguments to the incoming values specified.
1678 unsigned ArgNo = 0;
1679 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1680 ++AI, ++ArgNo)
1681 Values[AI] = ActualArgs[ArgNo];
Chris Lattnerda1889b2005-09-27 04:27:01 +00001682
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001683 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1684 /// we can only evaluate any one basic block at most once. This set keeps
1685 /// track of what we have executed so we can detect recursive cases etc.
1686 std::set<BasicBlock*> ExecutedBlocks;
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001687
Chris Lattner99e23fa2005-09-26 04:44:35 +00001688 // CurInst - The current instruction we're evaluating.
1689 BasicBlock::iterator CurInst = F->begin()->begin();
1690
1691 // This is the main evaluation loop.
1692 while (1) {
1693 Constant *InstResult = 0;
1694
1695 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001696 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner99e23fa2005-09-26 04:44:35 +00001697 Constant *Ptr = getVal(Values, SI->getOperand(1));
1698 if (!isSimpleEnoughPointerToCommit(Ptr))
1699 // If this is too complex for us to commit, reject it.
Chris Lattner65a3a092005-09-27 04:45:34 +00001700 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001701 Constant *Val = getVal(Values, SI->getOperand(0));
1702 MutatedMemory[Ptr] = Val;
1703 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1704 InstResult = ConstantExpr::get(BO->getOpcode(),
1705 getVal(Values, BO->getOperand(0)),
1706 getVal(Values, BO->getOperand(1)));
1707 } else if (ShiftInst *SI = dyn_cast<ShiftInst>(CurInst)) {
1708 InstResult = ConstantExpr::get(SI->getOpcode(),
1709 getVal(Values, SI->getOperand(0)),
1710 getVal(Values, SI->getOperand(1)));
1711 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1712 InstResult = ConstantExpr::getCast(getVal(Values, CI->getOperand(0)),
1713 CI->getType());
1714 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1715 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1716 getVal(Values, SI->getOperand(1)),
1717 getVal(Values, SI->getOperand(2)));
Chris Lattner4b05c322005-09-26 05:15:37 +00001718 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1719 Constant *P = getVal(Values, GEP->getOperand(0));
1720 std::vector<Constant*> GEPOps;
1721 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1722 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1723 InstResult = ConstantExpr::getGetElementPtr(P, GEPOps);
1724 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001725 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner4b05c322005-09-26 05:15:37 +00001726 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1727 MutatedMemory);
Chris Lattner65a3a092005-09-27 04:45:34 +00001728 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001729 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001730 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001731 const Type *Ty = AI->getType()->getElementType();
1732 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1733 GlobalValue::InternalLinkage,
1734 UndefValue::get(Ty),
1735 AI->getName()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001736 InstResult = AllocaTmps.back();
1737 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattnerfd2e13b2006-07-07 21:37:01 +00001738 // Cannot handle inline asm.
1739 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1740
Chris Lattner65a3a092005-09-27 04:45:34 +00001741 // Resolve function pointers.
1742 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1743 if (!Callee) return false; // Cannot resolve.
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001744
Chris Lattner65a3a092005-09-27 04:45:34 +00001745 std::vector<Constant*> Formals;
1746 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1747 Formals.push_back(getVal(Values, CI->getOperand(i)));
Chris Lattner65a3a092005-09-27 04:45:34 +00001748
Chris Lattner3d27e7f2005-09-27 05:02:43 +00001749 if (Callee->isExternal()) {
1750 // If this is a function we can constant fold, do it.
1751 if (Constant *C = ConstantFoldCall(Callee, Formals)) {
1752 InstResult = C;
1753 } else {
1754 return false;
1755 }
1756 } else {
1757 if (Callee->getFunctionType()->isVarArg())
1758 return false;
1759
1760 Constant *RetVal;
1761
1762 // Execute the call, if successful, use the return value.
1763 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1764 MutatedMemory, AllocaTmps))
1765 return false;
1766 InstResult = RetVal;
1767 }
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001768 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(CurInst)) {
1769 BasicBlock *NewBB = 0;
1770 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1771 if (BI->isUnconditional()) {
1772 NewBB = BI->getSuccessor(0);
1773 } else {
1774 ConstantBool *Cond =
1775 dyn_cast<ConstantBool>(getVal(Values, BI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001776 if (!Cond) return false; // Cannot determine.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001777 NewBB = BI->getSuccessor(!Cond->getValue());
1778 }
1779 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1780 ConstantInt *Val =
1781 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattner65a3a092005-09-27 04:45:34 +00001782 if (!Val) return false; // Cannot determine.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001783 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1784 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattner65a3a092005-09-27 04:45:34 +00001785 if (RI->getNumOperands())
1786 RetVal = getVal(Values, RI->getOperand(0));
1787
1788 CallStack.pop_back(); // return from fn.
Chris Lattnerda1889b2005-09-27 04:27:01 +00001789 return true; // We succeeded at evaluating this ctor!
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001790 } else {
Chris Lattner65a3a092005-09-27 04:45:34 +00001791 // invoke, unwind, unreachable.
1792 return false; // Cannot handle this terminator.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001793 }
1794
1795 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattner65a3a092005-09-27 04:45:34 +00001796 // executed the new block before. If so, we have a looping function,
1797 // which we cannot evaluate in reasonable time.
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001798 if (!ExecutedBlocks.insert(NewBB).second)
Chris Lattner65a3a092005-09-27 04:45:34 +00001799 return false; // looped!
Chris Lattner3e9ea5f2005-09-26 04:57:38 +00001800
1801 // Okay, we have never been in this block before. Check to see if there
1802 // are any PHI nodes. If so, evaluate them with information about where
1803 // we came from.
1804 BasicBlock *OldBB = CurInst->getParent();
1805 CurInst = NewBB->begin();
1806 PHINode *PN;
1807 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1808 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1809
1810 // Do NOT increment CurInst. We know that the terminator had no value.
1811 continue;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001812 } else {
Chris Lattner99e23fa2005-09-26 04:44:35 +00001813 // Did not know how to evaluate this!
Chris Lattner65a3a092005-09-27 04:45:34 +00001814 return false;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001815 }
1816
1817 if (!CurInst->use_empty())
1818 Values[CurInst] = InstResult;
1819
1820 // Advance program counter.
1821 ++CurInst;
1822 }
Chris Lattnerda1889b2005-09-27 04:27:01 +00001823}
1824
1825/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1826/// we can. Return true if we can, false otherwise.
1827static bool EvaluateStaticConstructor(Function *F) {
1828 /// MutatedMemory - For each store we execute, we update this map. Loads
1829 /// check this to get the most up-to-date value. If evaluation is successful,
1830 /// this state is committed to the process.
1831 std::map<Constant*, Constant*> MutatedMemory;
1832
1833 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1834 /// to represent its body. This vector is needed so we can delete the
1835 /// temporary globals when we are done.
1836 std::vector<GlobalVariable*> AllocaTmps;
1837
1838 /// CallStack - This is used to detect recursion. In pathological situations
1839 /// we could hit exponential behavior, but at least there is nothing
1840 /// unbounded.
1841 std::vector<Function*> CallStack;
1842
1843 // Call the function.
Chris Lattner65a3a092005-09-27 04:45:34 +00001844 Constant *RetValDummy;
1845 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1846 CallStack, MutatedMemory, AllocaTmps);
Chris Lattnerda1889b2005-09-27 04:27:01 +00001847 if (EvalSuccess) {
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001848 // We succeeded at evaluation: commit the result.
1849 DEBUG(std::cerr << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" <<
Chris Lattnerda1889b2005-09-27 04:27:01 +00001850 F->getName() << "' to " << MutatedMemory.size() << " stores.\n");
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001851 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1852 E = MutatedMemory.end(); I != E; ++I)
1853 CommitValueTo(I->second, I->first);
1854 }
Chris Lattner99e23fa2005-09-26 04:44:35 +00001855
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001856 // At this point, we are done interpreting. If we created any 'alloca'
1857 // temporaries, release them now.
1858 while (!AllocaTmps.empty()) {
1859 GlobalVariable *Tmp = AllocaTmps.back();
1860 AllocaTmps.pop_back();
Chris Lattnerda1889b2005-09-27 04:27:01 +00001861
Chris Lattner6bf2cd52005-09-26 17:07:09 +00001862 // If there are still users of the alloca, the program is doing something
1863 // silly, e.g. storing the address of the alloca somewhere and using it
1864 // later. Since this is undefined, we'll just make it be null.
1865 if (!Tmp->use_empty())
1866 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1867 delete Tmp;
1868 }
Chris Lattner46d9ff082005-09-26 07:34:35 +00001869
Chris Lattnerda1889b2005-09-27 04:27:01 +00001870 return EvalSuccess;
Chris Lattner99e23fa2005-09-26 04:44:35 +00001871}
1872
Chris Lattner696beef2005-09-26 02:31:18 +00001873
Chris Lattnerda1889b2005-09-27 04:27:01 +00001874
1875
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001876/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1877/// Return true if anything changed.
1878bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1879 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1880 bool MadeChange = false;
1881 if (Ctors.empty()) return false;
1882
1883 // Loop over global ctors, optimizing them when we can.
1884 for (unsigned i = 0; i != Ctors.size(); ++i) {
1885 Function *F = Ctors[i];
1886 // Found a null terminator in the middle of the list, prune off the rest of
1887 // the list.
Chris Lattner838bdc12005-09-26 02:19:27 +00001888 if (F == 0) {
1889 if (i != Ctors.size()-1) {
1890 Ctors.resize(i+1);
1891 MadeChange = true;
1892 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001893 break;
1894 }
1895
Chris Lattner99e23fa2005-09-26 04:44:35 +00001896 // We cannot simplify external ctor functions.
1897 if (F->empty()) continue;
1898
1899 // If we can evaluate the ctor at compile time, do.
1900 if (EvaluateStaticConstructor(F)) {
1901 Ctors.erase(Ctors.begin()+i);
1902 MadeChange = true;
1903 --i;
1904 ++NumCtorsEvaluated;
1905 continue;
1906 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001907 }
1908
1909 if (!MadeChange) return false;
1910
Chris Lattner696beef2005-09-26 02:31:18 +00001911 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001912 return true;
1913}
1914
1915
Chris Lattner25db5802004-10-07 04:16:33 +00001916bool GlobalOpt::runOnModule(Module &M) {
1917 bool Changed = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001918
1919 // Try to find the llvm.globalctors list.
1920 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001921
Chris Lattner25db5802004-10-07 04:16:33 +00001922 bool LocalChange = true;
1923 while (LocalChange) {
1924 LocalChange = false;
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001925
1926 // Delete functions that are trivially dead, ccc -> fastcc
1927 LocalChange |= OptimizeFunctions(M);
1928
1929 // Optimize global_ctors list.
1930 if (GlobalCtors)
1931 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1932
1933 // Optimize non-address-taken globals.
1934 LocalChange |= OptimizeGlobalVars(M);
Chris Lattner25db5802004-10-07 04:16:33 +00001935 Changed |= LocalChange;
1936 }
Chris Lattner41b6a5a2005-09-26 01:43:45 +00001937
1938 // TODO: Move all global ctors functions to the end of the module for code
1939 // layout.
1940
Chris Lattner25db5802004-10-07 04:16:33 +00001941 return Changed;
1942}